/*!--------------------------------------------------------
 * Copyright (C) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------*//******************************************************************************
Copyright (c) Microsoft Corporation.

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

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

export function __extends(d, b) {
    if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

export var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    }
    return __assign.apply(this, arguments);
}

export function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

export function __decorate(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;
}

export function __param(paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
}

export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};

export function __runInitializers(thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};

export function __propKey(x) {
    return typeof x === "symbol" ? x : "".concat(x);
};

export function __setFunctionName(f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};

export function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

export function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

export function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

export var __createBinding = Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
});

export function __exportStar(m, o) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}

export function __values(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

export function __read(o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
}

/** @deprecated */
export function __spread() {
    for (var ar = [], i = 0; i < arguments.length; i++)
        ar = ar.concat(__read(arguments[i]));
    return ar;
}

/** @deprecated */
export function __spreadArrays() {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
}

export function __spreadArray(to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
}

export function __await(v) {
    return this instanceof __await ? (this.v = v, this) : new __await(v);
}

export function __asyncGenerator(thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

export function __asyncDelegator(o) {
    var i, p;
    return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}

export function __asyncValues(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(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

export function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

var __setModuleDefault = Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
};

export function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
}

export function __importDefault(mod) {
    return (mod && mod.__esModule) ? mod : { default: mod };
}

export function __classPrivateFieldGet(receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

export function __classPrivateFieldSet(receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}

export function __classPrivateFieldIn(state, receiver) {
    if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
    return typeof state === "function" ? receiver === state : state.has(receiver);
}

export function __addDisposableResource(env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;

}

var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

export function __disposeResources(env) {
    function fail(e) {
        env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
        env.hasError = true;
    }
    function next() {
        while (env.stack.length) {
            var rec = env.stack.pop();
            try {
                var result = rec.dispose && rec.dispose.call(rec.value);
                if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
            }
            catch (e) {
                fail(e);
            }
        }
        if (env.hasError) throw env.error;
    }
    return next();
}

export default {
    __extends: __extends,
    __assign: __assign,
    __rest: __rest,
    __decorate: __decorate,
    __param: __param,
    __metadata: __metadata,
    __awaiter: __awaiter,
    __generator: __generator,
    __createBinding: __createBinding,
    __exportStar: __exportStar,
    __values: __values,
    __read: __read,
    __spread: __spread,
    __spreadArrays: __spreadArrays,
    __spreadArray: __spreadArray,
    __await: __await,
    __asyncGenerator: __asyncGenerator,
    __asyncDelegator: __asyncDelegator,
    __asyncValues: __asyncValues,
    __makeTemplateObject: __makeTemplateObject,
    __importStar: __importStar,
    __importDefault: __importDefault,
    __classPrivateFieldGet: __classPrivateFieldGet,
    __classPrivateFieldSet: __classPrivateFieldSet,
    __classPrivateFieldIn: __classPrivateFieldIn,
    __addDisposableResource: __addDisposableResource,
    __disposeResources: __disposeResources,
};

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

// node_modules/minimist/index.js
var require_minimist = __commonJS({
  "node_modules/minimist/index.js"(exports2, module2) {
    "use strict";
    function hasKey(obj, keys) {
      var o = obj;
      keys.slice(0, -1).forEach(function(key2) {
        o = o[key2] || {};
      });
      var key = keys[keys.length - 1];
      return key in o;
    }
    function isNumber2(x) {
      if (typeof x === "number") {
        return true;
      }
      if (/^0x[0-9a-f]+$/i.test(x)) {
        return true;
      }
      return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
    }
    function isConstructorOrProto(obj, key) {
      return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
    }
    module2.exports = function(args2, opts) {
      if (!opts) {
        opts = {};
      }
      var flags = {
        bools: {},
        strings: {},
        unknownFn: null
      };
      if (typeof opts.unknown === "function") {
        flags.unknownFn = opts.unknown;
      }
      if (typeof opts.boolean === "boolean" && opts.boolean) {
        flags.allBools = true;
      } else {
        [].concat(opts.boolean).filter(Boolean).forEach(function(key2) {
          flags.bools[key2] = true;
        });
      }
      var aliases = {};
      function aliasIsBoolean(key2) {
        return aliases[key2].some(function(x) {
          return flags.bools[x];
        });
      }
      Object.keys(opts.alias || {}).forEach(function(key2) {
        aliases[key2] = [].concat(opts.alias[key2]);
        aliases[key2].forEach(function(x) {
          aliases[x] = [key2].concat(aliases[key2].filter(function(y) {
            return x !== y;
          }));
        });
      });
      [].concat(opts.string).filter(Boolean).forEach(function(key2) {
        flags.strings[key2] = true;
        if (aliases[key2]) {
          [].concat(aliases[key2]).forEach(function(k) {
            flags.strings[k] = true;
          });
        }
      });
      var defaults = opts.default || {};
      var argv = { _: [] };
      function argDefined(key2, arg2) {
        return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
      }
      function setKey(obj, keys, value2) {
        var o = obj;
        for (var i2 = 0; i2 < keys.length - 1; i2++) {
          var key2 = keys[i2];
          if (isConstructorOrProto(o, key2)) {
            return;
          }
          if (o[key2] === void 0) {
            o[key2] = {};
          }
          if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype) {
            o[key2] = {};
          }
          if (o[key2] === Array.prototype) {
            o[key2] = [];
          }
          o = o[key2];
        }
        var lastKey = keys[keys.length - 1];
        if (isConstructorOrProto(o, lastKey)) {
          return;
        }
        if (o === Object.prototype || o === Number.prototype || o === String.prototype) {
          o = {};
        }
        if (o === Array.prototype) {
          o = [];
        }
        if (o[lastKey] === void 0 || flags.bools[lastKey] || typeof o[lastKey] === "boolean") {
          o[lastKey] = value2;
        } else if (Array.isArray(o[lastKey])) {
          o[lastKey].push(value2);
        } else {
          o[lastKey] = [o[lastKey], value2];
        }
      }
      function setArg(key2, val, arg2) {
        if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
          if (flags.unknownFn(arg2) === false) {
            return;
          }
        }
        var value2 = !flags.strings[key2] && isNumber2(val) ? Number(val) : val;
        setKey(argv, key2.split("."), value2);
        (aliases[key2] || []).forEach(function(x) {
          setKey(argv, x.split("."), value2);
        });
      }
      Object.keys(flags.bools).forEach(function(key2) {
        setArg(key2, defaults[key2] === void 0 ? false : defaults[key2]);
      });
      var notFlags = [];
      if (args2.indexOf("--") !== -1) {
        notFlags = args2.slice(args2.indexOf("--") + 1);
        args2 = args2.slice(0, args2.indexOf("--"));
      }
      for (var i = 0; i < args2.length; i++) {
        var arg = args2[i];
        var key;
        var next;
        if (/^--.+=/.test(arg)) {
          var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
          key = m[1];
          var value = m[2];
          if (flags.bools[key]) {
            value = value !== "false";
          }
          setArg(key, value, arg);
        } else if (/^--no-.+/.test(arg)) {
          key = arg.match(/^--no-(.+)/)[1];
          setArg(key, false, arg);
        } else if (/^--.+/.test(arg)) {
          key = arg.match(/^--(.+)/)[1];
          next = args2[i + 1];
          if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
            setArg(key, next, arg);
            i += 1;
          } else if (/^(true|false)$/.test(next)) {
            setArg(key, next === "true", arg);
            i += 1;
          } else {
            setArg(key, flags.strings[key] ? "" : true, arg);
          }
        } else if (/^-[^-]+/.test(arg)) {
          var letters = arg.slice(1, -1).split("");
          var broken = false;
          for (var j = 0; j < letters.length; j++) {
            next = arg.slice(j + 2);
            if (next === "-") {
              setArg(letters[j], next, arg);
              continue;
            }
            if (/[A-Za-z]/.test(letters[j]) && next[0] === "=") {
              setArg(letters[j], next.slice(1), arg);
              broken = true;
              break;
            }
            if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
              setArg(letters[j], next, arg);
              broken = true;
              break;
            }
            if (letters[j + 1] && letters[j + 1].match(/\W/)) {
              setArg(letters[j], arg.slice(j + 2), arg);
              broken = true;
              break;
            } else {
              setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
            }
          }
          key = arg.slice(-1)[0];
          if (!broken && key !== "-") {
            if (args2[i + 1] && !/^(-|--)[^-]/.test(args2[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, args2[i + 1], arg);
              i += 1;
            } else if (args2[i + 1] && /^(true|false)$/.test(args2[i + 1])) {
              setArg(key, args2[i + 1] === "true", arg);
              i += 1;
            } else {
              setArg(key, flags.strings[key] ? "" : true, arg);
            }
          }
        } else {
          if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
            argv._.push(flags.strings._ || !isNumber2(arg) ? arg : Number(arg));
          }
          if (opts.stopEarly) {
            argv._.push.apply(argv._, args2.slice(i + 1));
            break;
          }
        }
      }
      Object.keys(defaults).forEach(function(k) {
        if (!hasKey(argv, k.split("."))) {
          setKey(argv, k.split("."), defaults[k]);
          (aliases[k] || []).forEach(function(x) {
            setKey(argv, x.split("."), defaults[k]);
          });
        }
      });
      if (opts["--"]) {
        argv["--"] = notFlags.slice();
      } else {
        notFlags.forEach(function(k) {
          argv._.push(k);
        });
      }
      return argv;
    };
  }
});

// out-build/vs/workbench/api/node/extensionHostProcess.js
var import_minimist2 = __toESM(require_minimist(), 1);
import * as net5 from "net";

// out-build/vs/base/common/collections.js
var _a;
function $a(data, groupFn) {
  const result = /* @__PURE__ */ Object.create(null);
  for (const element of data) {
    const key = groupFn(element);
    let target = result[key];
    if (!target) {
      target = result[key] = [];
    }
    target.push(element);
  }
  return result;
}
function $b(before, after) {
  const removed = [];
  const added = [];
  for (const element of before) {
    if (!after.has(element)) {
      removed.push(element);
    }
  }
  for (const element of after) {
    if (!before.has(element)) {
      added.push(element);
    }
  }
  return { removed, added };
}
var $e = class {
  static {
    _a = Symbol.toStringTag;
  }
  constructor(values, b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
    this[_a] = "SetWithKey";
    for (const value of values) {
      this.add(value);
    }
  }
  get size() {
    return this.a.size;
  }
  add(value) {
    const key = this.b(value);
    this.a.set(key, value);
    return this;
  }
  delete(value) {
    return this.a.delete(this.b(value));
  }
  has(value) {
    return this.a.has(this.b(value));
  }
  *entries() {
    for (const entry of this.a.values()) {
      yield [entry, entry];
    }
  }
  keys() {
    return this.values();
  }
  *values() {
    for (const entry of this.a.values()) {
      yield entry;
    }
  }
  clear() {
    this.a.clear();
  }
  forEach(callbackfn, thisArg) {
    this.a.forEach((entry) => callbackfn.call(thisArg, entry, entry, this));
  }
  [Symbol.iterator]() {
    return this.values();
  }
};

// out-build/vs/base/common/errors.js
var $bb = class {
  constructor() {
    this.b = [];
    this.a = function(e) {
      setTimeout(() => {
        if (e.stack) {
          if ($ub.isErrorNoTelemetry(e)) {
            throw new $ub(e.message + "\n\n" + e.stack);
          }
          throw new Error(e.message + "\n\n" + e.stack);
        }
        throw e;
      }, 0);
    };
  }
  addListener(listener) {
    this.b.push(listener);
    return () => {
      this.d(listener);
    };
  }
  c(e) {
    this.b.forEach((listener) => {
      listener(e);
    });
  }
  d(listener) {
    this.b.splice(this.b.indexOf(listener), 1);
  }
  setUnexpectedErrorHandler(newUnexpectedErrorHandler) {
    this.a = newUnexpectedErrorHandler;
  }
  getUnexpectedErrorHandler() {
    return this.a;
  }
  onUnexpectedError(e) {
    this.a(e);
    this.c(e);
  }
  // For external errors, we don't want the listeners to be called
  onUnexpectedExternalError(e) {
    this.a(e);
  }
};
var $cb = new $bb();
function setUnexpectedErrorHandler(newUnexpectedErrorHandler) {
  $cb.setUnexpectedErrorHandler(newUnexpectedErrorHandler);
}
function $eb(e) {
  if (!e || typeof e !== "object") {
    return false;
  }
  const cast = e;
  return cast.code === "EPIPE" && cast.syscall?.toUpperCase() === "WRITE";
}
function $fb(e) {
  $cb.onUnexpectedError(e);
  return void 0;
}
function $gb(e) {
  if (!$kb(e)) {
    $cb.onUnexpectedError(e);
  }
  return void 0;
}
function $hb(e) {
  if (!$kb(e)) {
    $cb.onUnexpectedExternalError(e);
  }
  return void 0;
}
function $ib(error) {
  if (error instanceof Error) {
    const { name, message } = error;
    const stack = error.stacktrace || error.stack;
    return {
      $isError: true,
      name,
      message,
      stack,
      noTelemetry: $ub.isErrorNoTelemetry(error)
    };
  }
  return error;
}
function $jb(data) {
  let error;
  if (data.noTelemetry) {
    error = new $ub();
  } else {
    error = new Error();
    error.name = data.name;
  }
  error.message = data.message;
  error.stack = data.stack;
  return error;
}
var canceledName = "Canceled";
function $kb(error) {
  if (error instanceof $lb) {
    return true;
  }
  return error instanceof Error && error.name === canceledName && error.message === canceledName;
}
var $lb = class extends Error {
  constructor() {
    super(canceledName);
    this.name = this.message;
  }
};
function $mb() {
  const error = new Error(canceledName);
  error.name = error.message;
  return error;
}
function $nb(name) {
  if (name) {
    return new Error(`Illegal argument: ${name}`);
  } else {
    return new Error("Illegal argument");
  }
}
function $ob(name) {
  if (name) {
    return new Error(`Illegal state: ${name}`);
  } else {
    return new Error("Illegal state");
  }
}
var $pb = class extends TypeError {
  constructor(name) {
    super(name ? `${name} is read-only and cannot be changed` : "Cannot change read-only property");
  }
};
function $qb(err) {
  if (!err) {
    return "Error";
  }
  if (err.message) {
    return err.message;
  }
  if (err.stack) {
    return err.stack.split("\n")[0];
  }
  return String(err);
}
var $rb = class extends Error {
  constructor(message) {
    super("NotImplemented");
    if (message) {
      this.message = message;
    }
  }
};
var $sb = class extends Error {
  constructor(message) {
    super("NotSupported");
    if (message) {
      this.message = message;
    }
  }
};
var $ub = class _$ub extends Error {
  constructor(msg) {
    super(msg);
    this.name = "CodeExpectedError";
  }
  static fromError(err) {
    if (err instanceof _$ub) {
      return err;
    }
    const result = new _$ub();
    result.message = err.message;
    result.stack = err.stack;
    return result;
  }
  static isErrorNoTelemetry(err) {
    return err.name === "CodeExpectedError";
  }
};
var $vb = class _$vb extends Error {
  constructor(message) {
    super(message || "An unexpected bug occurred.");
    Object.setPrototypeOf(this, _$vb.prototype);
  }
};

// out-build/vs/base/common/functional.js
function $Qc(fn, fnDidRunCallback) {
  const _this = this;
  let didCall = false;
  let result;
  return function() {
    if (didCall) {
      return result;
    }
    didCall = true;
    if (fnDidRunCallback) {
      try {
        result = fn.apply(_this, arguments);
      } finally {
        fnDidRunCallback();
      }
    } else {
      result = fn.apply(_this, arguments);
    }
    return result;
  };
}

// out-build/vs/base/common/arraysFind.js
function $1(array, predicate) {
  const idx = $2(array, predicate);
  if (idx === -1) {
    return void 0;
  }
  return array[idx];
}
function $2(array, predicate, fromIndex = array.length - 1) {
  for (let i = fromIndex; i >= 0; i--) {
    const element = array[i];
    if (predicate(element)) {
      return i;
    }
  }
  return -1;
}
function $4(array, predicate, startIdx = 0, endIdxEx = array.length) {
  let i = startIdx;
  let j = endIdxEx;
  while (i < j) {
    const k = Math.floor((i + j) / 2);
    if (predicate(array[k])) {
      i = k + 1;
    } else {
      j = k;
    }
  }
  return i - 1;
}
function $6(array, predicate, startIdx = 0, endIdxEx = array.length) {
  let i = startIdx;
  let j = endIdxEx;
  while (i < j) {
    const k = Math.floor((i + j) / 2);
    if (predicate(array[k])) {
      j = k;
    } else {
      i = k + 1;
    }
  }
  return i;
}
var $8 = class _$8 {
  static {
    this.assertInvariants = false;
  }
  constructor(e) {
    this.e = e;
    this.c = 0;
  }
  /**
   * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
   * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`.
   */
  findLastMonotonous(predicate) {
    if (_$8.assertInvariants) {
      if (this.d) {
        for (const item of this.e) {
          if (this.d(item) && !predicate(item)) {
            throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.");
          }
        }
      }
      this.d = predicate;
    }
    const idx = $4(this.e, predicate, this.c);
    this.c = idx + 1;
    return idx === -1 ? void 0 : this.e[idx];
  }
};

// out-build/vs/base/common/arrays.js
function $zb(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 $Eb(data, compare3) {
  const result = [];
  let currentGroup = void 0;
  for (const element of data.slice(0).sort(compare3)) {
    if (!currentGroup || compare3(currentGroup[0], element) !== 0) {
      currentGroup = [element];
      result.push(currentGroup);
    } else {
      currentGroup.push(element);
    }
  }
  return result;
}
function $Ib(before, after, compare3) {
  const result = [];
  function pushSplice(start, deleteCount, toInsert) {
    if (deleteCount === 0 && toInsert.length === 0) {
      return;
    }
    const latest = result[result.length - 1];
    if (latest && latest.start + latest.deleteCount === start) {
      latest.deleteCount += deleteCount;
      latest.toInsert.push(...toInsert);
    } else {
      result.push({ start, deleteCount, toInsert });
    }
  }
  let beforeIdx = 0;
  let afterIdx = 0;
  while (true) {
    if (beforeIdx === before.length) {
      pushSplice(beforeIdx, 0, after.slice(afterIdx));
      break;
    }
    if (afterIdx === after.length) {
      pushSplice(beforeIdx, before.length - beforeIdx, []);
      break;
    }
    const beforeElement = before[beforeIdx];
    const afterElement = after[afterIdx];
    const n = compare3(beforeElement, afterElement);
    if (n === 0) {
      beforeIdx += 1;
      afterIdx += 1;
    } else if (n < 0) {
      pushSplice(beforeIdx, 1, []);
      beforeIdx += 1;
    } else if (n > 0) {
      pushSplice(beforeIdx, 0, [afterElement]);
      afterIdx += 1;
    }
  }
  return result;
}
function $Jb(before, after, compare3) {
  const splices = $Ib(before, after, compare3);
  const removed = [];
  const added = [];
  for (const splice of splices) {
    removed.push(...before.slice(splice.start, splice.start + splice.deleteCount));
    added.push(...splice.toInsert);
  }
  return { removed, added };
}
function $Lb(array, compare3, n, batch, token) {
  if (n === 0) {
    return Promise.resolve([]);
  }
  return new Promise((resolve, reject) => {
    (async () => {
      const o = array.length;
      const result = array.slice(0, n).sort(compare3);
      for (let i = n, m = Math.min(n + batch, o); i < o; i = m, m = Math.min(m + batch, o)) {
        if (i > n) {
          await new Promise((resolve2) => setTimeout(resolve2));
        }
        if (token && token.isCancellationRequested) {
          throw new $lb();
        }
        topStep(array, compare3, result, i, m);
      }
      return result;
    })().then(resolve, reject);
  });
}
function topStep(array, compare3, result, i, m) {
  for (const n = result.length; i < m; i++) {
    const element = array[i];
    if (compare3(element, result[n - 1]) < 0) {
      result.pop();
      const j = $6(result, (e) => compare3(element, e) < 0);
      result.splice(j, 0, element);
    }
  }
}
function $Mb(array) {
  return array.filter((e) => !!e);
}
function $Nb(array) {
  let to = 0;
  for (let i = 0; i < array.length; i++) {
    if (!!array[i]) {
      array[to] = array[i];
      to += 1;
    }
  }
  array.length = to;
}
function $Pb(obj) {
  return !Array.isArray(obj) || obj.length === 0;
}
function $Qb(obj) {
  return Array.isArray(obj) && obj.length > 0;
}
function $Rb(array, keyFn = (value) => value) {
  const seen = /* @__PURE__ */ new Set();
  return array.filter((element) => {
    const key = keyFn(element);
    if (seen.has(key)) {
      return false;
    }
    seen.add(key);
    return true;
  });
}
function $Wb(array, element) {
  array.push(element);
  return () => $Xb(array, element);
}
function $Xb(array, element) {
  const index = array.indexOf(element);
  if (index > -1) {
    array.splice(index, 1);
    return element;
  }
  return void 0;
}
function $Zb(array, _seed) {
  let rand;
  if (typeof _seed === "number") {
    let seed = _seed;
    rand = () => {
      const x = Math.sin(seed++) * 179426549;
      return x - Math.floor(x);
    };
  } else {
    rand = Math.random;
  }
  for (let i = array.length - 1; i > 0; i -= 1) {
    const j = Math.floor(rand() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}
function $4b(items, fn) {
  return Array.isArray(items) ? items.map(fn) : fn(items);
}
function $5b(x) {
  return Array.isArray(x) ? x : [x];
}
var CompareResult;
(function(CompareResult2) {
  function isLessThan(result) {
    return result < 0;
  }
  CompareResult2.isLessThan = isLessThan;
  function isLessThanOrEqual(result) {
    return result <= 0;
  }
  CompareResult2.isLessThanOrEqual = isLessThanOrEqual;
  function isGreaterThan(result) {
    return result > 0;
  }
  CompareResult2.isGreaterThan = isGreaterThan;
  function isNeitherLessOrGreaterThan(result) {
    return result === 0;
  }
  CompareResult2.isNeitherLessOrGreaterThan = isNeitherLessOrGreaterThan;
  CompareResult2.greaterThan = 1;
  CompareResult2.lessThan = -1;
  CompareResult2.neitherLessOrGreaterThan = 0;
})(CompareResult || (CompareResult = {}));
function $9b(selector, comparator) {
  return (a, b) => comparator(selector(a), selector(b));
}
var $$b = (a, b) => a - b;
var $cc = class _$cc {
  static {
    this.empty = new _$cc((_callback) => {
    });
  }
  constructor(iterate) {
    this.iterate = iterate;
  }
  forEach(handler) {
    this.iterate((item) => {
      handler(item);
      return true;
    });
  }
  toArray() {
    const result = [];
    this.iterate((item) => {
      result.push(item);
      return true;
    });
    return result;
  }
  filter(predicate) {
    return new _$cc((cb) => this.iterate((item) => predicate(item) ? cb(item) : true));
  }
  map(mapFn) {
    return new _$cc((cb) => this.iterate((item) => cb(mapFn(item))));
  }
  some(predicate) {
    let result = false;
    this.iterate((item) => {
      result = predicate(item);
      return !result;
    });
    return result;
  }
  findFirst(predicate) {
    let result;
    this.iterate((item) => {
      if (predicate(item)) {
        result = item;
        return false;
      }
      return true;
    });
    return result;
  }
  findLast(predicate) {
    let result;
    this.iterate((item) => {
      if (predicate(item)) {
        result = item;
      }
      return true;
    });
    return result;
  }
  findLastMaxBy(comparator) {
    let result;
    let first = true;
    this.iterate((item) => {
      if (first || CompareResult.isGreaterThan(comparator(item, result))) {
        first = false;
        result = item;
      }
      return true;
    });
    return result;
  }
};

// out-build/vs/base/common/map.js
var _a2;
var _b;
var _c;
function $Bc(map, key, value) {
  let result = map.get(key);
  if (result === void 0) {
    result = value;
    map.set(key, result);
  }
  return result;
}
var ResourceMapEntry = class {
  constructor(uri, value) {
    this.uri = uri;
    this.value = value;
  }
};
function isEntries(arg) {
  return Array.isArray(arg);
}
var $Ec = class _$Ec {
  static {
    this.c = (resource) => resource.toString();
  }
  constructor(arg, toKey) {
    this[_a2] = "ResourceMap";
    if (arg instanceof _$Ec) {
      this.d = new Map(arg.d);
      this.e = toKey ?? _$Ec.c;
    } else if (isEntries(arg)) {
      this.d = /* @__PURE__ */ new Map();
      this.e = toKey ?? _$Ec.c;
      for (const [resource, value] of arg) {
        this.set(resource, value);
      }
    } else {
      this.d = /* @__PURE__ */ new Map();
      this.e = arg ?? _$Ec.c;
    }
  }
  set(resource, value) {
    this.d.set(this.e(resource), new ResourceMapEntry(resource, value));
    return this;
  }
  get(resource) {
    return this.d.get(this.e(resource))?.value;
  }
  has(resource) {
    return this.d.has(this.e(resource));
  }
  get size() {
    return this.d.size;
  }
  clear() {
    this.d.clear();
  }
  delete(resource) {
    return this.d.delete(this.e(resource));
  }
  forEach(clb, thisArg) {
    if (typeof thisArg !== "undefined") {
      clb = clb.bind(thisArg);
    }
    for (const [_, entry] of this.d) {
      clb(entry.value, entry.uri, this);
    }
  }
  *values() {
    for (const entry of this.d.values()) {
      yield entry.value;
    }
  }
  *keys() {
    for (const entry of this.d.values()) {
      yield entry.uri;
    }
  }
  *entries() {
    for (const entry of this.d.values()) {
      yield [entry.uri, entry.value];
    }
  }
  *[(_a2 = Symbol.toStringTag, Symbol.iterator)]() {
    for (const [, entry] of this.d) {
      yield [entry.uri, entry.value];
    }
  }
};
var $Fc = class {
  constructor(entriesOrKey, toKey) {
    this[_b] = "ResourceSet";
    if (!entriesOrKey || typeof entriesOrKey === "function") {
      this.c = new $Ec(entriesOrKey);
    } else {
      this.c = new $Ec(toKey);
      entriesOrKey.forEach(this.add, this);
    }
  }
  get size() {
    return this.c.size;
  }
  add(value) {
    this.c.set(value, value);
    return this;
  }
  clear() {
    this.c.clear();
  }
  delete(value) {
    return this.c.delete(value);
  }
  forEach(callbackfn, thisArg) {
    this.c.forEach((_value, key) => callbackfn.call(thisArg, key, key, this));
  }
  has(value) {
    return this.c.has(value);
  }
  entries() {
    return this.c.entries();
  }
  keys() {
    return this.c.keys();
  }
  values() {
    return this.c.keys();
  }
  [(_b = Symbol.toStringTag, Symbol.iterator)]() {
    return this.keys();
  }
};
var Touch;
(function(Touch2) {
  Touch2[Touch2["None"] = 0] = "None";
  Touch2[Touch2["AsOld"] = 1] = "AsOld";
  Touch2[Touch2["AsNew"] = 2] = "AsNew";
})(Touch || (Touch = {}));
var $Gc = class {
  constructor() {
    this[_c] = "LinkedMap";
    this.c = /* @__PURE__ */ new Map();
    this.d = void 0;
    this.e = void 0;
    this.f = 0;
    this.g = 0;
  }
  clear() {
    this.c.clear();
    this.d = void 0;
    this.e = void 0;
    this.f = 0;
    this.g++;
  }
  isEmpty() {
    return !this.d && !this.e;
  }
  get size() {
    return this.f;
  }
  get first() {
    return this.d?.value;
  }
  get last() {
    return this.e?.value;
  }
  has(key) {
    return this.c.has(key);
  }
  get(key, touch = 0) {
    const item = this.c.get(key);
    if (!item) {
      return void 0;
    }
    if (touch !== 0) {
      this.m(item, touch);
    }
    return item.value;
  }
  set(key, value, touch = 0) {
    let item = this.c.get(key);
    if (item) {
      item.value = value;
      if (touch !== 0) {
        this.m(item, touch);
      }
    } else {
      item = { key, value, next: void 0, previous: void 0 };
      switch (touch) {
        case 0:
          this.k(item);
          break;
        case 1:
          this.j(item);
          break;
        case 2:
          this.k(item);
          break;
        default:
          this.k(item);
          break;
      }
      this.c.set(key, item);
      this.f++;
    }
    return this;
  }
  delete(key) {
    return !!this.remove(key);
  }
  remove(key) {
    const item = this.c.get(key);
    if (!item) {
      return void 0;
    }
    this.c.delete(key);
    this.l(item);
    this.f--;
    return item.value;
  }
  shift() {
    if (!this.d && !this.e) {
      return void 0;
    }
    if (!this.d || !this.e) {
      throw new Error("Invalid list");
    }
    const item = this.d;
    this.c.delete(item.key);
    this.l(item);
    this.f--;
    return item.value;
  }
  forEach(callbackfn, thisArg) {
    const state = this.g;
    let current = this.d;
    while (current) {
      if (thisArg) {
        callbackfn.bind(thisArg)(current.value, current.key, this);
      } else {
        callbackfn(current.value, current.key, this);
      }
      if (this.g !== state) {
        throw new Error(`LinkedMap got modified during iteration.`);
      }
      current = current.next;
    }
  }
  keys() {
    const map = this;
    const state = this.g;
    let current = this.d;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map.g !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: current.key, done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  values() {
    const map = this;
    const state = this.g;
    let current = this.d;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map.g !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: current.value, done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  entries() {
    const map = this;
    const state = this.g;
    let current = this.d;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map.g !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: [current.key, current.value], done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  [(_c = Symbol.toStringTag, Symbol.iterator)]() {
    return this.entries();
  }
  h(newSize) {
    if (newSize >= this.size) {
      return;
    }
    if (newSize === 0) {
      this.clear();
      return;
    }
    let current = this.d;
    let currentSize = this.size;
    while (current && currentSize > newSize) {
      this.c.delete(current.key);
      current = current.next;
      currentSize--;
    }
    this.d = current;
    this.f = currentSize;
    if (current) {
      current.previous = void 0;
    }
    this.g++;
  }
  i(newSize) {
    if (newSize >= this.size) {
      return;
    }
    if (newSize === 0) {
      this.clear();
      return;
    }
    let current = this.e;
    let currentSize = this.size;
    while (current && currentSize > newSize) {
      this.c.delete(current.key);
      current = current.previous;
      currentSize--;
    }
    this.e = current;
    this.f = currentSize;
    if (current) {
      current.next = void 0;
    }
    this.g++;
  }
  j(item) {
    if (!this.d && !this.e) {
      this.e = item;
    } else if (!this.d) {
      throw new Error("Invalid list");
    } else {
      item.next = this.d;
      this.d.previous = item;
    }
    this.d = item;
    this.g++;
  }
  k(item) {
    if (!this.d && !this.e) {
      this.d = item;
    } else if (!this.e) {
      throw new Error("Invalid list");
    } else {
      item.previous = this.e;
      this.e.next = item;
    }
    this.e = item;
    this.g++;
  }
  l(item) {
    if (item === this.d && item === this.e) {
      this.d = void 0;
      this.e = void 0;
    } else if (item === this.d) {
      if (!item.next) {
        throw new Error("Invalid list");
      }
      item.next.previous = void 0;
      this.d = item.next;
    } else if (item === this.e) {
      if (!item.previous) {
        throw new Error("Invalid list");
      }
      item.previous.next = void 0;
      this.e = 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.g++;
  }
  m(item, touch) {
    if (!this.d || !this.e) {
      throw new Error("Invalid list");
    }
    if (touch !== 1 && touch !== 2) {
      return;
    }
    if (touch === 1) {
      if (item === this.d) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this.e) {
        previous.next = void 0;
        this.e = previous;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.previous = void 0;
      item.next = this.d;
      this.d.previous = item;
      this.d = item;
      this.g++;
    } else if (touch === 2) {
      if (item === this.e) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this.d) {
        next.previous = void 0;
        this.d = next;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.next = void 0;
      item.previous = this.e;
      this.e.next = item;
      this.e = item;
      this.g++;
    }
  }
  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);
    }
  }
};
var Cache = class extends $Gc {
  constructor(limit, ratio = 1) {
    super();
    this.n = limit;
    this.o = Math.min(Math.max(0, ratio), 1);
  }
  get limit() {
    return this.n;
  }
  set limit(limit) {
    this.n = limit;
    this.p();
  }
  get ratio() {
    return this.o;
  }
  set ratio(ratio) {
    this.o = Math.min(Math.max(0, ratio), 1);
    this.p();
  }
  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 */
    );
    return this;
  }
  p() {
    if (this.size > this.n) {
      this.q(Math.round(this.n * this.o));
    }
  }
};
var $Hc = class extends Cache {
  constructor(limit, ratio = 1) {
    super(limit, ratio);
  }
  q(newSize) {
    this.h(newSize);
  }
  set(key, value) {
    super.set(key, value);
    this.p();
    return this;
  }
};
var $Lc = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
  }
  add(key, value) {
    let values = this.c.get(key);
    if (!values) {
      values = /* @__PURE__ */ new Set();
      this.c.set(key, values);
    }
    values.add(value);
  }
  delete(key, value) {
    const values = this.c.get(key);
    if (!values) {
      return;
    }
    values.delete(value);
    if (values.size === 0) {
      this.c.delete(key);
    }
  }
  forEach(key, fn) {
    const values = this.c.get(key);
    if (!values) {
      return;
    }
    values.forEach(fn);
  }
  get(key) {
    const values = this.c.get(key);
    if (!values) {
      return /* @__PURE__ */ new Set();
    }
    return values;
  }
};

// out-build/vs/base/common/iterator.js
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 empty() {
    return _empty2;
  }
  Iterable2.empty = empty;
  function* single(element) {
    yield element;
  }
  Iterable2.single = single;
  function wrap(iterableOrElement) {
    if (is(iterableOrElement)) {
      return iterableOrElement;
    } else {
      return single(iterableOrElement);
    }
  }
  Iterable2.wrap = wrap;
  function from(iterable) {
    return iterable || _empty2;
  }
  Iterable2.from = from;
  function* reverse(array) {
    for (let i = array.length - 1; i >= 0; i--) {
      yield array[i];
    }
  }
  Iterable2.reverse = reverse;
  function isEmpty(iterable) {
    return !iterable || iterable[Symbol.iterator]().next().done === true;
  }
  Iterable2.isEmpty = isEmpty;
  function first(iterable) {
    return iterable[Symbol.iterator]().next().value;
  }
  Iterable2.first = first;
  function some(iterable, predicate) {
    let i = 0;
    for (const element of iterable) {
      if (predicate(element, i++)) {
        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* filter(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        yield element;
      }
    }
  }
  Iterable2.filter = filter;
  function* map(iterable, fn) {
    let index = 0;
    for (const element of iterable) {
      yield fn(element, index++);
    }
  }
  Iterable2.map = map;
  function* flatMap(iterable, fn) {
    let index = 0;
    for (const element of iterable) {
      yield* fn(element, index++);
    }
  }
  Iterable2.flatMap = flatMap;
  function* concat(...iterables) {
    for (const iterable of iterables) {
      yield* iterable;
    }
  }
  Iterable2.concat = concat;
  function reduce(iterable, reducer, initialValue) {
    let value = initialValue;
    for (const element of iterable) {
      value = reducer(value, element);
    }
    return value;
  }
  Iterable2.reduce = reduce;
  function* slice(arr, from2, to = arr.length) {
    if (from2 < -arr.length) {
      from2 = 0;
    }
    if (from2 < 0) {
      from2 += arr.length;
    }
    if (to < 0) {
      to += arr.length;
    } else if (to > arr.length) {
      to = arr.length;
    }
    for (; from2 < to; from2++) {
      yield arr[from2];
    }
  }
  Iterable2.slice = slice;
  function consume(iterable, atMost = Number.POSITIVE_INFINITY) {
    const consumed = [];
    if (atMost === 0) {
      return [consumed, iterable];
    }
    const iterator = iterable[Symbol.iterator]();
    for (let i = 0; i < atMost; i++) {
      const next = iterator.next();
      if (next.done) {
        return [consumed, Iterable2.empty()];
      }
      consumed.push(next.value);
    }
    return [consumed, { [Symbol.iterator]() {
      return iterator;
    } }];
  }
  Iterable2.consume = consume;
  async function asyncToArray(iterable) {
    const result = [];
    for await (const item of iterable) {
      result.push(item);
    }
    return Promise.resolve(result);
  }
  Iterable2.asyncToArray = asyncToArray;
})(Iterable || (Iterable = {}));

// out-build/vs/base/common/lifecycle.js
var TRACK_DISPOSABLES = false;
var disposableTracker = null;
var $Rc = class _$Rc {
  constructor() {
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.a = 0;
  }
  c(d) {
    let val = this.b.get(d);
    if (!val) {
      val = { parent: null, source: null, isSingleton: false, value: d, idx: _$Rc.a++ };
      this.b.set(d, val);
    }
    return val;
  }
  trackDisposable(d) {
    const data = this.c(d);
    if (!data.source) {
      data.source = new Error().stack;
    }
  }
  setParent(child, parent) {
    const data = this.c(child);
    data.parent = parent;
  }
  markAsDisposed(x) {
    this.b.delete(x);
  }
  markAsSingleton(disposable) {
    this.c(disposable).isSingleton = true;
  }
  f(data, cache) {
    const cacheValue = cache.get(data);
    if (cacheValue) {
      return cacheValue;
    }
    const result = data.parent ? this.f(this.c(data.parent), cache) : data;
    cache.set(data, result);
    return result;
  }
  getTrackedDisposables() {
    const rootParentCache = /* @__PURE__ */ new Map();
    const leaking = [...this.b.entries()].filter(([, v]) => v.source !== null && !this.f(v, rootParentCache).isSingleton).flatMap(([k]) => k);
    return leaking;
  }
  computeLeakingDisposables(maxReported = 10, preComputedLeaks) {
    let uncoveredLeakingObjs;
    if (preComputedLeaks) {
      uncoveredLeakingObjs = preComputedLeaks;
    } else {
      const rootParentCache = /* @__PURE__ */ new Map();
      const leakingObjects = [...this.b.values()].filter((info) => info.source !== null && !this.f(info, rootParentCache).isSingleton);
      if (leakingObjects.length === 0) {
        return;
      }
      const leakingObjsSet = new Set(leakingObjects.map((o) => o.value));
      uncoveredLeakingObjs = leakingObjects.filter((l) => {
        return !(l.parent && leakingObjsSet.has(l.parent));
      });
      if (uncoveredLeakingObjs.length === 0) {
        throw new Error("There are cyclic diposable chains!");
      }
    }
    if (!uncoveredLeakingObjs) {
      return void 0;
    }
    function getStackTracePath(leaking) {
      function removePrefix(array, linesToRemove) {
        while (array.length > 0 && linesToRemove.some((regexp) => typeof regexp === "string" ? regexp === array[0] : array[0].match(regexp))) {
          array.shift();
        }
      }
      const lines = leaking.source.split("\n").map((p) => p.trim().replace("at ", "")).filter((l) => l !== "");
      removePrefix(lines, ["Error", /^trackDisposable \(.*\)$/, /^DisposableTracker.trackDisposable \(.*\)$/]);
      return lines.reverse();
    }
    const stackTraceStarts = new $Lc();
    for (const leaking of uncoveredLeakingObjs) {
      const stackTracePath = getStackTracePath(leaking);
      for (let i2 = 0; i2 <= stackTracePath.length; i2++) {
        stackTraceStarts.add(stackTracePath.slice(0, i2).join("\n"), leaking);
      }
    }
    uncoveredLeakingObjs.sort($9b((l) => l.idx, $$b));
    let message = "";
    let i = 0;
    for (const leaking of uncoveredLeakingObjs.slice(0, maxReported)) {
      i++;
      const stackTracePath = getStackTracePath(leaking);
      const stackTraceFormattedLines = [];
      for (let i2 = 0; i2 < stackTracePath.length; i2++) {
        let line = stackTracePath[i2];
        const starts = stackTraceStarts.get(stackTracePath.slice(0, i2 + 1).join("\n"));
        line = `(shared with ${starts.size}/${uncoveredLeakingObjs.length} leaks) at ${line}`;
        const prevStarts = stackTraceStarts.get(stackTracePath.slice(0, i2).join("\n"));
        const continuations = $a([...prevStarts].map((d) => getStackTracePath(d)[i2]), (v) => v);
        delete continuations[stackTracePath[i2]];
        for (const [cont, set] of Object.entries(continuations)) {
          stackTraceFormattedLines.unshift(`    - stacktraces of ${set.length} other leaks continue with ${cont}`);
        }
        stackTraceFormattedLines.unshift(line);
      }
      message += `


==================== Leaking disposable ${i}/${uncoveredLeakingObjs.length}: ${leaking.value.constructor.name} ====================
${stackTraceFormattedLines.join("\n")}
============================================================

`;
    }
    if (uncoveredLeakingObjs.length > maxReported) {
      message += `


... and ${uncoveredLeakingObjs.length - maxReported} more leaking disposables

`;
    }
    return { leaks: uncoveredLeakingObjs, details: message };
  }
};
function $Sc(tracker) {
  disposableTracker = tracker;
}
if (TRACK_DISPOSABLES) {
  const __is_disposable_tracked__ = "__is_disposable_tracked__";
  $Sc(new class {
    trackDisposable(x) {
      const stack = new Error("Potentially leaked disposable").stack;
      setTimeout(() => {
        if (!x[__is_disposable_tracked__]) {
          console.log(stack);
        }
      }, 3e3);
    }
    setParent(child, parent) {
      if (child && child !== $3c.None) {
        try {
          child[__is_disposable_tracked__] = true;
        } catch {
        }
      }
    }
    markAsDisposed(disposable) {
      if (disposable && disposable !== $3c.None) {
        try {
          disposable[__is_disposable_tracked__] = true;
        } catch {
        }
      }
    }
    markAsSingleton(disposable) {
    }
  }());
}
function $Tc(x) {
  disposableTracker?.trackDisposable(x);
  return x;
}
function $Uc(disposable) {
  disposableTracker?.markAsDisposed(disposable);
}
function setParentOfDisposable(child, parent) {
  disposableTracker?.setParent(child, parent);
}
function setParentOfDisposables(children, parent) {
  if (!disposableTracker) {
    return;
  }
  for (const child of children) {
    disposableTracker.setParent(child, parent);
  }
}
function $Wc(thing) {
  return typeof thing === "object" && thing !== null && typeof thing.dispose === "function" && thing.dispose.length === 0;
}
function $Xc(arg) {
  if (Iterable.is(arg)) {
    const errors = [];
    for (const d of arg) {
      if (d) {
        try {
          d.dispose();
        } catch (e) {
          errors.push(e);
        }
      }
    }
    if (errors.length === 1) {
      throw errors[0];
    } else if (errors.length > 1) {
      throw new AggregateError(errors, "Encountered errors while disposing of store");
    }
    return Array.isArray(arg) ? [] : arg;
  } else if (arg) {
    arg.dispose();
    return arg;
  }
}
function $Zc(...disposables) {
  const parent = $1c(() => $Xc(disposables));
  setParentOfDisposables(disposables, parent);
  return parent;
}
function $1c(fn) {
  const self2 = $Tc({
    dispose: $Qc(() => {
      $Uc(self2);
      fn();
    })
  });
  return self2;
}
var $2c = class _$2c {
  static {
    this.DISABLE_DISPOSED_WARNING = false;
  }
  constructor() {
    this.f = /* @__PURE__ */ new Set();
    this.g = false;
    $Tc(this);
  }
  /**
   * 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.g) {
      return;
    }
    $Uc(this);
    this.g = true;
    this.clear();
  }
  /**
   * @return `true` if this object has been disposed of.
   */
  get isDisposed() {
    return this.g;
  }
  /**
   * Dispose of all registered disposables but do not mark this object as disposed.
   */
  clear() {
    if (this.f.size === 0) {
      return;
    }
    try {
      $Xc(this.f);
    } finally {
      this.f.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!");
    }
    setParentOfDisposable(o, this);
    if (this.g) {
      if (!_$2c.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.f.add(o);
    }
    return o;
  }
  /**
   * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the
   * disposable even when the disposable is not part in the store.
   */
  delete(o) {
    if (!o) {
      return;
    }
    if (o === this) {
      throw new Error("Cannot dispose a disposable on itself!");
    }
    this.f.delete(o);
    o.dispose();
  }
  /**
   * Deletes the value from the store, but does not dispose it.
   */
  deleteAndLeak(o) {
    if (!o) {
      return;
    }
    if (this.f.has(o)) {
      this.f.delete(o);
      setParentOfDisposable(o, null);
    }
  }
};
var $3c = class {
  static {
    this.None = Object.freeze({ dispose() {
    } });
  }
  constructor() {
    this.q = new $2c();
    $Tc(this);
    setParentOfDisposable(this.q, this);
  }
  dispose() {
    $Uc(this);
    this.q.dispose();
  }
  /**
   * Adds `o` to the collection of disposables managed by this object.
   */
  B(o) {
    if (o === this) {
      throw new Error("Cannot register a disposable on itself!");
    }
    return this.q.add(o);
  }
};
var $4c = class {
  constructor() {
    this.b = false;
    $Tc(this);
  }
  get value() {
    return this.b ? void 0 : this.a;
  }
  set value(value) {
    if (this.b || value === this.a) {
      return;
    }
    this.a?.dispose();
    if (value) {
      setParentOfDisposable(value, this);
    }
    this.a = value;
  }
  /**
   * Resets the stored value and disposed of the previously stored value.
   */
  clear() {
    this.value = void 0;
  }
  dispose() {
    this.b = true;
    $Uc(this);
    this.a?.dispose();
    this.a = void 0;
  }
  /**
   * Clears the value, but does not dispose it.
   * The old value is returned.
  */
  clearAndLeak() {
    const oldValue = this.a;
    this.a = void 0;
    if (oldValue) {
      setParentOfDisposable(oldValue, null);
    }
    return oldValue;
  }
};
var $_c = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = false;
    $Tc(this);
  }
  /**
   * 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() {
    $Uc(this);
    this.b = true;
    this.clearAndDisposeAll();
  }
  /**
   * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed.
   */
  clearAndDisposeAll() {
    if (!this.a.size) {
      return;
    }
    try {
      $Xc(this.a.values());
    } finally {
      this.a.clear();
    }
  }
  has(key) {
    return this.a.has(key);
  }
  get size() {
    return this.a.size;
  }
  get(key) {
    return this.a.get(key);
  }
  set(key, value, skipDisposeOnOverwrite = false) {
    if (this.b) {
      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) {
      this.a.get(key)?.dispose();
    }
    this.a.set(key, value);
  }
  /**
   * Delete the value stored for `key` from this map and also dispose of it.
   */
  deleteAndDispose(key) {
    this.a.get(key)?.dispose();
    this.a.delete(key);
  }
  /**
   * Delete the value stored for `key` from this map but return it. The caller is
   * responsible for disposing of the value.
   */
  deleteAndLeak(key) {
    const value = this.a.get(key);
    this.a.delete(key);
    return value;
  }
  keys() {
    return this.a.keys();
  }
  values() {
    return this.a.values();
  }
  [Symbol.iterator]() {
    return this.a[Symbol.iterator]();
  }
};

// out-build/vs/base/common/linkedList.js
var Node = class _Node {
  static {
    this.Undefined = new _Node(void 0);
  }
  constructor(element) {
    this.element = element;
    this.next = _Node.Undefined;
    this.prev = _Node.Undefined;
  }
};
var $cd = class {
  constructor() {
    this.a = Node.Undefined;
    this.b = Node.Undefined;
    this.c = 0;
  }
  get size() {
    return this.c;
  }
  isEmpty() {
    return this.a === Node.Undefined;
  }
  clear() {
    let node = this.a;
    while (node !== Node.Undefined) {
      const next = node.next;
      node.prev = Node.Undefined;
      node.next = Node.Undefined;
      node = next;
    }
    this.a = Node.Undefined;
    this.b = Node.Undefined;
    this.c = 0;
  }
  unshift(element) {
    return this.d(element, false);
  }
  push(element) {
    return this.d(element, true);
  }
  d(element, atTheEnd) {
    const newNode = new Node(element);
    if (this.a === Node.Undefined) {
      this.a = newNode;
      this.b = newNode;
    } else if (atTheEnd) {
      const oldLast = this.b;
      this.b = newNode;
      newNode.prev = oldLast;
      oldLast.next = newNode;
    } else {
      const oldFirst = this.a;
      this.a = newNode;
      newNode.next = oldFirst;
      oldFirst.prev = newNode;
    }
    this.c += 1;
    let didRemove = false;
    return () => {
      if (!didRemove) {
        didRemove = true;
        this.e(newNode);
      }
    };
  }
  shift() {
    if (this.a === Node.Undefined) {
      return void 0;
    } else {
      const res = this.a.element;
      this.e(this.a);
      return res;
    }
  }
  pop() {
    if (this.b === Node.Undefined) {
      return void 0;
    } else {
      const res = this.b.element;
      this.e(this.b);
      return res;
    }
  }
  e(node) {
    if (node.prev !== Node.Undefined && node.next !== Node.Undefined) {
      const anchor = node.prev;
      anchor.next = node.next;
      node.next.prev = anchor;
    } else if (node.prev === Node.Undefined && node.next === Node.Undefined) {
      this.a = Node.Undefined;
      this.b = Node.Undefined;
    } else if (node.next === Node.Undefined) {
      this.b = this.b.prev;
      this.b.next = Node.Undefined;
    } else if (node.prev === Node.Undefined) {
      this.a = this.a.next;
      this.a.prev = Node.Undefined;
    }
    this.c -= 1;
  }
  *[Symbol.iterator]() {
    let node = this.a;
    while (node !== Node.Undefined) {
      yield node.element;
      node = node.next;
    }
  }
};

// out-build/vs/base/common/stopwatch.js
var hasPerformanceNow = globalThis.performance && typeof globalThis.performance.now === "function";
var $te = class _$te {
  static create(highResolution) {
    return new _$te(highResolution);
  }
  constructor(highResolution) {
    this.c = hasPerformanceNow && highResolution === false ? Date.now : globalThis.performance.now.bind(globalThis.performance);
    this.a = this.c();
    this.b = -1;
  }
  stop() {
    this.b = this.c();
  }
  reset() {
    this.a = this.c();
    this.b = -1;
  }
  elapsed() {
    if (this.b !== -1) {
      return this.b - this.a;
    }
    return this.c() - this.a;
  }
};

// out-build/vs/base/common/event.js
var _enableListenerGCedWarning = false;
var _enableDisposeWithListenerWarning = false;
var _enableSnapshotPotentialLeakWarning = false;
var Event;
(function(Event2) {
  Event2.None = () => $3c.None;
  function _addLeakageTraceLogic(options2) {
    if (_enableSnapshotPotentialLeakWarning) {
      const { onDidAddListener: origListenerDidAdd } = options2;
      const stack = Stacktrace.create();
      let count = 0;
      options2.onDidAddListener = () => {
        if (++count === 2) {
          console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here");
          stack.print();
        }
        origListenerDidAdd?.();
      };
    }
  }
  function defer(event, disposable) {
    return debounce(event, () => void 0, 0, void 0, true, void 0, disposable);
  }
  Event2.defer = defer;
  function once(event) {
    return (listener, thisArgs = null, disposables) => {
      let didFire = false;
      let result = void 0;
      result = event((e) => {
        if (didFire) {
          return;
        } else if (result) {
          result.dispose();
        } else {
          didFire = true;
        }
        return listener.call(thisArgs, e);
      }, null, disposables);
      if (didFire) {
        result.dispose();
      }
      return result;
    };
  }
  Event2.once = once;
  function onceIf(event, condition) {
    return Event2.once(Event2.filter(event, condition));
  }
  Event2.onceIf = onceIf;
  function map(event, map2, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((i) => listener.call(thisArgs, map2(i)), null, disposables), disposable);
  }
  Event2.map = map;
  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 filter(event, filter2, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((e) => filter2(e) && listener.call(thisArgs, e), null, disposables), disposable);
  }
  Event2.filter = filter;
  function signal(event) {
    return event;
  }
  Event2.signal = signal;
  function any(...events) {
    return (listener, thisArgs = null, disposables) => {
      const disposable = $Zc(...events.map((event) => event((e) => listener.call(thisArgs, e))));
      return addAndReturnDisposable(disposable, disposables);
    };
  }
  Event2.any = any;
  function reduce(event, merge, initial, disposable) {
    let output = initial;
    return map(event, (e) => {
      output = merge(output, e);
      return output;
    }, disposable);
  }
  Event2.reduce = reduce;
  function snapshot(event, disposable) {
    let listener;
    const options2 = {
      onWillAddFirstListener() {
        listener = event(emitter.fire, emitter);
      },
      onDidRemoveLastListener() {
        listener?.dispose();
      }
    };
    if (!disposable) {
      _addLeakageTraceLogic(options2);
    }
    const emitter = new $ze(options2);
    disposable?.add(emitter);
    return emitter.event;
  }
  function addAndReturnDisposable(d, store) {
    if (store instanceof Array) {
      store.push(d);
    } else if (store) {
      store.add(d);
    }
    return d;
  }
  function debounce(event, merge, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold, disposable) {
    let subscription;
    let output = void 0;
    let handle = void 0;
    let numDebouncedCalls = 0;
    let doFire;
    const options2 = {
      leakWarningThreshold,
      onWillAddFirstListener() {
        subscription = event((cur) => {
          numDebouncedCalls++;
          output = merge(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?.();
        }
      },
      onDidRemoveLastListener() {
        doFire = void 0;
        subscription.dispose();
      }
    };
    if (!disposable) {
      _addLeakageTraceLogic(options2);
    }
    const emitter = new $ze(options2);
    disposable?.add(emitter);
    return emitter.event;
  }
  Event2.debounce = debounce;
  function accumulate(event, delay = 0, disposable) {
    return Event2.debounce(event, (last, e) => {
      if (!last) {
        return [e];
      }
      last.push(e);
      return last;
    }, delay, void 0, true, void 0, disposable);
  }
  Event2.accumulate = accumulate;
  function latch(event, equals = (a, b) => a === b, disposable) {
    let firstCall = true;
    let cache;
    return filter(event, (value) => {
      const shouldEmit = firstCall || !equals(value, cache);
      firstCall = false;
      cache = 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 = [], disposable) {
    let buffer2 = _buffer.slice();
    let listener = event((e) => {
      if (buffer2) {
        buffer2.push(e);
      } else {
        emitter.fire(e);
      }
    });
    if (disposable) {
      disposable.add(listener);
    }
    const flush = () => {
      buffer2?.forEach((e) => emitter.fire(e));
      buffer2 = null;
    };
    const emitter = new $ze({
      onWillAddFirstListener() {
        if (!listener) {
          listener = event((e) => emitter.fire(e));
          if (disposable) {
            disposable.add(listener);
          }
        }
      },
      onDidAddFirstListener() {
        if (buffer2) {
          if (flushAfterTimeout) {
            setTimeout(flush);
          } else {
            flush();
          }
        }
      },
      onDidRemoveLastListener() {
        if (listener) {
          listener.dispose();
        }
        listener = null;
      }
    });
    if (disposable) {
      disposable.add(emitter);
    }
    return emitter.event;
  }
  Event2.buffer = buffer;
  function chain(event, sythensize) {
    const fn = (listener, thisArgs, disposables) => {
      const cs = sythensize(new ChainableSynthesis());
      return event(function(value) {
        const result = cs.evaluate(value);
        if (result !== HaltChainable) {
          listener.call(thisArgs, result);
        }
      }, void 0, disposables);
    };
    return fn;
  }
  Event2.chain = chain;
  const HaltChainable = Symbol("HaltChainable");
  class ChainableSynthesis {
    constructor() {
      this.f = [];
    }
    map(fn) {
      this.f.push(fn);
      return this;
    }
    forEach(fn) {
      this.f.push((v) => {
        fn(v);
        return v;
      });
      return this;
    }
    filter(fn) {
      this.f.push((v) => fn(v) ? v : HaltChainable);
      return this;
    }
    reduce(merge, initial) {
      let last = initial;
      this.f.push((v) => {
        last = merge(last, v);
        return last;
      });
      return this;
    }
    latch(equals = (a, b) => a === b) {
      let firstCall = true;
      let cache;
      this.f.push((value) => {
        const shouldEmit = firstCall || !equals(value, cache);
        firstCall = false;
        cache = value;
        return shouldEmit ? value : HaltChainable;
      });
      return this;
    }
    evaluate(value) {
      for (const step of this.f) {
        value = step(value);
        if (value === HaltChainable) {
          break;
        }
      }
      return value;
    }
  }
  function fromNodeEventEmitter(emitter, eventName, map2 = (id2) => id2) {
    const fn = (...args2) => result.fire(map2(...args2));
    const onFirstListenerAdd = () => emitter.on(eventName, fn);
    const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
    const result = new $ze({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
    return result.event;
  }
  Event2.fromNodeEventEmitter = fromNodeEventEmitter;
  function fromDOMEventEmitter(emitter, eventName, map2 = (id2) => id2) {
    const fn = (...args2) => result.fire(map2(...args2));
    const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
    const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
    const result = new $ze({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
    return result.event;
  }
  Event2.fromDOMEventEmitter = fromDOMEventEmitter;
  function toPromise(event) {
    return new Promise((resolve) => once(event)(resolve));
  }
  Event2.toPromise = toPromise;
  function fromPromise(promise) {
    const result = new $ze();
    promise.then((res) => {
      result.fire(res);
    }, () => {
      result.fire(void 0);
    }).finally(() => {
      result.dispose();
    });
    return result.event;
  }
  Event2.fromPromise = fromPromise;
  function forward(from, to) {
    return from((e) => to.fire(e));
  }
  Event2.forward = forward;
  function runAndSubscribe(event, handler, initial) {
    handler(initial);
    return event((e) => handler(e));
  }
  Event2.runAndSubscribe = runAndSubscribe;
  class EmitterObserver {
    constructor(_observable, store) {
      this._observable = _observable;
      this.f = 0;
      this.g = false;
      const options2 = {
        onWillAddFirstListener: () => {
          _observable.addObserver(this);
          this._observable.reportChanges();
        },
        onDidRemoveLastListener: () => {
          _observable.removeObserver(this);
        }
      };
      if (!store) {
        _addLeakageTraceLogic(options2);
      }
      this.emitter = new $ze(options2);
      if (store) {
        store.add(this.emitter);
      }
    }
    beginUpdate(_observable) {
      this.f++;
    }
    handlePossibleChange(_observable) {
    }
    handleChange(_observable, _change) {
      this.g = true;
    }
    endUpdate(_observable) {
      this.f--;
      if (this.f === 0) {
        this._observable.reportChanges();
        if (this.g) {
          this.g = 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, thisArgs, disposables) => {
      let count = 0;
      let didChange = false;
      const observer = {
        beginUpdate() {
          count++;
        },
        endUpdate() {
          count--;
          if (count === 0) {
            observable.reportChanges();
            if (didChange) {
              didChange = false;
              listener.call(thisArgs);
            }
          }
        },
        handlePossibleChange() {
        },
        handleChange() {
          didChange = true;
        }
      };
      observable.addObserver(observer);
      observable.reportChanges();
      const disposable = {
        dispose() {
          observable.removeObserver(observer);
        }
      };
      if (disposables instanceof $2c) {
        disposables.add(disposable);
      } else if (Array.isArray(disposables)) {
        disposables.push(disposable);
      }
      return disposable;
    };
  }
  Event2.fromObservableLight = fromObservableLight;
})(Event || (Event = {}));
var $ve = class _$ve {
  static {
    this.all = /* @__PURE__ */ new Set();
  }
  static {
    this.f = 0;
  }
  constructor(name) {
    this.listenerCount = 0;
    this.invocationCount = 0;
    this.elapsedOverall = 0;
    this.durations = [];
    this.name = `${name}_${_$ve.f++}`;
    _$ve.all.add(this);
  }
  start(listenerCount) {
    this.g = new $te();
    this.listenerCount = listenerCount;
  }
  stop() {
    if (this.g) {
      const elapsed = this.g.elapsed();
      this.durations.push(elapsed);
      this.elapsedOverall += elapsed;
      this.invocationCount += 1;
      this.g = void 0;
    }
  }
};
var _globalLeakWarningThreshold = -1;
var LeakageMonitor = class _LeakageMonitor {
  static {
    this.f = 1;
  }
  constructor(j, threshold, name = (_LeakageMonitor.f++).toString(16).padStart(3, "0")) {
    this.j = j;
    this.threshold = threshold;
    this.name = name;
    this.h = 0;
  }
  dispose() {
    this.g?.clear();
  }
  check(stack, listenerCount) {
    const threshold = this.threshold;
    if (threshold <= 0 || listenerCount < threshold) {
      return void 0;
    }
    if (!this.g) {
      this.g = /* @__PURE__ */ new Map();
    }
    const count = this.g.get(stack.value) || 0;
    this.g.set(stack.value, count + 1);
    this.h -= 1;
    if (this.h <= 0) {
      this.h = threshold * 0.5;
      const [topStack, topCount] = this.getMostFrequentStack();
      const message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`;
      console.warn(message);
      console.warn(topStack);
      const error = new $xe(message, topStack);
      this.j(error);
    }
    return () => {
      const count2 = this.g.get(stack.value) || 0;
      this.g.set(stack.value, count2 - 1);
    };
  }
  getMostFrequentStack() {
    if (!this.g) {
      return void 0;
    }
    let topStack;
    let topCount = 0;
    for (const [stack, count] of this.g) {
      if (!topStack || topCount < count) {
        topStack = [stack, count];
        topCount = count;
      }
    }
    return topStack;
  }
};
var Stacktrace = class _Stacktrace {
  static create() {
    const err = new Error();
    return new _Stacktrace(err.stack ?? "");
  }
  constructor(value) {
    this.value = value;
  }
  print() {
    console.warn(this.value.split("\n").slice(2).join("\n"));
  }
};
var $xe = class extends Error {
  constructor(message, stack) {
    super(message);
    this.name = "ListenerLeakError";
    this.stack = stack;
  }
};
var $ye = class extends Error {
  constructor(message, stack) {
    super(message);
    this.name = "ListenerRefusalError";
    this.stack = stack;
  }
};
var id = 0;
var UniqueContainer = class {
  constructor(value) {
    this.value = value;
    this.id = id++;
  }
};
var compactionThreshold = 2;
var forEachListener = (listeners, fn) => {
  if (listeners instanceof UniqueContainer) {
    fn(listeners);
  } else {
    for (let i = 0; i < listeners.length; i++) {
      const l = listeners[i];
      if (l) {
        fn(l);
      }
    }
  }
};
var _listenerFinalizers;
if (_enableListenerGCedWarning) {
  const leaks = [];
  setInterval(() => {
    if (leaks.length === 0) {
      return;
    }
    console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:");
    console.warn(leaks.join("\n"));
    leaks.length = 0;
  }, 3e3);
  _listenerFinalizers = new FinalizationRegistry((heldValue) => {
    if (typeof heldValue === "string") {
      leaks.push(heldValue);
    }
  });
}
var $ze = class {
  constructor(options2) {
    this.z = 0;
    this.f = options2;
    this.g = _globalLeakWarningThreshold > 0 || this.f?.leakWarningThreshold ? new LeakageMonitor(options2?.onListenerError ?? $gb, this.f?.leakWarningThreshold ?? _globalLeakWarningThreshold) : void 0;
    this.j = this.f?._profName ? new $ve(this.f._profName) : void 0;
    this.w = this.f?.deliveryQueue;
  }
  dispose() {
    if (!this.m) {
      this.m = true;
      if (this.w?.current === this) {
        this.w.reset();
      }
      if (this.u) {
        if (_enableDisposeWithListenerWarning) {
          const listeners = this.u;
          queueMicrotask(() => {
            forEachListener(listeners, (l) => l.stack?.print());
          });
        }
        this.u = void 0;
        this.z = 0;
      }
      this.f?.onDidRemoveLastListener?.();
      this.g?.dispose();
    }
  }
  /**
   * For the public to allow to subscribe
   * to events from this Emitter
   */
  get event() {
    this.q ??= (callback, thisArgs, disposables) => {
      if (this.g && this.z > this.g.threshold ** 2) {
        const message = `[${this.g.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this.z} vs ${this.g.threshold})`;
        console.warn(message);
        const tuple = this.g.getMostFrequentStack() ?? ["UNKNOWN stack", -1];
        const error = new $ye(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]);
        const errorHandler = this.f?.onListenerError || $gb;
        errorHandler(error);
        return $3c.None;
      }
      if (this.m) {
        return $3c.None;
      }
      if (thisArgs) {
        callback = callback.bind(thisArgs);
      }
      const contained = new UniqueContainer(callback);
      let removeMonitor;
      let stack;
      if (this.g && this.z >= Math.ceil(this.g.threshold * 0.2)) {
        contained.stack = Stacktrace.create();
        removeMonitor = this.g.check(contained.stack, this.z + 1);
      }
      if (_enableDisposeWithListenerWarning) {
        contained.stack = stack ?? Stacktrace.create();
      }
      if (!this.u) {
        this.f?.onWillAddFirstListener?.(this);
        this.u = contained;
        this.f?.onDidAddFirstListener?.(this);
      } else if (this.u instanceof UniqueContainer) {
        this.w ??= new EventDeliveryQueuePrivate();
        this.u = [this.u, contained];
      } else {
        this.u.push(contained);
      }
      this.f?.onDidAddListener?.(this);
      this.z++;
      const result = $1c(() => {
        _listenerFinalizers?.unregister(result);
        removeMonitor?.();
        this.A(contained);
      });
      if (disposables instanceof $2c) {
        disposables.add(result);
      } else if (Array.isArray(disposables)) {
        disposables.push(result);
      }
      if (_listenerFinalizers) {
        const stack2 = new Error().stack.split("\n").slice(2, 3).join("\n").trim();
        const match = /(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(stack2);
        _listenerFinalizers.register(result, match?.[2] ?? stack2, result);
      }
      return result;
    };
    return this.q;
  }
  A(listener) {
    this.f?.onWillRemoveListener?.(this);
    if (!this.u) {
      return;
    }
    if (this.z === 1) {
      this.u = void 0;
      this.f?.onDidRemoveLastListener?.(this);
      this.z = 0;
      return;
    }
    const listeners = this.u;
    const index = listeners.indexOf(listener);
    if (index === -1) {
      console.log("disposed?", this.m);
      console.log("size?", this.z);
      console.log("arr?", JSON.stringify(this.u));
      throw new Error("Attempted to dispose unknown listener");
    }
    this.z--;
    listeners[index] = void 0;
    const adjustDeliveryQueue = this.w.current === this;
    if (this.z * compactionThreshold <= listeners.length) {
      let n = 0;
      for (let i = 0; i < listeners.length; i++) {
        if (listeners[i]) {
          listeners[n++] = listeners[i];
        } else if (adjustDeliveryQueue && n < this.w.end) {
          this.w.end--;
          if (n < this.w.i) {
            this.w.i--;
          }
        }
      }
      listeners.length = n;
    }
  }
  B(listener, value) {
    if (!listener) {
      return;
    }
    const errorHandler = this.f?.onListenerError || $gb;
    if (!errorHandler) {
      listener.value(value);
      return;
    }
    try {
      listener.value(value);
    } catch (e) {
      errorHandler(e);
    }
  }
  /** Delivers items in the queue. Assumes the queue is ready to go. */
  C(dq) {
    const listeners = dq.current.u;
    while (dq.i < dq.end) {
      this.B(listeners[dq.i++], dq.value);
    }
    dq.reset();
  }
  /**
   * To be kept private to fire an event to
   * subscribers
   */
  fire(event) {
    if (this.w?.current) {
      this.C(this.w);
      this.j?.stop();
    }
    this.j?.start(this.z);
    if (!this.u) {
    } else if (this.u instanceof UniqueContainer) {
      this.B(this.u, event);
    } else {
      const dq = this.w;
      dq.enqueue(this, event, this.u.length);
      this.C(dq);
    }
    this.j?.stop();
  }
  hasListeners() {
    return this.z > 0;
  }
};
var EventDeliveryQueuePrivate = class {
  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;
  }
};
var $Be = class extends $ze {
  async fireAsync(data, token, promiseJoin) {
    if (!this.u) {
      return;
    }
    if (!this.h) {
      this.h = new $cd();
    }
    forEachListener(this.u, (listener) => this.h.push([listener.value, data]));
    while (this.h.size > 0 && !token.isCancellationRequested) {
      const [listener, data2] = this.h.shift();
      const thenables = [];
      const event = {
        ...data2,
        token,
        waitUntil: (p) => {
          if (Object.isFrozen(thenables)) {
            throw new Error("waitUntil can NOT be called asynchronous");
          }
          if (promiseJoin) {
            p = promiseJoin(p, listener);
          }
          thenables.push(p);
        }
      };
      try {
        listener(event);
      } catch (e) {
        $gb(e);
        continue;
      }
      Object.freeze(thenables);
      await Promise.allSettled(thenables).then((values) => {
        for (const value of values) {
          if (value.status === "rejected") {
            $gb(value.reason);
          }
        }
      });
    }
  }
};
var $Ce = class extends $ze {
  get isPaused() {
    return this.h !== 0;
  }
  constructor(options2) {
    super(options2);
    this.h = 0;
    this.s = new $cd();
    this.t = options2?.merge;
  }
  pause() {
    this.h++;
  }
  resume() {
    if (this.h !== 0 && --this.h === 0) {
      if (this.t) {
        if (this.s.size > 0) {
          const events = Array.from(this.s);
          this.s.clear();
          super.fire(this.t(events));
        }
      } else {
        while (!this.h && this.s.size !== 0) {
          super.fire(this.s.shift());
        }
      }
    }
  }
  fire(event) {
    if (this.z) {
      if (this.h !== 0) {
        this.s.push(event);
      } else {
        super.fire(event);
      }
    }
  }
};
var $De = class extends $Ce {
  constructor(options2) {
    super(options2);
    this.k = options2.delay ?? 100;
  }
  fire(event) {
    if (!this.o) {
      this.pause();
      this.o = setTimeout(() => {
        this.o = void 0;
        this.resume();
      }, this.k);
    }
    super.fire(event);
  }
};
var $Ie = class {
  constructor() {
    this.f = false;
    this.g = Event.None;
    this.h = $3c.None;
    this.j = new $ze({
      onDidAddFirstListener: () => {
        this.f = true;
        this.h = this.g(this.j.fire, this.j);
      },
      onDidRemoveLastListener: () => {
        this.f = false;
        this.h.dispose();
      }
    });
    this.event = this.j.event;
  }
  set input(event) {
    this.g = event;
    if (this.f) {
      this.h.dispose();
      this.h = event(this.j.fire, this.j);
    }
  }
  dispose() {
    this.h.dispose();
    this.j.dispose();
  }
};

// out-build/vs/base/common/cancellation.js
var 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.None
  });
  CancellationToken2.Cancelled = Object.freeze({
    isCancellationRequested: true,
    onCancellationRequested: shortcutEvent
  });
})(CancellationToken || (CancellationToken = {}));
var MutableToken = class {
  constructor() {
    this.a = false;
    this.b = null;
  }
  cancel() {
    if (!this.a) {
      this.a = true;
      if (this.b) {
        this.b.fire(void 0);
        this.dispose();
      }
    }
  }
  get isCancellationRequested() {
    return this.a;
  }
  get onCancellationRequested() {
    if (this.a) {
      return shortcutEvent;
    }
    if (!this.b) {
      this.b = new $ze();
    }
    return this.b.event;
  }
  dispose() {
    if (this.b) {
      this.b.dispose();
      this.b = null;
    }
  }
};
var $ad = class {
  constructor(parent) {
    this.f = void 0;
    this.g = void 0;
    this.g = parent && parent.onCancellationRequested(this.cancel, this);
  }
  get token() {
    if (!this.f) {
      this.f = new MutableToken();
    }
    return this.f;
  }
  cancel() {
    if (!this.f) {
      this.f = CancellationToken.Cancelled;
    } else if (this.f instanceof MutableToken) {
      this.f.cancel();
    }
  }
  dispose(cancel = false) {
    if (cancel) {
      this.cancel();
    }
    this.g?.dispose();
    if (!this.f) {
      this.f = CancellationToken.None;
    } else if (this.f instanceof MutableToken) {
      this.f.dispose();
    }
  }
};

// out-build/vs/nls.messages.js
function $f() {
  return globalThis._VSCODE_NLS_MESSAGES;
}
function $g() {
  return globalThis._VSCODE_NLS_LANGUAGE;
}

// out-build/vs/nls.js
var isPseudo = $g() === "pseudo" || typeof document !== "undefined" && document.location && typeof document.location.hash === "string" && document.location.hash.indexOf("pseudo=true") >= 0;
function _format(message, args2) {
  let result;
  if (args2.length === 0) {
    result = message;
  } else {
    result = message.replace(/\{(\d+)\}/g, (match, rest) => {
      const index = rest[0];
      const arg = args2[index];
      let result2 = match;
      if (typeof arg === "string") {
        result2 = arg;
      } else if (typeof arg === "number" || typeof arg === "boolean" || arg === void 0 || arg === null) {
        result2 = String(arg);
      }
      return result2;
    });
  }
  if (isPseudo) {
    result = "\uFF3B" + result.replace(/[aouei]/g, "$&$&") + "\uFF3D";
  }
  return result;
}
function localize(data, message, ...args2) {
  if (typeof data === "number") {
    return _format(lookupMessage(data, message), args2);
  }
  return _format(message, args2);
}
function lookupMessage(index, fallback) {
  const message = $f()?.[index];
  if (typeof message !== "string") {
    if (typeof fallback === "string") {
      return fallback;
    }
    throw new Error(`!!! NLS MISSING: ${index} !!!`);
  }
  return message;
}
function localize2(data, originalMessage, ...args2) {
  let message;
  if (typeof data === "number") {
    message = lookupMessage(data, originalMessage);
  } else {
    message = originalMessage;
  }
  const value = _format(message, args2);
  return {
    value,
    original: originalMessage === message ? value : _format(originalMessage, args2)
  };
}

// out-build/vs/base/common/platform.js
var $j = "en";
var _isWindows = false;
var _isMacintosh = false;
var _isLinux = false;
var _isLinuxSnap = false;
var _isNative = false;
var _isWeb = false;
var _isElectron = false;
var _isIOS = false;
var _isCI = false;
var _isMobile = false;
var _locale = void 0;
var _language = $j;
var _platformLocale = $j;
var _translationsConfigFile = void 0;
var _userAgent = void 0;
var $globalThis = globalThis;
var nodeProcess = void 0;
if (typeof $globalThis.vscode !== "undefined" && typeof $globalThis.vscode.process !== "undefined") {
  nodeProcess = $globalThis.vscode.process;
} else if (typeof process !== "undefined" && typeof process?.versions?.node === "string") {
  nodeProcess = process;
}
var isElectronProcess = typeof nodeProcess?.versions?.electron === "string";
var isElectronRenderer = isElectronProcess && nodeProcess?.type === "renderer";
if (typeof nodeProcess === "object") {
  _isWindows = nodeProcess.platform === "win32";
  _isMacintosh = nodeProcess.platform === "darwin";
  _isLinux = nodeProcess.platform === "linux";
  _isLinuxSnap = _isLinux && !!nodeProcess.env["SNAP"] && !!nodeProcess.env["SNAP_REVISION"];
  _isElectron = isElectronProcess;
  _isCI = !!nodeProcess.env["CI"] || !!nodeProcess.env["BUILD_ARTIFACTSTAGINGDIRECTORY"];
  _locale = $j;
  _language = $j;
  const rawNlsConfig = nodeProcess.env["VSCODE_NLS_CONFIG"];
  if (rawNlsConfig) {
    try {
      const nlsConfig = JSON.parse(rawNlsConfig);
      _locale = nlsConfig.userLocale;
      _platformLocale = nlsConfig.osLocale;
      _language = nlsConfig.resolvedLanguage || $j;
      _translationsConfigFile = nlsConfig.languagePack?.translationsConfigFile;
    } catch (e) {
    }
  }
  _isNative = true;
} else 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?.indexOf("Mobi") >= 0;
  _isWeb = true;
  _language = $g() || $j;
  _locale = navigator.language.toLowerCase();
  _platformLocale = _locale;
} else {
  console.error("Unable to resolve platform.");
}
var Platform;
(function(Platform2) {
  Platform2[Platform2["Web"] = 0] = "Web";
  Platform2[Platform2["Mac"] = 1] = "Mac";
  Platform2[Platform2["Linux"] = 2] = "Linux";
  Platform2[Platform2["Windows"] = 3] = "Windows";
})(Platform || (Platform = {}));
function $k(platform) {
  switch (platform) {
    case 0:
      return "Web";
    case 1:
      return "Mac";
    case 2:
      return "Linux";
    case 3:
      return "Windows";
  }
}
var _platform = 0;
if (_isMacintosh) {
  _platform = 1;
} else if (_isWindows) {
  _platform = 3;
} else if (_isLinux) {
  _platform = 2;
}
var $l = _isWindows;
var $m = _isMacintosh;
var $n = _isLinux;
var $p = _isNative;
var $r = _isWeb;
var $s = _isWeb && typeof $globalThis.importScripts === "function";
var $t = $s ? $globalThis.origin : void 0;
var $w = _isCI;
var $x = _platform;
var $y = _userAgent;
var $z = _language;
var Language;
(function(Language2) {
  function value() {
    return $z;
  }
  Language2.value = value;
  function isDefaultVariant() {
    if ($z.length === 2) {
      return $z === "en";
    } else if ($z.length >= 3) {
      return $z[0] === "e" && $z[1] === "n" && $z[2] === "-";
    } else {
      return false;
    }
  }
  Language2.isDefaultVariant = isDefaultVariant;
  function isDefault() {
    return $z === "en";
  }
  Language2.isDefault = isDefault;
})(Language || (Language = {}));
var $D = typeof $globalThis.postMessage === "function" && !$globalThis.importScripts;
var $E = (() => {
  if ($D) {
    const pending = [];
    $globalThis.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
      });
      $globalThis.postMessage({ vscodeScheduleAsyncWork: myId }, "*");
    };
  }
  return (callback) => setTimeout(callback);
})();
var OperatingSystem;
(function(OperatingSystem2) {
  OperatingSystem2[OperatingSystem2["Windows"] = 1] = "Windows";
  OperatingSystem2[OperatingSystem2["Macintosh"] = 2] = "Macintosh";
  OperatingSystem2[OperatingSystem2["Linux"] = 3] = "Linux";
})(OperatingSystem || (OperatingSystem = {}));
var OS = _isMacintosh || _isIOS ? 2 : _isWindows ? 1 : 3;
var _isLittleEndian = true;
var _isLittleEndianComputed = false;
function $G() {
  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;
}
var $H = !!($y && $y.indexOf("Chrome") >= 0);
var $I = !!($y && $y.indexOf("Firefox") >= 0);
var $J = !!(!$H && ($y && $y.indexOf("Safari") >= 0));
var $K = !!($y && $y.indexOf("Edg/") >= 0);
var $L = !!($y && $y.indexOf("Android") >= 0);

// out-build/vs/base/common/process.js
var safeProcess;
var vscodeGlobal = globalThis.vscode;
if (typeof vscodeGlobal !== "undefined" && typeof vscodeGlobal.process !== "undefined") {
  const sandboxProcess = vscodeGlobal.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" && typeof process?.versions?.node === "string") {
  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 $l ? "win32" : $m ? "darwin" : "linux";
    },
    get arch() {
      return void 0;
    },
    // Unsupported
    get env() {
      return {};
    },
    cwd() {
      return "/";
    }
  };
}
var cwd = safeProcess.cwd;
var env = safeProcess.env;
var $hc = safeProcess.platform;
var $ic = safeProcess.arch;

// out-build/vs/base/common/path.js
var CHAR_UPPERCASE_A = 65;
var CHAR_LOWERCASE_A = 97;
var CHAR_UPPERCASE_Z = 90;
var CHAR_LOWERCASE_Z = 122;
var CHAR_DOT = 46;
var CHAR_FORWARD_SLASH = 47;
var CHAR_BACKWARD_SLASH = 92;
var CHAR_COLON = 58;
var CHAR_QUESTION_MARK = 63;
var ErrorInvalidArgType = class 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);
  }
}
var platformIsWin32 = $hc === "win32";
function isPathSeparator(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(path, allowAboveRoot, separator, isPathSeparator2) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code = 0;
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.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}${path.slice(lastSlash + 1, i)}`;
        } else {
          res = path.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 formatExt(ext) {
  return ext ? `${ext[0] === "." ? "" : "."}${ext}` : "";
}
function _format2(sep2, pathObject) {
  validateObject(pathObject, "pathObject");
  const dir = pathObject.dir || pathObject.root;
  const base = pathObject.base || `${pathObject.name || ""}${formatExt(pathObject.ext)}`;
  if (!dir) {
    return base;
  }
  return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep2}${base}`;
}
var $jc = {
  // path.resolve([from ...], to)
  resolve(...pathSegments) {
    let resolvedDevice = "";
    let resolvedTail = "";
    let resolvedAbsolute = false;
    for (let i = pathSegments.length - 1; i >= -1; i--) {
      let path;
      if (i >= 0) {
        path = pathSegments[i];
        validateString(path, `paths[${i}]`);
        if (path.length === 0) {
          continue;
        }
      } else if (resolvedDevice.length === 0) {
        path = cwd();
      } else {
        path = env[`=${resolvedDevice}`] || cwd();
        if (path === void 0 || path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
          path = `${resolvedDevice}\\`;
        }
      }
      const len = path.length;
      let rootEnd = 0;
      let device = "";
      let isAbsolute = false;
      const code = path.charCodeAt(0);
      if (len === 1) {
        if (isPathSeparator(code)) {
          rootEnd = 1;
          isAbsolute = true;
        }
      } else if (isPathSeparator(code)) {
        isAbsolute = true;
        if (isPathSeparator(path.charCodeAt(1))) {
          let j = 2;
          let last = j;
          while (j < len && !isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            const firstPart = path.slice(last, j);
            last = j;
            while (j < len && isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j < len && j !== last) {
              last = j;
              while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                j++;
              }
              if (j === len || j !== last) {
                device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                rootEnd = j;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
        device = path.slice(0, 2);
        rootEnd = 2;
        if (len > 2 && isPathSeparator(path.charCodeAt(2))) {
          isAbsolute = 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 = `${path.slice(rootEnd)}\\${resolvedTail}`;
        resolvedAbsolute = isAbsolute;
        if (isAbsolute && resolvedDevice.length > 0) {
          break;
        }
      }
    }
    resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator);
    return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || ".";
  },
  normalize(path) {
    validateString(path, "path");
    const len = path.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = 0;
    let device;
    let isAbsolute = false;
    const code = path.charCodeAt(0);
    if (len === 1) {
      return isPosixPathSeparator(code) ? "\\" : path;
    }
    if (isPathSeparator(code)) {
      isAbsolute = true;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          const firstPart = path.slice(last, j);
          last = j;
          while (j < len && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return `\\\\${firstPart}\\${path.slice(last)}\\`;
            }
            if (j !== last) {
              device = `\\\\${firstPart}\\${path.slice(last, j)}`;
              rootEnd = j;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.slice(0, 2);
      rootEnd = 2;
      if (len > 2 && isPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true;
        rootEnd = 3;
      }
    }
    let tail = rootEnd < len ? normalizeString(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator) : "";
    if (tail.length === 0 && !isAbsolute) {
      tail = ".";
    }
    if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) {
      tail += "\\";
    }
    if (device === void 0) {
      return isAbsolute ? `\\${tail}` : tail;
    }
    return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
  },
  isAbsolute(path) {
    validateString(path, "path");
    const len = path.length;
    if (len === 0) {
      return false;
    }
    const code = path.charCodeAt(0);
    return isPathSeparator(code) || // Possible device root
    len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isPathSeparator(path.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(firstPart.charCodeAt(0))) {
      ++slashCount;
      const firstLen = firstPart.length;
      if (firstLen > 1 && isPathSeparator(firstPart.charCodeAt(1))) {
        ++slashCount;
        if (firstLen > 2) {
          if (isPathSeparator(firstPart.charCodeAt(2))) {
            ++slashCount;
          } else {
            needsReplace = false;
          }
        }
      }
    }
    if (needsReplace) {
      while (slashCount < joined.length && isPathSeparator(joined.charCodeAt(slashCount))) {
        slashCount++;
      }
      if (slashCount >= 2) {
        joined = `\\${joined.slice(slashCount)}`;
      }
    }
    return $jc.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(from, to) {
    validateString(from, "from");
    validateString(to, "to");
    if (from === to) {
      return "";
    }
    const fromOrig = $jc.resolve(from);
    const toOrig = $jc.resolve(to);
    if (fromOrig === toOrig) {
      return "";
    }
    from = fromOrig.toLowerCase();
    to = toOrig.toLowerCase();
    if (from === to) {
      return "";
    }
    let fromStart = 0;
    while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
      fromStart++;
    }
    let fromEnd = from.length;
    while (fromEnd - 1 > fromStart && from.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 length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i = 0;
    for (; i < length; i++) {
      const fromCode = from.charCodeAt(fromStart + i);
      if (fromCode !== to.charCodeAt(toStart + i)) {
        break;
      } else if (fromCode === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i;
      }
    }
    if (i !== length) {
      if (lastCommonSep === -1) {
        return toOrig;
      }
    } else {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
          return toOrig.slice(toStart + i + 1);
        }
        if (i === 2) {
          return toOrig.slice(toStart + i);
        }
      }
      if (fromLen > length) {
        if (from.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 || from.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(path) {
    if (typeof path !== "string" || path.length === 0) {
      return path;
    }
    const resolvedPath = $jc.resolve(path);
    if (resolvedPath.length <= 2) {
      return path;
    }
    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 path;
  },
  dirname(path) {
    validateString(path, "path");
    const len = path.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = -1;
    let offset = 0;
    const code = path.charCodeAt(0);
    if (len === 1) {
      return isPathSeparator(code) ? path : ".";
    }
    if (isPathSeparator(code)) {
      rootEnd = offset = 1;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          last = j;
          while (j < len && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return path;
            }
            if (j !== last) {
              rootEnd = offset = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      rootEnd = len > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2;
      offset = rootEnd;
    }
    let end = -1;
    let matchedSlash = true;
    for (let i = len - 1; i >= offset; --i) {
      if (isPathSeparator(path.charCodeAt(i))) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      if (rootEnd === -1) {
        return ".";
      }
      end = rootEnd;
    }
    return path.slice(0, end);
  },
  basename(path, suffix) {
    if (suffix !== void 0) {
      validateString(suffix, "suffix");
    }
    validateString(path, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i;
    if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
      start = 2;
    }
    if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
      if (suffix === path) {
        return "";
      }
      let extIdx = suffix.length - 1;
      let firstNonSlashEnd = -1;
      for (i = path.length - 1; i >= start; --i) {
        const code = path.charCodeAt(i);
        if (isPathSeparator(code)) {
          if (!matchedSlash) {
            start = i + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            if (code === suffix.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path.length;
      }
      return path.slice(start, end);
    }
    for (i = path.length - 1; i >= start; --i) {
      if (isPathSeparator(path.charCodeAt(i))) {
        if (!matchedSlash) {
          start = i + 1;
          break;
        }
      } else if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
    }
    if (end === -1) {
      return "";
    }
    return path.slice(start, end);
  },
  extname(path) {
    validateString(path, "path");
    let start = 0;
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
      start = startPart = 2;
    }
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i);
      if (isPathSeparator(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 path.slice(startDot, end);
  },
  format: _format2.bind(null, "\\"),
  parse(path) {
    validateString(path, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path.length === 0) {
      return ret;
    }
    const len = path.length;
    let rootEnd = 0;
    let code = path.charCodeAt(0);
    if (len === 1) {
      if (isPathSeparator(code)) {
        ret.root = ret.dir = path;
        return ret;
      }
      ret.base = ret.name = path;
      return ret;
    }
    if (isPathSeparator(code)) {
      rootEnd = 1;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          last = j;
          while (j < len && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              rootEnd = j;
            } else if (j !== last) {
              rootEnd = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      if (len <= 2) {
        ret.root = ret.dir = path;
        return ret;
      }
      rootEnd = 2;
      if (isPathSeparator(path.charCodeAt(2))) {
        if (len === 3) {
          ret.root = ret.dir = path;
          return ret;
        }
        rootEnd = 3;
      }
    }
    if (rootEnd > 0) {
      ret.root = path.slice(0, rootEnd);
    }
    let startDot = -1;
    let startPart = rootEnd;
    let end = -1;
    let matchedSlash = true;
    let i = path.length - 1;
    let preDotState = 0;
    for (; i >= rootEnd; --i) {
      code = path.charCodeAt(i);
      if (isPathSeparator(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 = path.slice(startPart, end);
      } else {
        ret.name = path.slice(startPart, startDot);
        ret.base = path.slice(startPart, end);
        ret.ext = path.slice(startDot, end);
      }
    }
    if (startPart > 0 && startPart !== rootEnd) {
      ret.dir = path.slice(0, startPart - 1);
    } else {
      ret.dir = ret.root;
    }
    return ret;
  },
  sep: "\\",
  delimiter: ";",
  win32: null,
  posix: null
};
var posixCwd = (() => {
  if (platformIsWin32) {
    const regexp = /\\/g;
    return () => {
      const cwd2 = cwd().replace(regexp, "/");
      return cwd2.slice(cwd2.indexOf("/"));
    };
  }
  return () => cwd();
})();
var $kc = {
  // path.resolve([from ...], to)
  resolve(...pathSegments) {
    let resolvedPath = "";
    let resolvedAbsolute = false;
    for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
      const path = i >= 0 ? pathSegments[i] : posixCwd();
      validateString(path, `paths[${i}]`);
      if (path.length === 0) {
        continue;
      }
      resolvedPath = `${path}/${resolvedPath}`;
      resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    }
    resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
    if (resolvedAbsolute) {
      return `/${resolvedPath}`;
    }
    return resolvedPath.length > 0 ? resolvedPath : ".";
  },
  normalize(path) {
    validateString(path, "path");
    if (path.length === 0) {
      return ".";
    }
    const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
    path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator);
    if (path.length === 0) {
      if (isAbsolute) {
        return "/";
      }
      return trailingSeparator ? "./" : ".";
    }
    if (trailingSeparator) {
      path += "/";
    }
    return isAbsolute ? `/${path}` : path;
  },
  isAbsolute(path) {
    validateString(path, "path");
    return path.length > 0 && path.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 $kc.normalize(joined);
  },
  relative(from, to) {
    validateString(from, "from");
    validateString(to, "to");
    if (from === to) {
      return "";
    }
    from = $kc.resolve(from);
    to = $kc.resolve(to);
    if (from === to) {
      return "";
    }
    const fromStart = 1;
    const fromEnd = from.length;
    const fromLen = fromEnd - fromStart;
    const toStart = 1;
    const toLen = to.length - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i = 0;
    for (; i < length; i++) {
      const fromCode = from.charCodeAt(fromStart + i);
      if (fromCode !== to.charCodeAt(toStart + i)) {
        break;
      } else if (fromCode === CHAR_FORWARD_SLASH) {
        lastCommonSep = i;
      }
    }
    if (i === length) {
      if (toLen > length) {
        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 > length) {
        if (from.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 || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        out += out.length === 0 ? ".." : "/..";
      }
    }
    return `${out}${to.slice(toStart + lastCommonSep)}`;
  },
  toNamespacedPath(path) {
    return path;
  },
  dirname(path) {
    validateString(path, "path");
    if (path.length === 0) {
      return ".";
    }
    const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let end = -1;
    let matchedSlash = true;
    for (let i = path.length - 1; i >= 1; --i) {
      if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      return hasRoot ? "/" : ".";
    }
    if (hasRoot && end === 1) {
      return "//";
    }
    return path.slice(0, end);
  },
  basename(path, suffix) {
    if (suffix !== void 0) {
      validateString(suffix, "ext");
    }
    validateString(path, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i;
    if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
      if (suffix === path) {
        return "";
      }
      let extIdx = suffix.length - 1;
      let firstNonSlashEnd = -1;
      for (i = path.length - 1; i >= 0; --i) {
        const code = path.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 === suffix.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path.length;
      }
      return path.slice(start, end);
    }
    for (i = path.length - 1; i >= 0; --i) {
      if (path.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 path.slice(start, end);
  },
  extname(path) {
    validateString(path, "path");
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.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 path.slice(startDot, end);
  },
  format: _format2.bind(null, "/"),
  parse(path) {
    validateString(path, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path.length === 0) {
      return ret;
    }
    const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let start;
    if (isAbsolute) {
      ret.root = "/";
      start = 1;
    } else {
      start = 0;
    }
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let i = path.length - 1;
    let preDotState = 0;
    for (; i >= start; --i) {
      const code = path.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 && isAbsolute ? 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 = path.slice(start2, end);
      } else {
        ret.name = path.slice(start2, startDot);
        ret.base = path.slice(start2, end);
        ret.ext = path.slice(startDot, end);
      }
    }
    if (startPart > 0) {
      ret.dir = path.slice(0, startPart - 1);
    } else if (isAbsolute) {
      ret.dir = "/";
    }
    return ret;
  },
  sep: "/",
  delimiter: ":",
  win32: null,
  posix: null
};
$kc.win32 = $jc.win32 = $jc;
$kc.posix = $jc.posix = $kc;
var $lc = platformIsWin32 ? $jc.normalize : $kc.normalize;
var $mc = platformIsWin32 ? $jc.isAbsolute : $kc.isAbsolute;
var $nc = platformIsWin32 ? $jc.join : $kc.join;
var $oc = platformIsWin32 ? $jc.resolve : $kc.resolve;
var $pc = platformIsWin32 ? $jc.relative : $kc.relative;
var $qc = platformIsWin32 ? $jc.dirname : $kc.dirname;
var $rc = platformIsWin32 ? $jc.basename : $kc.basename;
var $sc = platformIsWin32 ? $jc.extname : $kc.extname;
var $tc = platformIsWin32 ? $jc.format : $kc.format;
var $uc = platformIsWin32 ? $jc.parse : $kc.parse;
var $vc = platformIsWin32 ? $jc.toNamespacedPath : $kc.toNamespacedPath;
var sep = platformIsWin32 ? $jc.sep : $kc.sep;
var $xc = platformIsWin32 ? $jc.delimiter : $kc.delimiter;

// out-build/vs/base/common/cache.js
function $pf(t) {
  return t;
}
var $qf = class {
  constructor(arg1, arg2) {
    this.a = void 0;
    this.b = void 0;
    if (typeof arg1 === "function") {
      this.c = arg1;
      this.d = $pf;
    } else {
      this.c = arg2;
      this.d = arg1.getCacheKey;
    }
  }
  get(arg) {
    const key = this.d(arg);
    if (this.b !== key) {
      this.b = key;
      this.a = this.c(arg);
    }
    return this.a;
  }
};

// out-build/vs/base/common/lazy.js
var $sf = class {
  constructor(d) {
    this.d = d;
    this.a = false;
  }
  /**
   * True if the lazy value has been resolved.
   */
  get hasValue() {
    return this.a;
  }
  /**
   * 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.a) {
      try {
        this.b = this.d();
      } catch (err) {
        this.c = err;
      } finally {
        this.a = true;
      }
    }
    if (this.c) {
      throw this.c;
    }
    return this.b;
  }
  /**
   * Get the wrapped value without forcing evaluation.
   */
  get rawValue() {
    return this.b;
  }
};

// out-build/vs/base/common/strings.js
function $vf(str) {
  if (!str || typeof str !== "string") {
    return true;
  }
  return str.trim().length === 0;
}
var _format2Regexp = /{([^}]+)}/g;
function $xf(template, values) {
  if (Object.keys(values).length === 0) {
    return template;
  }
  return template.replace(_format2Regexp, (match, group) => values[group] ?? match);
}
function $Af(value) {
  return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, "\\$&");
}
function $Bf(value, substr) {
  let result = 0;
  let index = value.indexOf(substr);
  while (index !== -1) {
    result++;
    index = value.indexOf(substr, index + substr.length);
  }
  return result;
}
function $Ff(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 $Gf(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 $If(pattern) {
  return pattern.replace(/\*/g, "");
}
function $Jf(searchString, isRegex, options2 = {}) {
  if (!searchString) {
    throw new Error("Cannot create regex from empty string");
  }
  if (!isRegex) {
    searchString = $Af(searchString);
  }
  if (options2.wholeWord) {
    if (!/\B/.test(searchString.charAt(0))) {
      searchString = "\\b" + searchString;
    }
    if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
      searchString = searchString + "\\b";
    }
  }
  let modifiers = "";
  if (options2.global) {
    modifiers += "g";
  }
  if (!options2.matchCase) {
    modifiers += "i";
  }
  if (options2.multiline) {
    modifiers += "m";
  }
  if (options2.unicode) {
    modifiers += "u";
  }
  return new RegExp(searchString, modifiers);
}
function $Kf(regexp) {
  if (regexp.source === "^" || regexp.source === "^$" || regexp.source === "$" || regexp.source === "^\\s*$") {
    return false;
  }
  const match = regexp.exec("");
  return !!(match && regexp.lastIndex === 0);
}
function $Mf(str) {
  return str.split(/\r\n|\r|\n/);
}
function $Of(str) {
  for (let i = 0, len = str.length; i < len; i++) {
    const chCode = str.charCodeAt(i);
    if (chCode !== 32 && chCode !== 9) {
      return i;
    }
  }
  return -1;
}
function $Qf(str, startIndex = str.length - 1) {
  for (let i = startIndex; i >= 0; i--) {
    const chCode = str.charCodeAt(i);
    if (chCode !== 32 && chCode !== 9) {
      return i;
    }
  }
  return -1;
}
function $Sf(str, search, replacer2) {
  const parts = [];
  let last = 0;
  for (const match of str.matchAll(search)) {
    parts.push(str.slice(last, match.index));
    if (match.index === void 0) {
      throw new Error("match.index should be defined");
    }
    last = match.index + match[0].length;
    parts.push(replacer2(match[0], ...match.slice(1), match.index, str, match.groups));
  }
  parts.push(str.slice(last));
  return Promise.all(parts).then((p) => p.join(""));
}
function $Tf(a, b) {
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  } else {
    return 0;
  }
}
function $Uf(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 $Vf(a, b) {
  return $Wf(a, b, 0, a.length, 0, b.length);
}
function $Wf(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 $Uf(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
    }
    if ($Yf(codeA)) {
      codeA -= 32;
    }
    if ($Yf(codeB)) {
      codeB -= 32;
    }
    const diff2 = codeA - codeB;
    if (diff2 === 0) {
      continue;
    }
    return diff2;
  }
  const aLen = aEnd - aStart;
  const bLen = bEnd - bStart;
  if (aLen < bLen) {
    return -1;
  } else if (aLen > bLen) {
    return 1;
  }
  return 0;
}
function $Yf(code) {
  return code >= 97 && code <= 122;
}
function $Zf(code) {
  return code >= 65 && code <= 90;
}
function $1f(a, b) {
  return a.length === b.length && $Wf(a, b) === 0;
}
function $2f(str, candidate) {
  const candidateLength = candidate.length;
  if (candidate.length > str.length) {
    return false;
  }
  return $Wf(str, candidate, 0, candidateLength) === 0;
}
function $3f(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 $5f(charCode) {
  return 55296 <= charCode && charCode <= 56319;
}
function $6f(charCode) {
  return 56320 <= charCode && charCode <= 57343;
}
function $7f(highSurrogate, lowSurrogate) {
  return (highSurrogate - 55296 << 10) + (lowSurrogate - 56320) + 65536;
}
function $8f(str, len, offset) {
  const charCode = str.charCodeAt(offset);
  if ($5f(charCode) && offset + 1 < len) {
    const nextCharCode = str.charCodeAt(offset + 1);
    if ($6f(nextCharCode)) {
      return $7f(charCode, nextCharCode);
    }
  }
  return charCode;
}
function getPrevCodePoint(str, offset) {
  const charCode = str.charCodeAt(offset - 1);
  if ($6f(charCode) && offset > 1) {
    const prevCharCode = str.charCodeAt(offset - 2);
    if ($5f(prevCharCode)) {
      return $7f(prevCharCode, charCode);
    }
  }
  return charCode;
}
var $9f = class {
  get offset() {
    return this.e;
  }
  constructor(str, offset = 0) {
    this.c = str;
    this.d = str.length;
    this.e = offset;
  }
  setOffset(offset) {
    this.e = offset;
  }
  prevCodePoint() {
    const codePoint = getPrevCodePoint(this.c, this.e);
    this.e -= codePoint >= 65536 ? 2 : 1;
    return codePoint;
  }
  nextCodePoint() {
    const codePoint = $8f(this.c, this.d, this.e);
    this.e += codePoint >= 65536 ? 2 : 1;
    return codePoint;
  }
  eol() {
    return this.e >= this.d;
  }
};
var $0f = class {
  get offset() {
    return this.c.offset;
  }
  constructor(str, offset = 0) {
    this.c = new $9f(str, offset);
  }
  nextGraphemeLength() {
    const graphemeBreakTree = GraphemeBreakTree.getInstance();
    const iterator = this.c;
    const initialOffset = iterator.offset;
    let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint());
    while (!iterator.eol()) {
      const offset = iterator.offset;
      const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint());
      if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
        iterator.setOffset(offset);
        break;
      }
      graphemeBreakType = nextGraphemeBreakType;
    }
    return iterator.offset - initialOffset;
  }
  prevGraphemeLength() {
    const graphemeBreakTree = GraphemeBreakTree.getInstance();
    const iterator = this.c;
    const initialOffset = iterator.offset;
    let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint());
    while (iterator.offset > 0) {
      const offset = iterator.offset;
      const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint());
      if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) {
        iterator.setOffset(offset);
        break;
      }
      graphemeBreakType = prevGraphemeBreakType;
    }
    return initialOffset - iterator.offset;
  }
  eol() {
    return this.c.eol();
  }
};
function $$f(str, initialOffset) {
  const iterator = new $0f(str, initialOffset);
  return iterator.nextGraphemeLength();
}
var 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 $cg(str) {
  if (!CONTAINS_RTL) {
    CONTAINS_RTL = makeContainsRtl();
  }
  return CONTAINS_RTL.test(str);
}
var IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/;
function $dg(str) {
  return IS_BASIC_ASCII.test(str);
}
var $eg = /[\u2028\u2029]/;
function $fg(str) {
  return $eg.test(str);
}
var $mg = String.fromCharCode(
  65279
  /* CharCode.UTF8_BOM */
);
function $ng(str) {
  return !!(str && str.length > 0 && str.charCodeAt(0) === 65279);
}
function $pg(target, query) {
  if (!target || !query) {
    return false;
  }
  if (target.length < query.length) {
    return false;
  }
  const queryLen = query.length;
  const targetLower = target.toLowerCase();
  let index = 0;
  let lastIndexOf = -1;
  while (index < queryLen) {
    const indexOf = targetLower.indexOf(query[index], lastIndexOf + 1);
    if (indexOf < 0) {
      return false;
    }
    lastIndexOf = indexOf;
    index++;
  }
  return true;
}
function $qg(target, ignoreEscapedChars = false) {
  if (!target) {
    return false;
  }
  if (ignoreEscapedChars) {
    target = target.replace(/\\./g, "");
  }
  return target.toLowerCase() !== target;
}
function $rg(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
function $sg(str, n = 1) {
  if (n === 0) {
    return "";
  }
  let idx = -1;
  do {
    idx = str.indexOf("\n", idx + 1);
    n--;
  } while (n > 0 && idx >= 0);
  if (idx === -1) {
    return str;
  }
  if (str[idx - 1] === "\r") {
    idx--;
  }
  return str.substr(0, idx);
}
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;
}
var GraphemeBreakType;
(function(GraphemeBreakType2) {
  GraphemeBreakType2[GraphemeBreakType2["Other"] = 0] = "Other";
  GraphemeBreakType2[GraphemeBreakType2["Prepend"] = 1] = "Prepend";
  GraphemeBreakType2[GraphemeBreakType2["CR"] = 2] = "CR";
  GraphemeBreakType2[GraphemeBreakType2["LF"] = 3] = "LF";
  GraphemeBreakType2[GraphemeBreakType2["Control"] = 4] = "Control";
  GraphemeBreakType2[GraphemeBreakType2["Extend"] = 5] = "Extend";
  GraphemeBreakType2[GraphemeBreakType2["Regional_Indicator"] = 6] = "Regional_Indicator";
  GraphemeBreakType2[GraphemeBreakType2["SpacingMark"] = 7] = "SpacingMark";
  GraphemeBreakType2[GraphemeBreakType2["L"] = 8] = "L";
  GraphemeBreakType2[GraphemeBreakType2["V"] = 9] = "V";
  GraphemeBreakType2[GraphemeBreakType2["T"] = 10] = "T";
  GraphemeBreakType2[GraphemeBreakType2["LV"] = 11] = "LV";
  GraphemeBreakType2[GraphemeBreakType2["LVT"] = 12] = "LVT";
  GraphemeBreakType2[GraphemeBreakType2["ZWJ"] = 13] = "ZWJ";
  GraphemeBreakType2[GraphemeBreakType2["Extended_Pictographic"] = 14] = "Extended_Pictographic";
})(GraphemeBreakType || (GraphemeBreakType = {}));
var GraphemeBreakTree = class _GraphemeBreakTree {
  static {
    this.c = null;
  }
  static getInstance() {
    if (!_GraphemeBreakTree.c) {
      _GraphemeBreakTree.c = new _GraphemeBreakTree();
    }
    return _GraphemeBreakTree.c;
  }
  constructor() {
    this.d = 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.d;
    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;
  }
};
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]");
}
var CodePoint;
(function(CodePoint2) {
  CodePoint2[CodePoint2["zwj"] = 8205] = "zwj";
  CodePoint2[CodePoint2["emojiVariantSelector"] = 65039] = "emojiVariantSelector";
  CodePoint2[CodePoint2["enclosingKeyCap"] = 8419] = "enclosingKeyCap";
})(CodePoint || (CodePoint = {}));
var $xg = class _$xg {
  static {
    this.c = new $sf(() => {
      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]}');
    });
  }
  static {
    this.d = new $qf({ getCacheKey: JSON.stringify }, (locales) => {
      function arrayToMap(arr) {
        const result = /* @__PURE__ */ new Map();
        for (let i = 0; i < arr.length; i += 2) {
          result.set(arr[i], arr[i + 1]);
        }
        return result;
      }
      function mergeMaps(map1, map2) {
        const result = new Map(map1);
        for (const [key, value] of map2) {
          result.set(key, value);
        }
        return result;
      }
      function intersectMaps(map1, map2) {
        if (!map1) {
          return map2;
        }
        const result = /* @__PURE__ */ new Map();
        for (const [key, value] of map1) {
          if (map2.has(key)) {
            result.set(key, value);
          }
        }
        return result;
      }
      const data = this.c.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 map2 = arrayToMap(data[locale]);
        languageSpecificMap = intersectMaps(languageSpecificMap, map2);
      }
      const commonMap = arrayToMap(data["_common"]);
      const map = mergeMaps(commonMap, languageSpecificMap);
      return new _$xg(map);
    });
  }
  static getInstance(locales) {
    return _$xg.d.get(Array.from(locales));
  }
  static {
    this.e = new $sf(() => Object.keys(_$xg.c.value).filter((k) => !k.startsWith("_")));
  }
  static getLocales() {
    return _$xg.e.value;
  }
  constructor(f) {
    this.f = f;
  }
  isAmbiguous(codePoint) {
    return this.f.has(codePoint);
  }
  containsAmbiguousCharacter(str) {
    for (let i = 0; i < str.length; i++) {
      const codePoint = str.codePointAt(i);
      if (typeof codePoint === "number" && this.isAmbiguous(codePoint)) {
        return true;
      }
    }
    return false;
  }
  /**
   * 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.f.get(codePoint);
  }
  getConfusableCodePoints() {
    return new Set(this.f.keys());
  }
};
var $yg = class _$yg {
  static c() {
    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 {
    this.d = void 0;
  }
  static e() {
    if (!this.d) {
      this.d = new Set(_$yg.c());
    }
    return this.d;
  }
  static isInvisibleCharacter(codePoint) {
    return _$yg.e().has(codePoint);
  }
  static containsInvisibleCharacter(str) {
    for (let i = 0; i < str.length; i++) {
      const codePoint = str.codePointAt(i);
      if (typeof codePoint === "number" && _$yg.isInvisibleCharacter(codePoint)) {
        return true;
      }
    }
    return false;
  }
  static get codePoints() {
    return _$yg.e();
  }
};

// out-build/vs/base/common/types.js
function $zg(str) {
  return typeof str === "string";
}
function $Ag(value) {
  return Array.isArray(value) && value.every((elem) => $zg(elem));
}
function $Bg(obj) {
  return typeof obj === "object" && obj !== null && !Array.isArray(obj) && !(obj instanceof RegExp) && !(obj instanceof Date);
}
function $Cg(obj) {
  const TypedArray = Object.getPrototypeOf(Uint8Array);
  return typeof obj === "object" && obj instanceof TypedArray;
}
function $Dg(obj) {
  return typeof obj === "number" && !isNaN(obj);
}
function $Fg(obj) {
  return obj === true || obj === false;
}
function $Gg(obj) {
  return typeof obj === "undefined";
}
function $Hg(arg) {
  return !$Ig(arg);
}
function $Ig(obj) {
  return $Gg(obj) || obj === null;
}
function $Jg(condition, type) {
  if (!condition) {
    throw new Error(type ? `Unexpected type, expected '${type}'` : "Unexpected type");
  }
}
function $Kg(arg) {
  if ($Ig(arg)) {
    throw new Error("Assertion Failed: argument is undefined or null");
  }
  return arg;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function $Mg(obj) {
  if (!$Bg(obj)) {
    return false;
  }
  for (const key in obj) {
    if (hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}
function $Ng(obj) {
  return typeof obj === "function";
}
function $Qg(arg, constraint) {
  if ($zg(constraint)) {
    if (typeof arg !== constraint) {
      throw new Error(`argument does not match constraint: typeof ${constraint}`);
    }
  } else if ($Ng(constraint)) {
    try {
      if (arg instanceof constraint) {
        return;
      }
    } catch {
    }
    if (!$Ig(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`);
  }
}

// out-build/vs/base/common/extpath.js
function $Sg(code) {
  return code === 47 || code === 92;
}
function $Tg(osPath) {
  return osPath.replace(/[\\/]/g, $kc.sep);
}
function $Ug(osPath) {
  if (osPath.indexOf("/") === -1) {
    osPath = $Tg(osPath);
  }
  if (/^[a-zA-Z]:(\/|$)/.test(osPath)) {
    osPath = "/" + osPath;
  }
  return osPath;
}
function $Vg(path, sep2 = $kc.sep) {
  if (!path) {
    return "";
  }
  const len = path.length;
  const firstLetter = path.charCodeAt(0);
  if ($Sg(firstLetter)) {
    if ($Sg(path.charCodeAt(1))) {
      if (!$Sg(path.charCodeAt(2))) {
        let pos2 = 3;
        const start = pos2;
        for (; pos2 < len; pos2++) {
          if ($Sg(path.charCodeAt(pos2))) {
            break;
          }
        }
        if (start !== pos2 && !$Sg(path.charCodeAt(pos2 + 1))) {
          pos2 += 1;
          for (; pos2 < len; pos2++) {
            if ($Sg(path.charCodeAt(pos2))) {
              return path.slice(0, pos2 + 1).replace(/[\\/]/g, sep2);
            }
          }
        }
      }
    }
    return sep2;
  } else if ($1g(firstLetter)) {
    if (path.charCodeAt(1) === 58) {
      if ($Sg(path.charCodeAt(2))) {
        return path.slice(0, 2) + sep2;
      } else {
        return path.slice(0, 2);
      }
    }
  }
  let pos = path.indexOf("://");
  if (pos !== -1) {
    pos += 3;
    for (; pos < len; pos++) {
      if ($Sg(path.charCodeAt(pos))) {
        return path.slice(0, pos + 1);
      }
    }
  }
  return "";
}
var WINDOWS_INVALID_FILE_CHARS = /[\\/:\*\?"<>\|]/g;
var UNIX_INVALID_FILE_CHARS = /[/]/g;
var WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])(\.(.*?))?$/i;
function $Xg(name, isWindowsOS = $l) {
  const invalidFileChars = isWindowsOS ? WINDOWS_INVALID_FILE_CHARS : UNIX_INVALID_FILE_CHARS;
  if (!name || name.length === 0 || /^\s+$/.test(name)) {
    return false;
  }
  invalidFileChars.lastIndex = 0;
  if (invalidFileChars.test(name)) {
    return false;
  }
  if (isWindowsOS && WINDOWS_FORBIDDEN_NAMES.test(name)) {
    return false;
  }
  if (name === "." || name === "..") {
    return false;
  }
  if (isWindowsOS && name[name.length - 1] === ".") {
    return false;
  }
  if (isWindowsOS && name.length !== name.trim().length) {
    return false;
  }
  if (name.length > 255) {
    return false;
  }
  return true;
}
function $Yg(pathA, pathB, ignoreCase) {
  const identityEquals = pathA === pathB;
  if (!ignoreCase || identityEquals) {
    return identityEquals;
  }
  if (!pathA || !pathB) {
    return false;
  }
  return $1f(pathA, pathB);
}
function $Zg(base, parentCandidate, ignoreCase, separator = sep) {
  if (base === parentCandidate) {
    return true;
  }
  if (!base || !parentCandidate) {
    return false;
  }
  if (parentCandidate.length > base.length) {
    return false;
  }
  if (ignoreCase) {
    const beginsWith = $2f(base, parentCandidate);
    if (!beginsWith) {
      return false;
    }
    if (parentCandidate.length === base.length) {
      return true;
    }
    let sepOffset = parentCandidate.length;
    if (parentCandidate.charAt(parentCandidate.length - 1) === separator) {
      sepOffset--;
    }
    return base.charAt(sepOffset) === separator;
  }
  if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) {
    parentCandidate += separator;
  }
  return base.indexOf(parentCandidate) === 0;
}
function $1g(char0) {
  return char0 >= 65 && char0 <= 90 || char0 >= 97 && char0 <= 122;
}
function $3g(candidate) {
  if ($l) {
    candidate = $Gf(candidate, sep);
    if (candidate.endsWith(":")) {
      candidate += sep;
    }
  } else {
    candidate = $Gf(candidate, sep);
    if (!candidate) {
      candidate = sep;
    }
  }
  return candidate;
}
function $4g(path) {
  const pathNormalized = $lc(path);
  if ($l) {
    if (path.length > 3) {
      return false;
    }
    return $5g(pathNormalized) && (path.length === 2 || pathNormalized.charCodeAt(2) === 92);
  }
  return pathNormalized === $kc.sep;
}
function $5g(path, isWindowsOS = $l) {
  if (isWindowsOS) {
    return $1g(path.charCodeAt(0)) && path.charCodeAt(1) === 58;
  }
  return false;
}
function $6g(path, isWindowsOS = $l) {
  return $5g(path, isWindowsOS) ? path[0] : void 0;
}
var pathChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var windowsSafePathFirstChars = "BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";
function $9g(parent, prefix, randomLength = 8) {
  let suffix = "";
  for (let i = 0; i < randomLength; i++) {
    let pathCharsTouse;
    if (i === 0 && $l && !prefix && (randomLength === 3 || randomLength === 4)) {
      pathCharsTouse = windowsSafePathFirstChars;
    } else {
      pathCharsTouse = pathChars;
    }
    suffix += pathCharsTouse.charAt(Math.floor(Math.random() * pathCharsTouse.length));
  }
  let randomFileName;
  if (prefix) {
    randomFileName = `${prefix}-${suffix}`;
  } else {
    randomFileName = suffix;
  }
  if (parent) {
    return $nc(parent, randomFileName);
  }
  return randomFileName;
}

// out-build/vs/base/common/uri.js
var _schemePattern = /^\w[\w\d+.-]*$/;
var _singleSlashStart = /^\//;
var _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, path) {
  switch (scheme) {
    case "https":
    case "http":
    case "file":
      if (!path) {
        path = _slash;
      } else if (path[0] !== _slash) {
        path = _slash + path;
      }
      break;
  }
  return path;
}
var _empty = "";
var _slash = "/";
var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
var URI = 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, path, 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, path || _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 $Ac(this, false);
  }
  // ---- modify to new -------------------------
  with(change) {
    if (!change) {
      return this;
    }
    let { scheme, authority, path, 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 (path === void 0) {
      path = this.path;
    } else if (path === null) {
      path = _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 && path === this.path && query === this.query && fragment === this.fragment) {
      return this;
    }
    return new Uri(scheme, authority, path, 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 match = _regexp.exec(value);
    if (!match) {
      return new Uri(_empty, _empty, _empty, _empty, _empty);
    }
    return new Uri(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[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(path) {
    let authority = _empty;
    if ($l) {
      path = path.replace(/\\/g, _slash);
    }
    if (path[0] === _slash && path[1] === _slash) {
      const idx = path.indexOf(_slash, 2);
      if (idx === -1) {
        authority = path.substring(2);
        path = _slash;
      } else {
        authority = path.substring(2, idx);
        path = path.substring(idx) || _slash;
      }
    }
    return new Uri("file", authority, path, _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 result = new Uri(components.scheme, components.authority, components.path, components.query, components.fragment, strict);
    return result;
  }
  /**
   * 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 ($l && uri.scheme === "file") {
      newPath = _URI.file($jc.join($Ac(uri, true), ...pathFragment)).path;
    } else {
      newPath = $kc.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) {
    if (!data) {
      return data;
    } else if (data instanceof _URI) {
      return data;
    } else {
      const result = new Uri(data);
      result._formatted = data.external ?? null;
      result._fsPath = data._sep === _pathSepMarker ? data.fsPath ?? null : null;
      return result;
    }
  }
  [Symbol.for("debug.description")]() {
    return `URI(${this.toString()})`;
  }
};
function $zc(thing) {
  if (!thing || typeof thing !== "object") {
    return false;
  }
  return typeof thing.scheme === "string" && (typeof thing.authority === "string" || typeof thing.authority === "undefined") && (typeof thing.path === "string" || typeof thing.path === "undefined") && (typeof thing.query === "string" || typeof thing.query === "undefined") && (typeof thing.fragment === "string" || typeof thing.fragment === "undefined");
}
var _pathSepMarker = $l ? 1 : void 0;
var Uri = class extends URI {
  constructor() {
    super(...arguments);
    this._formatted = null;
    this._fsPath = null;
  }
  get fsPath() {
    if (!this._fsPath) {
      this._fsPath = $Ac(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;
  }
};
var encodeTable = {
  [
    58
    /* CharCode.Colon */
  ]: "%3A",
  // gen-delims
  [
    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",
  // sub-delims
  [
    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(path) {
  let res = void 0;
  for (let pos = 0; pos < path.length; pos++) {
    const code = path.charCodeAt(pos);
    if (code === 35 || code === 63) {
      if (res === void 0) {
        res = path.substr(0, pos);
      }
      res += encodeTable[code];
    } else {
      if (res !== void 0) {
        res += path[pos];
      }
    }
  }
  return res !== void 0 ? res : path;
}
function $Ac(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 ($l) {
    value = value.replace(/\//g, "\\");
  }
  return value;
}
function _asFormatted(uri, skipEncoding) {
  const encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal;
  let res = "";
  let { scheme, authority, path, 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 (path) {
    if (path.length >= 3 && path.charCodeAt(0) === 47 && path.charCodeAt(2) === 58) {
      const code = path.charCodeAt(1);
      if (code >= 65 && code <= 90) {
        path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`;
      }
    } else if (path.length >= 2 && path.charCodeAt(1) === 58) {
      const code = path.charCodeAt(0);
      if (code >= 65 && code <= 90) {
        path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`;
      }
    }
    res += encoder(path, true, false);
  }
  if (query) {
    res += "?";
    res += encoder(query, false, false);
  }
  if (fragment) {
    res += "#";
    res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
  }
  return res;
}
function decodeURIComponentGraceful(str) {
  try {
    return decodeURIComponent(str);
  } catch {
    if (str.length > 3) {
      return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));
    } else {
      return str;
    }
  }
}
var _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
function percentDecode(str) {
  if (!str.match(_rEncodedAsHex)) {
    return str;
  }
  return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match));
}

// out-build/vs/base/common/network.js
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.vscodeNotebookCellMetadataDiff = "vscode-notebook-cell-metadata-diff";
  Schemas2.vscodeNotebookCellOutput = "vscode-notebook-cell-output";
  Schemas2.vscodeNotebookCellOutputDiff = "vscode-notebook-cell-output-diff";
  Schemas2.vscodeNotebookMetadata = "vscode-notebook-metadata";
  Schemas2.vscodeInteractiveInput = "vscode-interactive-input";
  Schemas2.vscodeSettings = "vscode-settings";
  Schemas2.vscodeWorkspaceTrust = "vscode-workspace-trust";
  Schemas2.vscodeTerminal = "vscode-terminal";
  Schemas2.vscodeChatCodeBlock = "vscode-chat-code-block";
  Schemas2.vscodeChatCodeCompareBlock = "vscode-chat-code-compare-block";
  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";
  Schemas2.commentsInput = "comment";
  Schemas2.codeSetting = "code-setting";
  Schemas2.outputChannel = "output";
  Schemas2.accessibleView = "accessible-view";
})(Schemas || (Schemas = {}));
function $0g(target, scheme) {
  if (URI.isUri(target)) {
    return $1f(target.scheme, scheme);
  } else {
    return $2f(target, scheme + ":");
  }
}
function $$g(target, ...schemes) {
  return schemes.some((scheme) => $0g(target, scheme));
}
var $ah = "tkn";
var RemoteAuthoritiesImpl = class {
  constructor() {
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = /* @__PURE__ */ Object.create(null);
    this.c = /* @__PURE__ */ Object.create(null);
    this.d = "http";
    this.e = null;
    this.f = "/";
  }
  setPreferredWebSchema(schema) {
    this.d = schema;
  }
  setDelegate(delegate) {
    this.e = delegate;
  }
  setServerRootPath(product2, serverBasePath) {
    this.f = $ch(product2, serverBasePath);
  }
  getServerRootPath() {
    return this.f;
  }
  get g() {
    return $kc.join(this.f, Schemas.vscodeRemoteResource);
  }
  set(authority, host, port) {
    this.a[authority] = host;
    this.b[authority] = port;
  }
  setConnectionToken(authority, connectionToken) {
    this.c[authority] = connectionToken;
  }
  getPreferredWebSchema() {
    return this.d;
  }
  rewrite(uri) {
    if (this.e) {
      try {
        return this.e(uri);
      } catch (err) {
        $gb(err);
        return uri;
      }
    }
    const authority = uri.authority;
    let host = this.a[authority];
    if (host && host.indexOf(":") !== -1 && host.indexOf("[") === -1) {
      host = `[${host}]`;
    }
    const port = this.b[authority];
    const connectionToken = this.c[authority];
    let query = `path=${encodeURIComponent(uri.path)}`;
    if (typeof connectionToken === "string") {
      query += `&${$ah}=${encodeURIComponent(connectionToken)}`;
    }
    return URI.from({
      scheme: $r ? this.d : Schemas.vscodeRemoteResource,
      authority: `${host}:${port}`,
      path: $r ? (window.location.pathname + "/" + this.g).replace(/\/\/+/g, "/") : this.g,
      query
    });
  }
};
var $bh = new RemoteAuthoritiesImpl();
function $ch(product2, basePath) {
  return $kc.join(basePath ?? "/", `${product2.quality ?? "oss"}-${product2.commit ?? "dev"}`);
}
var $hh = "vscode-app";
var FileAccessImpl = class _FileAccessImpl {
  static {
    this.a = $hh;
  }
  /**
   * 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.
   */
  asBrowserUri(resourcePath) {
    const uri = this.b(resourcePath);
    return this.uriToBrowserUri(uri);
  }
  /**
   * 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 $bh.rewrite(uri);
    }
    if (
      // ...only ever for `file` resources
      uri.scheme === Schemas.file && // ...and we run in native environments
      ($p || // ...or web worker extensions on desktop
      $t === `${Schemas.vscodeFileResource}://${_FileAccessImpl.a}`)
    ) {
      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.a,
        query: null,
        fragment: null
      });
    }
    return uri;
  }
  /**
   * Returns the `file` URI to use in contexts where node.js
   * is responsible for loading.
   */
  asFileUri(resourcePath) {
    const uri = this.b(resourcePath);
    return this.uriToFileUri(uri);
  }
  /**
   * Returns the `file` URI to use in contexts where node.js
   * is responsible for loading.
   */
  uriToFileUri(uri) {
    if (uri.scheme === Schemas.vscodeFileResource) {
      return uri.with({
        scheme: Schemas.file,
        // Only preserve the `authority` if it is different from
        // our fallback authority. This ensures we properly preserve
        // Windows UNC paths that come with their own authority.
        authority: uri.authority !== _FileAccessImpl.a ? uri.authority : null,
        query: null,
        fragment: null
      });
    }
    return uri;
  }
  b(uriOrModule, moduleIdToUrl) {
    if (URI.isUri(uriOrModule)) {
      return uriOrModule;
    }
    if (globalThis._VSCODE_FILE_ROOT) {
      const rootUriOrPath = globalThis._VSCODE_FILE_ROOT;
      if (/^\w[\w\d+.-]*:\/\//.test(rootUriOrPath)) {
        return URI.joinPath(URI.parse(rootUriOrPath, true), uriOrModule);
      }
      const modulePath = $nc(rootUriOrPath, uriOrModule);
      return URI.file(modulePath);
    }
    return URI.parse(moduleIdToUrl.toUrl(uriOrModule));
  }
};
var $ih = 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?.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 = {}));

// out-build/vs/base/common/resources.js
function $jh(uri) {
  return $Ac(uri, true);
}
var $kh = class {
  constructor(a) {
    this.a = a;
  }
  compare(uri1, uri2, ignoreFragment = false) {
    if (uri1 === uri2) {
      return 0;
    }
    return $Tf(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.a(uri) ? uri.path.toLowerCase() : void 0,
      fragment: ignoreFragment ? null : void 0
    }).toString();
  }
  ignorePathCasing(uri) {
    return this.a(uri);
  }
  isEqualOrParent(base, parentCandidate, ignoreFragment = false) {
    if (base.scheme === parentCandidate.scheme) {
      if (base.scheme === Schemas.file) {
        return $Zg($jh(base), $jh(parentCandidate), this.a(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
      }
      if ($Ah(base.authority, parentCandidate.authority)) {
        return $Zg(base.path, parentCandidate.path, this.a(base), "/") && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
      }
    }
    return false;
  }
  // --- path math
  joinPath(resource, ...pathFragment) {
    return URI.joinPath(resource, ...pathFragment);
  }
  basenameOrAuthority(resource) {
    return $sh(resource) || resource.authority;
  }
  basename(resource) {
    return $kc.basename(resource.path);
  }
  extname(resource) {
    return $kc.extname(resource.path);
  }
  dirname(resource) {
    if (resource.path.length === 0) {
      return resource;
    }
    let dirname;
    if (resource.scheme === Schemas.file) {
      dirname = URI.file($qc($jh(resource))).path;
    } else {
      dirname = $kc.dirname(resource.path);
      if (resource.authority && dirname.length && dirname.charCodeAt(0) !== 47) {
        console.error(`dirname("${resource.toString})) resulted in a relative path`);
        dirname = "/";
      }
    }
    return resource.with({
      path: dirname
    });
  }
  normalizePath(resource) {
    if (!resource.path.length) {
      return resource;
    }
    let normalizedPath;
    if (resource.scheme === Schemas.file) {
      normalizedPath = URI.file($lc($jh(resource))).path;
    } else {
      normalizedPath = $kc.normalize(resource.path);
    }
    return resource.with({
      path: normalizedPath
    });
  }
  relativePath(from, to) {
    if (from.scheme !== to.scheme || !$Ah(from.authority, to.authority)) {
      return void 0;
    }
    if (from.scheme === Schemas.file) {
      const relativePath = $pc($jh(from), $jh(to));
      return $l ? $Tg(relativePath) : relativePath;
    }
    let fromPath = from.path || "/";
    const toPath = to.path || "/";
    if (this.a(from)) {
      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 $kc.relative(fromPath, toPath);
  }
  resolvePath(base, path) {
    if (base.scheme === Schemas.file) {
      const newURI = URI.file($oc($jh(base), path));
      return base.with({
        authority: newURI.authority,
        path: newURI.path
      });
    }
    path = $Ug(path);
    return base.with({
      path: $kc.resolve(base.path, path)
    });
  }
  // --- misc
  isAbsolutePath(resource) {
    return !!resource.path && resource.path[0] === "/";
  }
  isEqualAuthority(a1, a2) {
    return a1 === a2 || a1 !== void 0 && a2 !== void 0 && $1f(a1, a2);
  }
  hasTrailingPathSeparator(resource, sep2 = sep) {
    if (resource.scheme === Schemas.file) {
      const fsp = $jh(resource);
      return fsp.length > $Vg(fsp).length && fsp[fsp.length - 1] === sep2;
    } else {
      const p = resource.path;
      return p.length > 1 && p.charCodeAt(p.length - 1) === 47 && !/^[a-zA-Z]:(\/$|\\$)/.test(resource.fsPath);
    }
  }
  removeTrailingPathSeparator(resource, sep2 = sep) {
    if ($Bh(resource, sep2)) {
      return resource.with({ path: resource.path.substr(0, resource.path.length - 1) });
    }
    return resource;
  }
  addTrailingPathSeparator(resource, sep2 = sep) {
    let isRootSep = false;
    if (resource.scheme === Schemas.file) {
      const fsp = $jh(resource);
      isRootSep = fsp !== void 0 && fsp.length === $Vg(fsp).length && fsp[fsp.length - 1] === sep2;
    } else {
      sep2 = "/";
      const p = resource.path;
      isRootSep = p.length === 1 && p.charCodeAt(p.length - 1) === 47;
    }
    if (!isRootSep && !$Bh(resource, sep2)) {
      return resource.with({ path: resource.path + "/" });
    }
    return resource;
  }
};
var $lh = new $kh(() => false);
var $mh = new $kh((uri) => {
  return uri.scheme === Schemas.file ? !$n : true;
});
var $nh = new $kh((_) => true);
var $oh = $lh.isEqual.bind($lh);
var $ph = $lh.isEqualOrParent.bind($lh);
var $qh = $lh.getComparisonKey.bind($lh);
var $rh = $lh.basenameOrAuthority.bind($lh);
var $sh = $lh.basename.bind($lh);
var $th = $lh.extname.bind($lh);
var $uh = $lh.dirname.bind($lh);
var $vh = $lh.joinPath.bind($lh);
var $wh = $lh.normalizePath.bind($lh);
var $xh = $lh.relativePath.bind($lh);
var $yh = $lh.resolvePath.bind($lh);
var $zh = $lh.isAbsolutePath.bind($lh);
var $Ah = $lh.isEqualAuthority.bind($lh);
var $Bh = $lh.hasTrailingPathSeparator.bind($lh);
var $Ch = $lh.removeTrailingPathSeparator.bind($lh);
var $Dh = $lh.addTrailingPathSeparator.bind($lh);
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 = {}));

// out-build/vs/base/common/symbols.js
var $ue = Symbol("MicrotaskDelay");

// out-build/vs/base/common/async.js
function $Gh(obj) {
  return !!obj && typeof obj.then === "function";
}
function $Hh(callback) {
  const source = new $ad();
  const thenable = callback(source.token);
  const promise = new Promise((resolve, reject) => {
    const subscription = source.token.onCancellationRequested(() => {
      subscription.dispose();
      reject(new $lb());
    });
    Promise.resolve(thenable).then((value) => {
      subscription.dispose();
      source.dispose();
      resolve(value);
    }, (err) => {
      subscription.dispose();
      source.dispose();
      reject(err);
    });
  });
  return new class {
    cancel() {
      source.cancel();
      source.dispose();
    }
    then(resolve, reject) {
      return promise.then(resolve, reject);
    }
    catch(reject) {
      return this.then(void 0, reject);
    }
    finally(onfinally) {
      return promise.finally(onfinally);
    }
  }();
}
function $Ih(promise, token, defaultValue) {
  return new Promise((resolve, reject) => {
    const ref = token.onCancellationRequested(() => {
      ref.dispose();
      resolve(defaultValue);
    });
    promise.then(resolve, reject).finally(() => ref.dispose());
  });
}
function $Jh(promise, token) {
  return new Promise((resolve, reject) => {
    const ref = token.onCancellationRequested(() => {
      ref.dispose();
      reject(new $lb());
    });
    promise.then(resolve, reject).finally(() => ref.dispose());
  });
}
function $Nh(callback) {
  return new Promise((resolve, reject) => {
    const item = callback();
    if ($Gh(item)) {
      item.then(resolve, reject);
    } else {
      resolve(item);
    }
  });
}
function $Oh() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}
var $Ph = class {
  constructor() {
    this.f = false;
    this.a = null;
    this.b = null;
    this.d = null;
  }
  queue(promiseFactory) {
    if (this.f) {
      return Promise.reject(new Error("Throttler is disposed"));
    }
    if (this.a) {
      this.d = promiseFactory;
      if (!this.b) {
        const onComplete = () => {
          this.b = null;
          if (this.f) {
            return;
          }
          const result = this.queue(this.d);
          this.d = null;
          return result;
        };
        this.b = new Promise((resolve) => {
          this.a.then(onComplete, onComplete).then(resolve);
        });
      }
      return new Promise((resolve, reject) => {
        this.b.then(resolve, reject);
      });
    }
    this.a = promiseFactory();
    return new Promise((resolve, reject) => {
      this.a.then((result) => {
        this.a = null;
        resolve(result);
      }, (err) => {
        this.a = null;
        reject(err);
      });
    });
  }
  dispose() {
    this.f = true;
  }
};
var timeoutDeferred = (timeout, fn) => {
  let scheduled = true;
  const handle = setTimeout(() => {
    scheduled = false;
    fn();
  }, timeout);
  return {
    isTriggered: () => scheduled,
    dispose: () => {
      clearTimeout(handle);
      scheduled = false;
    }
  };
};
var microtaskDeferred = (fn) => {
  let scheduled = true;
  queueMicrotask(() => {
    if (scheduled) {
      scheduled = false;
      fn();
    }
  });
  return {
    isTriggered: () => scheduled,
    dispose: () => {
      scheduled = false;
    }
  };
};
var $Sh = class {
  constructor(defaultDelay) {
    this.defaultDelay = defaultDelay;
    this.a = null;
    this.b = null;
    this.d = null;
    this.f = null;
    this.g = null;
  }
  trigger(task, delay = this.defaultDelay) {
    this.g = task;
    this.h();
    if (!this.b) {
      this.b = new Promise((resolve, reject) => {
        this.d = resolve;
        this.f = reject;
      }).then(() => {
        this.b = null;
        this.d = null;
        if (this.g) {
          const task2 = this.g;
          this.g = null;
          return task2();
        }
        return void 0;
      });
    }
    const fn = () => {
      this.a = null;
      this.d?.(null);
    };
    this.a = delay === $ue ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);
    return this.b;
  }
  isTriggered() {
    return !!this.a?.isTriggered();
  }
  cancel() {
    this.h();
    if (this.b) {
      this.f?.(new $lb());
      this.b = null;
    }
  }
  h() {
    this.a?.dispose();
    this.a = null;
  }
  dispose() {
    this.cancel();
  }
};
var $Th = class {
  constructor(defaultDelay) {
    this.a = new $Sh(defaultDelay);
    this.b = new $Ph();
  }
  trigger(promiseFactory, delay) {
    return this.a.trigger(() => this.b.queue(promiseFactory), delay);
  }
  isTriggered() {
    return this.a.isTriggered();
  }
  cancel() {
    this.a.cancel();
  }
  dispose() {
    this.a.dispose();
    this.b.dispose();
  }
};
var $Uh = class {
  constructor() {
    this.a = false;
    this.b = new Promise((c, e) => {
      this.d = c;
    });
  }
  isOpen() {
    return this.a;
  }
  open() {
    this.a = true;
    this.d(true);
  }
  wait() {
    return this.b;
  }
};
function $Wh(millis, token) {
  if (!token) {
    return $Hh((token2) => $Wh(millis, token2));
  }
  return new Promise((resolve, reject) => {
    const handle = setTimeout(() => {
      disposable.dispose();
      resolve();
    }, millis);
    const disposable = token.onCancellationRequested(() => {
      clearTimeout(handle);
      disposable.dispose();
      reject(new $lb());
    });
  });
}
function $Xh(handler, timeout = 0, store) {
  const timer2 = setTimeout(() => {
    handler();
    if (store) {
      disposable.dispose();
    }
  }, timeout);
  const disposable = $1c(() => {
    clearTimeout(timer2);
    store?.deleteAndLeak(disposable);
  });
  store?.add(disposable);
  return disposable;
}
function $1h(promiseList, shouldStop = (t) => !!t, defaultValue = null) {
  if (promiseList.length === 0) {
    return Promise.resolve(defaultValue);
  }
  let todo = promiseList.length;
  const finish = () => {
    todo = -1;
    for (const promise of promiseList) {
      promise.cancel?.();
    }
  };
  return new Promise((resolve, reject) => {
    for (const promise of promiseList) {
      promise.then((result) => {
        if (--todo >= 0 && shouldStop(result)) {
          finish();
          resolve(result);
        } else if (todo === 0) {
          resolve(defaultValue);
        }
      }).catch((err) => {
        if (--todo >= 0) {
          finish();
          reject(err);
        }
      });
    }
  });
}
var $2h = class {
  constructor(maxDegreeOfParalellism) {
    this.a = 0;
    this.b = false;
    this.f = maxDegreeOfParalellism;
    this.g = [];
    this.d = 0;
    this.h = new $ze();
  }
  /**
   *
   * @returns A promise that resolved when all work is done (onDrained) or when
   * there is nothing to do
   */
  whenIdle() {
    return this.size > 0 ? Event.toPromise(this.onDrained) : Promise.resolve();
  }
  get onDrained() {
    return this.h.event;
  }
  get size() {
    return this.a;
  }
  queue(factory) {
    if (this.b) {
      throw new Error("Object has been disposed");
    }
    this.a++;
    return new Promise((c, e) => {
      this.g.push({ factory, c, e });
      this.j();
    });
  }
  j() {
    while (this.g.length && this.d < this.f) {
      const iLimitedTask = this.g.shift();
      this.d++;
      const promise = iLimitedTask.factory();
      promise.then(iLimitedTask.c, iLimitedTask.e);
      promise.then(() => this.k(), () => this.k());
    }
  }
  k() {
    if (this.b) {
      return;
    }
    this.d--;
    if (--this.a === 0) {
      this.h.fire();
    }
    if (this.g.length > 0) {
      this.j();
    }
  }
  clear() {
    if (this.b) {
      throw new Error("Object has been disposed");
    }
    this.g.length = 0;
    this.a = this.d;
  }
  dispose() {
    this.b = true;
    this.g.length = 0;
    this.a = 0;
    this.h.dispose();
  }
};
var $3h = class extends $2h {
  constructor() {
    super(1);
  }
};
var $5h = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Set();
    this.d = void 0;
    this.f = 0;
  }
  async whenDrained() {
    if (this.g()) {
      return;
    }
    const promise = new $gi();
    this.b.add(promise);
    return promise.p;
  }
  g() {
    for (const [, queue] of this.a) {
      if (queue.size > 0) {
        return false;
      }
    }
    return true;
  }
  queueSize(resource, extUri = $lh) {
    const key = extUri.getComparisonKey(resource);
    return this.a.get(key)?.size ?? 0;
  }
  queueFor(resource, factory, extUri = $lh) {
    const key = extUri.getComparisonKey(resource);
    let queue = this.a.get(key);
    if (!queue) {
      queue = new $3h();
      const drainListenerId = this.f++;
      const drainListener = Event.once(queue.onDrained)(() => {
        queue?.dispose();
        this.a.delete(key);
        this.h();
        this.d?.deleteAndDispose(drainListenerId);
        if (this.d?.size === 0) {
          this.d.dispose();
          this.d = void 0;
        }
      });
      if (!this.d) {
        this.d = new $_c();
      }
      this.d.set(drainListenerId, drainListener);
      this.a.set(key, queue);
    }
    return queue.queue(factory);
  }
  h() {
    if (!this.g()) {
      return;
    }
    this.j();
  }
  j() {
    for (const drainer of this.b) {
      drainer.complete();
    }
    this.b.clear();
  }
  dispose() {
    for (const [, queue] of this.a) {
      queue.dispose();
    }
    this.a.clear();
    this.j();
    this.d?.dispose();
  }
};
var $7h = class {
  constructor() {
    this.d = void 0;
    this.f = false;
  }
  cancel() {
    this.d?.dispose();
    this.d = void 0;
  }
  cancelAndSet(runner, interval, context = globalThis) {
    if (this.f) {
      throw new $vb(`Calling 'cancelAndSet' on a disposed IntervalTimer`);
    }
    this.cancel();
    const handle = context.setInterval(() => {
      runner();
    }, interval);
    this.d = $1c(() => {
      context.clearInterval(handle);
      this.d = void 0;
    });
  }
  dispose() {
    this.cancel();
    this.f = true;
  }
};
var $8h = class {
  constructor(runner, delay) {
    this.b = -1;
    this.a = runner;
    this.d = delay;
    this.f = this.g.bind(this);
  }
  /**
   * Dispose RunOnceScheduler
   */
  dispose() {
    this.cancel();
    this.a = null;
  }
  /**
   * Cancel current scheduled runner (if any).
   */
  cancel() {
    if (this.isScheduled()) {
      clearTimeout(this.b);
      this.b = -1;
    }
  }
  /**
   * Cancel previous runner (if any) & schedule a new runner.
   */
  schedule(delay = this.d) {
    this.cancel();
    this.b = setTimeout(this.f, delay);
  }
  get delay() {
    return this.d;
  }
  set delay(value) {
    this.d = value;
  }
  /**
   * Returns true if scheduled.
   */
  isScheduled() {
    return this.b !== -1;
  }
  flush() {
    if (this.isScheduled()) {
      this.cancel();
      this.h();
    }
  }
  g() {
    this.b = -1;
    if (this.a) {
      this.h();
    }
  }
  h() {
    this.a?.();
  }
};
var $9h = class {
  constructor(runner, delay) {
    if (delay % 1e3 !== 0) {
      console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`);
    }
    this.a = runner;
    this.b = delay;
    this.d = 0;
    this.f = -1;
    this.g = this.h.bind(this);
  }
  dispose() {
    this.cancel();
    this.a = null;
  }
  cancel() {
    if (this.isScheduled()) {
      clearInterval(this.f);
      this.f = -1;
    }
  }
  /**
   * Cancel previous runner (if any) & schedule a new runner.
   */
  schedule(delay = this.b) {
    if (delay % 1e3 !== 0) {
      console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`);
    }
    this.cancel();
    this.d = Math.ceil(delay / 1e3);
    this.f = setInterval(this.g, 1e3);
  }
  /**
   * Returns true if scheduled.
   */
  isScheduled() {
    return this.f !== -1;
  }
  h() {
    this.d--;
    if (this.d > 0) {
      return;
    }
    clearInterval(this.f);
    this.f = -1;
    this.a?.();
  }
};
var $0h = class extends $8h {
  constructor(runner, timeout) {
    super(runner, timeout);
    this.j = [];
  }
  work(unit) {
    this.j.push(unit);
    if (!this.isScheduled()) {
      this.schedule();
    }
  }
  h() {
    const units = this.j;
    this.j = [];
    this.a?.(units);
  }
  dispose() {
    this.j = [];
    super.dispose();
  }
};
var $$h = class extends $3c {
  constructor(h, j) {
    super();
    this.h = h;
    this.j = j;
    this.a = [];
    this.b = this.B(new $4c());
    this.f = false;
    this.g = 0;
  }
  /**
   * The number of work units that are pending to be processed.
   */
  get pending() {
    return this.a.length;
  }
  /**
   * Add units to be worked on. Use `pending` to figure out
   * how many units are not yet processed after this method
   * was called.
   *
   * @returns whether the work was accepted or not. If the
   * worker is disposed, it will not accept any more work.
   * If the number of pending units would become larger
   * than `maxPendingWork`, more work will also not be accepted.
   */
  work(units) {
    if (this.f) {
      return false;
    }
    if (typeof this.h.maxBufferedWork === "number") {
      if (this.b.value) {
        if (this.pending + units.length > this.h.maxBufferedWork) {
          return false;
        }
      } else {
        if (this.pending + units.length - this.h.maxWorkChunkSize > this.h.maxBufferedWork) {
          return false;
        }
      }
    }
    for (const unit of units) {
      this.a.push(unit);
    }
    const timeSinceLastExecution = Date.now() - this.g;
    if (!this.b.value && (!this.h.waitThrottleDelayBetweenWorkUnits || timeSinceLastExecution >= this.h.throttleDelay)) {
      this.m();
    } else if (!this.b.value && this.h.waitThrottleDelayBetweenWorkUnits) {
      this.r(Math.max(this.h.throttleDelay - timeSinceLastExecution, 0));
    } else {
    }
    return true;
  }
  m() {
    this.g = Date.now();
    this.j(this.a.splice(0, this.h.maxWorkChunkSize));
    if (this.a.length > 0) {
      this.r();
    }
  }
  r(delay = this.h.throttleDelay) {
    this.b.value = new $8h(() => {
      this.b.clear();
      this.m();
    }, delay);
    this.b.value.schedule();
  }
  dispose() {
    super.dispose();
    this.f = true;
  }
};
var $_h;
var $ai;
(function() {
  if (typeof globalThis.requestIdleCallback !== "function" || typeof globalThis.cancelIdleCallback !== "function") {
    $ai = (_targetWindow, runner, timeout) => {
      $E(() => {
        if (disposed) {
          return;
        }
        const end = Date.now() + 15;
        const deadline = {
          didTimeout: true,
          timeRemaining() {
            return Math.max(0, end - Date.now());
          }
        };
        runner(Object.freeze(deadline));
      });
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
        }
      };
    };
  } else {
    $ai = (targetWindow, runner, timeout) => {
      const handle = targetWindow.requestIdleCallback(runner, typeof timeout === "number" ? { timeout } : void 0);
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
          targetWindow.cancelIdleCallback(handle);
        }
      };
    };
  }
  $_h = (runner, timeout) => $ai(globalThis, runner, timeout);
})();
var $bi = class {
  constructor(targetWindow, executor) {
    this.g = false;
    this.d = () => {
      try {
        this.j = executor();
      } catch (err) {
        this.l = err;
      } finally {
        this.g = true;
      }
    };
    this.f = $ai(targetWindow, () => this.d());
  }
  dispose() {
    this.f.dispose();
  }
  get value() {
    if (!this.g) {
      this.f.dispose();
      this.d();
    }
    if (this.l) {
      throw this.l;
    }
    return this.j;
  }
  get isInitialized() {
    return this.g;
  }
};
var $ci = class extends $bi {
  constructor(executor) {
    super(globalThis, executor);
  }
};
async function $di(task, delay, retries) {
  let lastError;
  for (let i = 0; i < retries; i++) {
    try {
      return await task();
    } catch (error) {
      lastError = error;
      await $Wh(delay);
    }
  }
  throw lastError;
}
var DeferredOutcome;
(function(DeferredOutcome2) {
  DeferredOutcome2[DeferredOutcome2["Resolved"] = 0] = "Resolved";
  DeferredOutcome2[DeferredOutcome2["Rejected"] = 1] = "Rejected";
})(DeferredOutcome || (DeferredOutcome = {}));
var $gi = class {
  get isRejected() {
    return this.d?.outcome === 1;
  }
  get isResolved() {
    return this.d?.outcome === 0;
  }
  get isSettled() {
    return !!this.d;
  }
  get value() {
    return this.d?.outcome === 0 ? this.d?.value : void 0;
  }
  constructor() {
    this.p = new Promise((c, e) => {
      this.a = c;
      this.b = e;
    });
  }
  complete(value) {
    return new Promise((resolve) => {
      this.a(value);
      this.d = { outcome: 0, value };
      resolve();
    });
  }
  error(err) {
    return new Promise((resolve) => {
      this.b(err);
      this.d = { outcome: 1, value: err };
      resolve();
    });
  }
  cancel() {
    return this.error(new $lb());
  }
};
var Promises;
(function(Promises3) {
  async function settled(promises8) {
    let firstError = void 0;
    const result = await Promise.all(promises8.map((promise) => promise.then((value) => value, (error) => {
      if (!firstError) {
        firstError = error;
      }
      return void 0;
    })));
    if (typeof firstError !== "undefined") {
      throw firstError;
    }
    return result;
  }
  Promises3.settled = settled;
  function withAsyncBody(bodyFn) {
    return new Promise(async (resolve, reject) => {
      try {
        await bodyFn(resolve, reject);
      } catch (error) {
        reject(error);
      }
    });
  }
  Promises3.withAsyncBody = withAsyncBody;
})(Promises || (Promises = {}));
var AsyncIterableSourceState;
(function(AsyncIterableSourceState2) {
  AsyncIterableSourceState2[AsyncIterableSourceState2["Initial"] = 0] = "Initial";
  AsyncIterableSourceState2[AsyncIterableSourceState2["DoneOK"] = 1] = "DoneOK";
  AsyncIterableSourceState2[AsyncIterableSourceState2["DoneError"] = 2] = "DoneError";
})(AsyncIterableSourceState || (AsyncIterableSourceState = {}));
var $ji = class _$ji {
  static fromArray(items) {
    return new _$ji((writer) => {
      writer.emitMany(items);
    });
  }
  static fromPromise(promise) {
    return new _$ji(async (emitter) => {
      emitter.emitMany(await promise);
    });
  }
  static fromPromisesResolveOrder(promises8) {
    return new _$ji(async (emitter) => {
      await Promise.all(promises8.map(async (p) => emitter.emitOne(await p)));
    });
  }
  static merge(iterables) {
    return new _$ji(async (emitter) => {
      await Promise.all(iterables.map(async (iterable) => {
        for await (const item of iterable) {
          emitter.emitOne(item);
        }
      }));
    });
  }
  static {
    this.EMPTY = _$ji.fromArray([]);
  }
  constructor(executor, onReturn) {
    this.a = 0;
    this.b = [];
    this.d = null;
    this.f = onReturn;
    this.g = new $ze();
    queueMicrotask(async () => {
      const writer = {
        emitOne: (item) => this.h(item),
        emitMany: (items) => this.j(items),
        reject: (error) => this.l(error)
      };
      try {
        await Promise.resolve(executor(writer));
        this.k();
      } catch (err) {
        this.l(err);
      } finally {
        writer.emitOne = void 0;
        writer.emitMany = void 0;
        writer.reject = void 0;
      }
    });
  }
  [Symbol.asyncIterator]() {
    let i = 0;
    return {
      next: async () => {
        do {
          if (this.a === 2) {
            throw this.d;
          }
          if (i < this.b.length) {
            return { done: false, value: this.b[i++] };
          }
          if (this.a === 1) {
            return { done: true, value: void 0 };
          }
          await Event.toPromise(this.g.event);
        } while (true);
      },
      return: async () => {
        this.f?.();
        return { done: true, value: void 0 };
      }
    };
  }
  static map(iterable, mapFn) {
    return new _$ji(async (emitter) => {
      for await (const item of iterable) {
        emitter.emitOne(mapFn(item));
      }
    });
  }
  map(mapFn) {
    return _$ji.map(this, mapFn);
  }
  static filter(iterable, filterFn) {
    return new _$ji(async (emitter) => {
      for await (const item of iterable) {
        if (filterFn(item)) {
          emitter.emitOne(item);
        }
      }
    });
  }
  filter(filterFn) {
    return _$ji.filter(this, filterFn);
  }
  static coalesce(iterable) {
    return _$ji.filter(iterable, (item) => !!item);
  }
  coalesce() {
    return _$ji.coalesce(this);
  }
  static async toPromise(iterable) {
    const result = [];
    for await (const item of iterable) {
      result.push(item);
    }
    return result;
  }
  toPromise() {
    return _$ji.toPromise(this);
  }
  /**
   * The value will be appended at the end.
   *
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  h(value) {
    if (this.a !== 0) {
      return;
    }
    this.b.push(value);
    this.g.fire();
  }
  /**
   * The values will be appended at the end.
   *
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  j(values) {
    if (this.a !== 0) {
      return;
    }
    this.b = this.b.concat(values);
    this.g.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.
   */
  k() {
    if (this.a !== 0) {
      return;
    }
    this.a = 1;
    this.g.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.
   */
  l(error) {
    if (this.a !== 0) {
      return;
    }
    this.a = 2;
    this.d = error;
    this.g.fire();
  }
};
var $mi = class {
  /**
   *
   * @param onReturn A function that will be called when consuming the async iterable
   * has finished by the consumer, e.g the for-await-loop has be existed (break, return) early.
   * This is NOT called when resolving this source by its owner.
   */
  constructor(onReturn) {
    this.a = new $gi();
    this.b = new $ji((emitter) => {
      if (earlyError) {
        emitter.reject(earlyError);
        return;
      }
      if (earlyItems) {
        emitter.emitMany(earlyItems);
      }
      this.d = (error) => emitter.reject(error);
      this.f = (item) => emitter.emitOne(item);
      return this.a.p;
    }, onReturn);
    let earlyError;
    let earlyItems;
    this.f = (item) => {
      if (!earlyItems) {
        earlyItems = [];
      }
      earlyItems.push(item);
    };
    this.d = (error) => {
      if (!earlyError) {
        earlyError = error;
      }
    };
  }
  get asyncIterable() {
    return this.b;
  }
  resolve() {
    this.a.complete();
  }
  reject(error) {
    this.d(error);
    this.a.complete();
  }
  emitOne(item) {
    this.f(item);
  }
};

// out-build/vs/base/common/stream.js
function $qi(reducer, options2) {
  return new WriteableStreamImpl(reducer, options2);
}
var WriteableStreamImpl = class {
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.a = {
      flowing: false,
      ended: false,
      destroyed: false
    };
    this.b = {
      data: [],
      error: []
    };
    this.c = {
      data: [],
      error: [],
      end: []
    };
    this.d = [];
  }
  pause() {
    if (this.a.destroyed) {
      return;
    }
    this.a.flowing = false;
  }
  resume() {
    if (this.a.destroyed) {
      return;
    }
    if (!this.a.flowing) {
      this.a.flowing = true;
      this.j();
      this.k();
      this.l();
    }
  }
  write(data) {
    if (this.a.destroyed) {
      return;
    }
    if (this.a.flowing) {
      this.g(data);
    } else {
      this.b.data.push(data);
      if (typeof this.f?.highWaterMark === "number" && this.b.data.length > this.f.highWaterMark) {
        return new Promise((resolve) => this.d.push(resolve));
      }
    }
  }
  error(error) {
    if (this.a.destroyed) {
      return;
    }
    if (this.a.flowing) {
      this.h(error);
    } else {
      this.b.error.push(error);
    }
  }
  end(result) {
    if (this.a.destroyed) {
      return;
    }
    if (typeof result !== "undefined") {
      this.write(result);
    }
    if (this.a.flowing) {
      this.i();
      this.destroy();
    } else {
      this.a.ended = true;
    }
  }
  g(data) {
    this.c.data.slice(0).forEach((listener) => listener(data));
  }
  h(error) {
    if (this.c.error.length === 0) {
      $gb(error);
    } else {
      this.c.error.slice(0).forEach((listener) => listener(error));
    }
  }
  i() {
    this.c.end.slice(0).forEach((listener) => listener());
  }
  on(event, callback) {
    if (this.a.destroyed) {
      return;
    }
    switch (event) {
      case "data":
        this.c.data.push(callback);
        this.resume();
        break;
      case "end":
        this.c.end.push(callback);
        if (this.a.flowing && this.l()) {
          this.destroy();
        }
        break;
      case "error":
        this.c.error.push(callback);
        if (this.a.flowing) {
          this.k();
        }
        break;
    }
  }
  removeListener(event, callback) {
    if (this.a.destroyed) {
      return;
    }
    let listeners = void 0;
    switch (event) {
      case "data":
        listeners = this.c.data;
        break;
      case "end":
        listeners = this.c.end;
        break;
      case "error":
        listeners = this.c.error;
        break;
    }
    if (listeners) {
      const index = listeners.indexOf(callback);
      if (index >= 0) {
        listeners.splice(index, 1);
      }
    }
  }
  j() {
    if (this.b.data.length > 0) {
      const fullDataBuffer = this.e(this.b.data);
      this.g(fullDataBuffer);
      this.b.data.length = 0;
      const pendingWritePromises = [...this.d];
      this.d.length = 0;
      pendingWritePromises.forEach((pendingWritePromise) => pendingWritePromise());
    }
  }
  k() {
    if (this.c.error.length > 0) {
      for (const error of this.b.error) {
        this.h(error);
      }
      this.b.error.length = 0;
    }
  }
  l() {
    if (this.a.ended) {
      this.i();
      return this.c.end.length > 0;
    }
    return false;
  }
  destroy() {
    if (!this.a.destroyed) {
      this.a.destroyed = true;
      this.a.ended = true;
      this.b.data.length = 0;
      this.b.error.length = 0;
      this.c.data.length = 0;
      this.c.error.length = 0;
      this.c.end.length = 0;
      this.d.length = 0;
    }
  }
};
function $ti(stream, reducer) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    $ui(stream, {
      onData: (chunk) => {
        if (reducer) {
          chunks.push(chunk);
        }
      },
      onError: (error) => {
        if (reducer) {
          reject(error);
        } else {
          resolve(void 0);
        }
      },
      onEnd: () => {
        if (reducer) {
          resolve(reducer(chunks));
        } else {
          resolve(void 0);
        }
      }
    });
  });
}
function $ui(stream, listener, token) {
  stream.on("error", (error) => {
    if (!token?.isCancellationRequested) {
      listener.onError(error);
    }
  });
  stream.on("end", () => {
    if (!token?.isCancellationRequested) {
      listener.onEnd();
    }
  });
  stream.on("data", (data) => {
    if (!token?.isCancellationRequested) {
      listener.onData(data);
    }
  });
}
function $zi(stream, transformer, reducer) {
  const target = $qi(reducer);
  $ui(stream, {
    onData: (data) => target.write(transformer.data(data)),
    onError: (error) => target.error(transformer.error ? transformer.error(error) : error),
    onEnd: () => target.end()
  });
  return target;
}

// out-build/vs/base/common/buffer.js
var hasBuffer = typeof Buffer !== "undefined";
var indexOfTable = new $sf(() => new Uint8Array(256));
var textEncoder;
var textDecoder;
var $Ci = class _$Ci {
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  static alloc(byteLength) {
    if (hasBuffer) {
      return new _$Ci(Buffer.allocUnsafe(byteLength));
    } else {
      return new _$Ci(new Uint8Array(byteLength));
    }
  }
  /**
   * 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 _$Ci(actual);
  }
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  static fromString(source, options2) {
    const dontUseNodeBuffer = options2?.dontUseNodeBuffer || false;
    if (!dontUseNodeBuffer && hasBuffer) {
      return new _$Ci(Buffer.from(source));
    } else {
      if (!textEncoder) {
        textEncoder = new TextEncoder();
      }
      return new _$Ci(textEncoder.encode(source));
    }
  }
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  static fromByteArray(source) {
    const result = _$Ci.alloc(source.length);
    for (let i = 0, len = source.length; i < len; i++) {
      result.buffer[i] = source[i];
    }
    return result;
  }
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  static concat(buffers, totalLength) {
    if (typeof totalLength === "undefined") {
      totalLength = 0;
      for (let i = 0, len = buffers.length; i < len; i++) {
        totalLength += buffers[i].byteLength;
      }
    }
    const ret = _$Ci.alloc(totalLength);
    let offset = 0;
    for (let i = 0, len = buffers.length; i < len; i++) {
      const element = buffers[i];
      ret.set(element, offset);
      offset += element.byteLength;
    }
    return ret;
  }
  constructor(buffer) {
    this.buffer = buffer;
    this.byteLength = this.buffer.byteLength;
  }
  /**
   * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
   * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
   */
  clone() {
    const result = _$Ci.alloc(this.byteLength);
    result.set(this);
    return result;
  }
  toString() {
    if (hasBuffer) {
      return this.buffer.toString();
    } else {
      if (!textDecoder) {
        textDecoder = new TextDecoder();
      }
      return textDecoder.decode(this.buffer);
    }
  }
  slice(start, end) {
    return new _$Ci(this.buffer.subarray(start, end));
  }
  set(array, offset) {
    if (array instanceof _$Ci) {
      this.buffer.set(array.buffer, offset);
    } else if (array instanceof Uint8Array) {
      this.buffer.set(array, offset);
    } else if (array instanceof ArrayBuffer) {
      this.buffer.set(new Uint8Array(array), offset);
    } else if (ArrayBuffer.isView(array)) {
      this.buffer.set(new Uint8Array(array.buffer, array.byteOffset, array.byteLength), offset);
    } else {
      throw new Error(`Unknown argument 'array'`);
    }
  }
  readUInt32BE(offset) {
    return $Gi(this.buffer, offset);
  }
  writeUInt32BE(value, offset) {
    $Hi(this.buffer, value, offset);
  }
  readUInt32LE(offset) {
    return $Ii(this.buffer, offset);
  }
  writeUInt32LE(value, offset) {
    $Ji(this.buffer, value, offset);
  }
  readUInt8(offset) {
    return $Ki(this.buffer, offset);
  }
  writeUInt8(value, offset) {
    $Li(this.buffer, value, offset);
  }
  indexOf(subarray, offset = 0) {
    return $Di(this.buffer, subarray instanceof _$Ci ? subarray.buffer : subarray, offset);
  }
};
function $Di(haystack, needle, offset = 0) {
  const needleLen = needle.byteLength;
  const haystackLen = haystack.byteLength;
  if (needleLen === 0) {
    return 0;
  }
  if (needleLen === 1) {
    return haystack.indexOf(needle[0]);
  }
  if (needleLen > haystackLen - offset) {
    return -1;
  }
  const table = indexOfTable.value;
  table.fill(needle.length);
  for (let i2 = 0; i2 < needle.length; i2++) {
    table[needle[i2]] = needle.length - i2 - 1;
  }
  let i = offset + needle.length - 1;
  let j = i;
  let result = -1;
  while (i < haystackLen) {
    if (haystack[i] === needle[j]) {
      if (j === 0) {
        result = i;
        break;
      }
      i--;
      j--;
    } else {
      i += Math.max(needle.length - j, table[haystack[i]]);
      j = needle.length - 1;
    }
  }
  return result;
}
function $Ei(source, offset) {
  return source[offset + 0] << 0 >>> 0 | source[offset + 1] << 8 >>> 0;
}
function $Fi(destination, value, offset) {
  destination[offset + 0] = value & 255;
  value = value >>> 8;
  destination[offset + 1] = value & 255;
}
function $Gi(source, offset) {
  return source[offset] * 2 ** 24 + source[offset + 1] * 2 ** 16 + source[offset + 2] * 2 ** 8 + source[offset + 3];
}
function $Hi(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 $Ii(source, offset) {
  return source[offset + 0] << 0 >>> 0 | source[offset + 1] << 8 >>> 0 | source[offset + 2] << 16 >>> 0 | source[offset + 3] << 24 >>> 0;
}
function $Ji(destination, value, offset) {
  destination[offset + 0] = value & 255;
  value = value >>> 8;
  destination[offset + 1] = value & 255;
  value = value >>> 8;
  destination[offset + 2] = value & 255;
  value = value >>> 8;
  destination[offset + 3] = value & 255;
}
function $Ki(source, offset) {
  return source[offset];
}
function $Li(destination, value, offset) {
  destination[offset] = value;
}
function $Oi(stream) {
  return $ti(stream, (chunks) => $Ci.concat(chunks));
}
function $Ri(stream) {
  return $zi(stream, { data: (data) => typeof data === "string" ? $Ci.fromString(data) : $Ci.wrap(data) }, (chunks) => $Ci.concat(chunks));
}
function $Vi(encoded) {
  let building = 0;
  let remainder = 0;
  let bufi = 0;
  const buffer = new Uint8Array(Math.floor(encoded.length / 4 * 3));
  const append = (value) => {
    switch (remainder) {
      case 3:
        buffer[bufi++] = building | value;
        remainder = 0;
        break;
      case 2:
        buffer[bufi++] = building | value >>> 2;
        building = value << 6;
        remainder = 3;
        break;
      case 1:
        buffer[bufi++] = building | value >>> 4;
        building = value << 4;
        remainder = 2;
        break;
      default:
        building = value << 2;
        remainder = 1;
    }
  };
  for (let i = 0; i < encoded.length; i++) {
    const code = encoded.charCodeAt(i);
    if (code >= 65 && code <= 90) {
      append(code - 65);
    } else if (code >= 97 && code <= 122) {
      append(code - 97 + 26);
    } else if (code >= 48 && code <= 57) {
      append(code - 48 + 52);
    } else if (code === 43 || code === 45) {
      append(62);
    } else if (code === 47 || code === 95) {
      append(63);
    } else if (code === 61) {
      break;
    } else {
      throw new SyntaxError(`Unexpected base64 character ${encoded[i]}`);
    }
  }
  const unpadded = bufi;
  while (remainder > 0) {
    append(0);
  }
  return $Ci.wrap(buffer).slice(0, unpadded);
}
var base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64UrlSafeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
function $Wi({ buffer }, padded = true, urlSafe = false) {
  const dictionary = urlSafe ? base64UrlSafeAlphabet : base64Alphabet;
  let output = "";
  const remainder = buffer.byteLength % 3;
  let i = 0;
  for (; i < buffer.byteLength - remainder; i += 3) {
    const a = buffer[i + 0];
    const b = buffer[i + 1];
    const c = buffer[i + 2];
    output += dictionary[a >>> 2];
    output += dictionary[(a << 4 | b >>> 4) & 63];
    output += dictionary[(b << 2 | c >>> 6) & 63];
    output += dictionary[c & 63];
  }
  if (remainder === 1) {
    const a = buffer[i + 0];
    output += dictionary[a >>> 2];
    output += dictionary[a << 4 & 63];
    if (padded) {
      output += "==";
    }
  } else if (remainder === 2) {
    const a = buffer[i + 0];
    const b = buffer[i + 1];
    output += dictionary[a >>> 2];
    output += dictionary[(a << 4 | b >>> 4) & 63];
    output += dictionary[b << 2 & 63];
    if (padded) {
      output += "=";
    }
  }
  return output;
}

// out-build/vs/base/common/performance.js
function _definePolyfillMarks(timeOrigin) {
  const _data = [];
  if (typeof timeOrigin === "number") {
    _data.push("code/timeOrigin", timeOrigin);
  }
  function mark(name, markOptions) {
    _data.push(name, markOptions?.startTime ?? Date.now());
  }
  function getMarks() {
    const result = [];
    for (let i = 0; i < _data.length; i += 2) {
      result.push({
        name: _data[i],
        startTime: _data[i + 1]
      });
    }
    return result;
  }
  return { mark, getMarks };
}
function _define() {
  if (typeof performance === "object" && typeof performance.mark === "function" && !performance.nodeTiming) {
    if (typeof performance.timeOrigin !== "number" && !performance.timing) {
      return _definePolyfillMarks();
    } else {
      return {
        mark(name, markOptions) {
          performance.mark(name, markOptions);
        },
        getMarks() {
          let timeOrigin = performance.timeOrigin;
          if (typeof timeOrigin !== "number") {
            timeOrigin = performance.timing.navigationStart || performance.timing.redirectStart || performance.timing.fetchStart;
          }
          const result = [{ name: "code/timeOrigin", startTime: Math.round(timeOrigin) }];
          for (const entry of performance.getEntriesByType("mark")) {
            result.push({
              name: entry.name,
              startTime: Math.round(timeOrigin + entry.startTime)
            });
          }
          return result;
        }
      };
    }
  } else if (typeof process === "object") {
    const timeOrigin = performance?.timeOrigin;
    return _definePolyfillMarks(timeOrigin);
  } else {
    console.trace("perf-util loaded in UNKNOWN environment");
    return _definePolyfillMarks();
  }
}
function _factory(sharedObj) {
  if (!sharedObj.MonacoPerformanceMarks) {
    sharedObj.MonacoPerformanceMarks = _define();
  }
  return sharedObj.MonacoPerformanceMarks;
}
var perf = _factory(globalThis);
var $S = perf.mark;
var $T = perf.getMarks;

// out-build/vs/base/node/extpath.js
import * as fs2 from "fs";

// out-build/vs/base/node/pfs.js
var pfs_exports = {};
__export(pfs_exports, {
  Promises: () => Promises2,
  RimRafMode: () => RimRafMode,
  SymlinkSupport: () => SymlinkSupport,
  configureFlushOnWrite: () => configureFlushOnWrite,
  readdirSync: () => readdirSync2,
  rimrafSync: () => rimrafSync,
  whenDeleted: () => whenDeleted,
  writeFileSync: () => writeFileSync2
});
import * as fs from "fs";
import { tmpdir } from "os";
import { promisify } from "util";

// out-build/vs/base/common/normalization.js
var nfcCache = new $Hc(1e4);
function $Qs(str) {
  return normalize(str, "NFC", nfcCache);
}
var nfdCache = new $Hc(1e4);
function $Rs(str) {
  return normalize(str, "NFD", nfdCache);
}
var nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
function normalize(str, form, normalizedCache) {
  if (!str) {
    return str;
  }
  const cached = normalizedCache.get(str);
  if (cached) {
    return cached;
  }
  let res;
  if (nonAsciiCharactersPattern.test(str)) {
    res = str.normalize(form);
  } else {
    res = str;
  }
  normalizedCache.set(str, res);
  return res;
}

// out-build/vs/base/node/pfs.js
var RimRafMode;
(function(RimRafMode2) {
  RimRafMode2[RimRafMode2["UNLINK"] = 0] = "UNLINK";
  RimRafMode2[RimRafMode2["MOVE"] = 1] = "MOVE";
})(RimRafMode || (RimRafMode = {}));
async function rimraf(path, mode = RimRafMode.UNLINK, moveToPath) {
  if ($4g(path)) {
    throw new Error("rimraf - will refuse to recursively delete root");
  }
  if (mode === RimRafMode.UNLINK) {
    return rimrafUnlink(path);
  }
  return rimrafMove(path, moveToPath);
}
async function rimrafMove(path, moveToPath = $9g(tmpdir())) {
  try {
    try {
      await fs.promises.rename(path, moveToPath);
    } catch (error) {
      if (error.code === "ENOENT") {
        return;
      }
      return rimrafUnlink(path);
    }
    rimrafUnlink(moveToPath).catch((error) => {
    });
  } catch (error) {
    if (error.code !== "ENOENT") {
      throw error;
    }
  }
}
async function rimrafUnlink(path) {
  return fs.promises.rm(path, { recursive: true, force: true, maxRetries: 3 });
}
function rimrafSync(path) {
  if ($4g(path)) {
    throw new Error("rimraf - will refuse to recursively delete root");
  }
  fs.rmSync(path, { recursive: true, force: true, maxRetries: 3 });
}
async function readdir(path, options2) {
  return handleDirectoryChildren(await (options2 ? safeReaddirWithFileTypes(path) : fs.promises.readdir(path)));
}
async function safeReaddirWithFileTypes(path) {
  try {
    return await fs.promises.readdir(path, { withFileTypes: true });
  } catch (error) {
    console.warn("[node.js fs] readdir with filetypes failed with error: ", error);
  }
  const result = [];
  const children = await readdir(path);
  for (const child of children) {
    let isFile = false;
    let isDirectory = false;
    let isSymbolicLink = false;
    try {
      const lstat2 = await fs.promises.lstat($nc(path, child));
      isFile = lstat2.isFile();
      isDirectory = lstat2.isDirectory();
      isSymbolicLink = lstat2.isSymbolicLink();
    } catch (error) {
      console.warn("[node.js fs] unexpected error from lstat after readdir: ", error);
    }
    result.push({
      name: child,
      isFile: () => isFile,
      isDirectory: () => isDirectory,
      isSymbolicLink: () => isSymbolicLink
    });
  }
  return result;
}
function readdirSync2(path) {
  return handleDirectoryChildren(fs.readdirSync(path));
}
function handleDirectoryChildren(children) {
  return children.map((child) => {
    if (typeof child === "string") {
      return $m ? $Qs(child) : child;
    }
    child.name = $m ? $Qs(child.name) : child.name;
    return child;
  });
}
async function readDirsInDir(dirPath) {
  const children = await readdir(dirPath);
  const directories = [];
  for (const child of children) {
    if (await SymlinkSupport.existsDirectory($nc(dirPath, child))) {
      directories.push(child);
    }
  }
  return directories;
}
function whenDeleted(path, intervalMs = 1e3) {
  return new Promise((resolve) => {
    let running = false;
    const interval = setInterval(() => {
      if (!running) {
        running = true;
        fs.access(path, (err) => {
          running = false;
          if (err) {
            clearInterval(interval);
            resolve(void 0);
          }
        });
      }
    }, intervalMs);
  });
}
var SymlinkSupport;
(function(SymlinkSupport2) {
  async function stat2(path) {
    let lstats;
    try {
      lstats = await fs.promises.lstat(path);
      if (!lstats.isSymbolicLink()) {
        return { stat: lstats };
      }
    } catch (error) {
    }
    try {
      const stats = await fs.promises.stat(path);
      return { stat: stats, symbolicLink: lstats?.isSymbolicLink() ? { dangling: false } : void 0 };
    } catch (error) {
      if (error.code === "ENOENT" && lstats) {
        return { stat: lstats, symbolicLink: { dangling: true } };
      }
      if ($l && error.code === "EACCES") {
        try {
          const stats = await fs.promises.stat(await fs.promises.readlink(path));
          return { stat: stats, symbolicLink: { dangling: false } };
        } catch (error2) {
          if (error2.code === "ENOENT" && lstats) {
            return { stat: lstats, symbolicLink: { dangling: true } };
          }
          throw error2;
        }
      }
      throw error;
    }
  }
  SymlinkSupport2.stat = stat2;
  async function existsFile(path) {
    try {
      const { stat: stat3, symbolicLink } = await SymlinkSupport2.stat(path);
      return stat3.isFile() && symbolicLink?.dangling !== true;
    } catch (error) {
    }
    return false;
  }
  SymlinkSupport2.existsFile = existsFile;
  async function existsDirectory(path) {
    try {
      const { stat: stat3, symbolicLink } = await SymlinkSupport2.stat(path);
      return stat3.isDirectory() && symbolicLink?.dangling !== true;
    } catch (error) {
    }
    return false;
  }
  SymlinkSupport2.existsDirectory = existsDirectory;
})(SymlinkSupport || (SymlinkSupport = {}));
var writeQueues = new $5h();
function writeFile2(path, data, options2) {
  return writeQueues.queueFor(URI.file(path), () => {
    const ensuredOptions = ensureWriteOptions(options2);
    return new Promise((resolve, reject) => doWriteFileAndFlush(path, data, ensuredOptions, (error) => error ? reject(error) : resolve()));
  }, $mh);
}
var canFlush = true;
function configureFlushOnWrite(enabled) {
  canFlush = enabled;
}
function doWriteFileAndFlush(path, data, options2, callback) {
  if (!canFlush) {
    return fs.writeFile(path, data, { mode: options2.mode, flag: options2.flag }, callback);
  }
  fs.open(path, options2.flag, options2.mode, (openError, fd) => {
    if (openError) {
      return callback(openError);
    }
    fs.writeFile(fd, data, (writeError) => {
      if (writeError) {
        return fs.close(fd, () => callback(writeError));
      }
      fs.fdatasync(fd, (syncError) => {
        if (syncError) {
          console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ", syncError);
          configureFlushOnWrite(false);
        }
        return fs.close(fd, (closeError) => callback(closeError));
      });
    });
  });
}
function writeFileSync2(path, data, options2) {
  const ensuredOptions = ensureWriteOptions(options2);
  if (!canFlush) {
    return fs.writeFileSync(path, data, { mode: ensuredOptions.mode, flag: ensuredOptions.flag });
  }
  const fd = fs.openSync(path, ensuredOptions.flag, ensuredOptions.mode);
  try {
    fs.writeFileSync(fd, data);
    try {
      fs.fdatasyncSync(fd);
    } catch (syncError) {
      console.warn("[node.js fs] fdatasyncSync is now disabled for this session because it failed: ", syncError);
      configureFlushOnWrite(false);
    }
  } finally {
    fs.closeSync(fd);
  }
}
function ensureWriteOptions(options2) {
  if (!options2) {
    return { mode: 438, flag: "w" };
  }
  return {
    mode: typeof options2.mode === "number" ? options2.mode : 438,
    flag: typeof options2.flag === "string" ? options2.flag : "w"
  };
}
async function rename(source, target, windowsRetryTimeout = 6e4) {
  if (source === target) {
    return;
  }
  try {
    if ($l && typeof windowsRetryTimeout === "number") {
      await renameWithRetry(source, target, Date.now(), windowsRetryTimeout);
    } else {
      await fs.promises.rename(source, target);
    }
  } catch (error) {
    if (source.toLowerCase() !== target.toLowerCase() && error.code === "EXDEV" || source.endsWith(".")) {
      await copy(source, target, {
        preserveSymlinks: false
        /* copying to another device */
      });
      await rimraf(source, RimRafMode.MOVE);
    } else {
      throw error;
    }
  }
}
async function renameWithRetry(source, target, startTime, retryTimeout, attempt = 0) {
  try {
    return await fs.promises.rename(source, target);
  } catch (error) {
    if (error.code !== "EACCES" && error.code !== "EPERM" && error.code !== "EBUSY") {
      throw error;
    }
    if (Date.now() - startTime >= retryTimeout) {
      console.error(`[node.js fs] rename failed after ${attempt} retries with error: ${error}`);
      throw error;
    }
    if (attempt === 0) {
      let abortRetry = false;
      try {
        const { stat: stat2 } = await SymlinkSupport.stat(target);
        if (!stat2.isFile()) {
          abortRetry = true;
        }
      } catch (error2) {
      }
      if (abortRetry) {
        throw error;
      }
    }
    await $Wh(Math.min(100, attempt * 10));
    return renameWithRetry(source, target, startTime, retryTimeout, attempt + 1);
  }
}
async function copy(source, target, options2) {
  return doCopy(source, target, { root: { source, target }, options: options2, handledSourcePaths: /* @__PURE__ */ new Set() });
}
var COPY_MODE_MASK = 511;
async function doCopy(source, target, payload) {
  if (payload.handledSourcePaths.has(source)) {
    return;
  } else {
    payload.handledSourcePaths.add(source);
  }
  const { stat: stat2, symbolicLink } = await SymlinkSupport.stat(source);
  if (symbolicLink) {
    if (payload.options.preserveSymlinks) {
      try {
        return await doCopySymlink(source, target, payload);
      } catch (error) {
      }
    }
    if (symbolicLink.dangling) {
      return;
    }
  }
  if (stat2.isDirectory()) {
    return doCopyDirectory(source, target, stat2.mode & COPY_MODE_MASK, payload);
  } else {
    return doCopyFile(source, target, stat2.mode & COPY_MODE_MASK);
  }
}
async function doCopyDirectory(source, target, mode, payload) {
  await fs.promises.mkdir(target, { recursive: true, mode });
  const files = await readdir(source);
  for (const file of files) {
    await doCopy($nc(source, file), $nc(target, file), payload);
  }
}
async function doCopyFile(source, target, mode) {
  await fs.promises.copyFile(source, target);
  await fs.promises.chmod(target, mode);
}
async function doCopySymlink(source, target, payload) {
  let linkTarget = await fs.promises.readlink(source);
  if ($Zg(linkTarget, payload.root.source, !$n)) {
    linkTarget = $nc(payload.root.target, linkTarget.substr(payload.root.source.length + 1));
  }
  await fs.promises.symlink(linkTarget, target);
}
var Promises2 = new class {
  //#region Implemented by node.js
  get read() {
    return (fd, buffer, offset, length, position) => {
      return new Promise((resolve, reject) => {
        fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer2) => {
          if (err) {
            return reject(err);
          }
          return resolve({ bytesRead, buffer: buffer2 });
        });
      });
    };
  }
  get write() {
    return (fd, buffer, offset, length, position) => {
      return new Promise((resolve, reject) => {
        fs.write(fd, buffer, offset, length, position, (err, bytesWritten, buffer2) => {
          if (err) {
            return reject(err);
          }
          return resolve({ bytesWritten, buffer: buffer2 });
        });
      });
    };
  }
  get fdatasync() {
    return promisify(fs.fdatasync);
  }
  // not exposed as API in 20.x yet
  get open() {
    return promisify(fs.open);
  }
  // changed to return `FileHandle` in promise API
  get close() {
    return promisify(fs.close);
  }
  // not exposed as API due to the `FileHandle` return type of `open`
  get realpath() {
    return promisify(fs.realpath);
  }
  // `fs.promises.realpath` will use `fs.realpath.native` which we do not want
  get ftruncate() {
    return promisify(fs.ftruncate);
  }
  // not exposed as API in 20.x yet
  //#endregion
  //#region Implemented by us
  async exists(path) {
    try {
      await fs.promises.access(path);
      return true;
    } catch {
      return false;
    }
  }
  get readdir() {
    return readdir;
  }
  get readDirsInDir() {
    return readDirsInDir;
  }
  get writeFile() {
    return writeFile2;
  }
  get rm() {
    return rimraf;
  }
  get rename() {
    return rename;
  }
  get copy() {
    return copy;
  }
}();

// out-build/vs/base/node/extpath.js
async function $4s(path, token) {
  if ($n) {
    return path;
  }
  const dir = $qc(path);
  if (path === dir) {
    return path;
  }
  const name = ($rc(path) || path).toLowerCase();
  try {
    if (token?.isCancellationRequested) {
      return null;
    }
    const entries = await Promises2.readdir(dir);
    const found = entries.filter((e) => e.toLowerCase() === name);
    if (found.length === 1) {
      const prefix = await $4s(dir, token);
      if (prefix) {
        return $nc(prefix, found[0]);
      }
    } else if (found.length > 1) {
      const ix = found.indexOf(name);
      if (ix >= 0) {
        const prefix = await $4s(dir, token);
        if (prefix) {
          return $nc(prefix, found[ix]);
        }
      }
    }
  } catch (error) {
  }
  return null;
}
async function $5s(path) {
  try {
    return await Promises2.realpath(path);
  } catch (error) {
    const normalizedPath = normalizePath(path);
    await fs2.promises.access(normalizedPath, fs2.constants.R_OK);
    return normalizedPath;
  }
}
function $6s(path) {
  try {
    return fs2.realpathSync(path);
  } catch (error) {
    const normalizedPath = normalizePath(path);
    fs2.accessSync(normalizedPath, fs2.constants.R_OK);
    return normalizedPath;
  }
}
function normalizePath(path) {
  return $Gf($lc(path), sep);
}

// out-build/vs/base/common/decorators.js
function createDecorator(mapFn) {
  return (_target, key, descriptor) => {
    let fnKey = null;
    let fn = null;
    if (typeof descriptor.value === "function") {
      fnKey = "value";
      fn = descriptor.value;
    } else if (typeof descriptor.get === "function") {
      fnKey = "get";
      fn = descriptor.get;
    }
    if (!fn || typeof key === "symbol") {
      throw new Error("not supported");
    }
    descriptor[fnKey] = mapFn(fn, key);
  };
}
function $0t(_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(...args2) {
    if (!this.hasOwnProperty(memoizeKey)) {
      Object.defineProperty(this, memoizeKey, {
        configurable: false,
        enumerable: false,
        writable: false,
        value: fn.apply(this, args2)
      });
    }
    return this[memoizeKey];
  };
}
function $$t(delay, reducer, initialValueProvider) {
  return createDecorator((fn, key) => {
    const timerKey = `$debounce$${key}`;
    const resultKey = `$debounce$result$${key}`;
    return function(...args2) {
      if (!this[resultKey]) {
        this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
      }
      clearTimeout(this[timerKey]);
      if (reducer) {
        this[resultKey] = reducer(this[resultKey], ...args2);
        args2 = [this[resultKey]];
      }
      this[timerKey] = setTimeout(() => {
        fn.apply(this, args2);
        this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
      }, delay);
    };
  });
}
function $_t(delay, reducer, initialValueProvider) {
  return createDecorator((fn, key) => {
    const timerKey = `$throttle$timer$${key}`;
    const resultKey = `$throttle$result$${key}`;
    const lastRunKey = `$throttle$lastRun$${key}`;
    const pendingKey = `$throttle$pending$${key}`;
    return function(...args2) {
      if (!this[resultKey]) {
        this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
      }
      if (this[lastRunKey] === null || this[lastRunKey] === void 0) {
        this[lastRunKey] = -Number.MAX_VALUE;
      }
      if (reducer) {
        this[resultKey] = reducer(this[resultKey], ...args2);
      }
      if (this[pendingKey]) {
        return;
      }
      const nextTime = this[lastRunKey] + delay;
      if (nextTime <= Date.now()) {
        this[lastRunKey] = Date.now();
        fn.apply(this, [this[resultKey]]);
        this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
      } else {
        this[pendingKey] = true;
        this[timerKey] = setTimeout(() => {
          this[pendingKey] = false;
          this[lastRunKey] = Date.now();
          fn.apply(this, [this[resultKey]]);
          this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
        }, nextTime - Date.now());
      }
    };
  });
}

// out-build/vs/base/common/marshalling.js
function $au(obj) {
  return JSON.stringify(obj, replacer);
}
function $bu(text) {
  let data = JSON.parse(text);
  data = $cu(data);
  return data;
}
function replacer(key, value) {
  if (value instanceof RegExp) {
    return {
      $mid: 2,
      source: value.source,
      flags: value.flags
    };
  }
  return value;
}
function $cu(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 17:
        return new Date(obj.source);
    }
    if (obj instanceof $Ci || obj instanceof Uint8Array) {
      return obj;
    }
    if (Array.isArray(obj)) {
      for (let i = 0; i < obj.length; ++i) {
        obj[i] = $cu(obj[i], depth + 1);
      }
    } else {
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          obj[key] = $cu(obj[key], depth + 1);
        }
      }
    }
  }
  return obj;
}

// out-build/vs/base/parts/ipc/common/ipc.js
var RequestType;
(function(RequestType2) {
  RequestType2[RequestType2["Promise"] = 100] = "Promise";
  RequestType2[RequestType2["PromiseCancel"] = 101] = "PromiseCancel";
  RequestType2[RequestType2["EventListen"] = 102] = "EventListen";
  RequestType2[RequestType2["EventDispose"] = 103] = "EventDispose";
})(RequestType || (RequestType = {}));
function requestTypeToStr(type) {
  switch (type) {
    case 100:
      return "req";
    case 101:
      return "cancel";
    case 102:
      return "subscribe";
    case 103:
      return "unsubscribe";
  }
}
var ResponseType;
(function(ResponseType2) {
  ResponseType2[ResponseType2["Initialize"] = 200] = "Initialize";
  ResponseType2[ResponseType2["PromiseSuccess"] = 201] = "PromiseSuccess";
  ResponseType2[ResponseType2["PromiseError"] = 202] = "PromiseError";
  ResponseType2[ResponseType2["PromiseErrorObj"] = 203] = "PromiseErrorObj";
  ResponseType2[ResponseType2["EventFire"] = 204] = "EventFire";
})(ResponseType || (ResponseType = {}));
function responseTypeToStr(type) {
  switch (type) {
    case 200:
      return `init`;
    case 201:
      return `reply:`;
    case 202:
    case 203:
      return `replyErr:`;
    case 204:
      return `event:`;
  }
}
var State;
(function(State4) {
  State4[State4["Uninitialized"] = 0] = "Uninitialized";
  State4[State4["Idle"] = 1] = "Idle";
})(State || (State = {}));
function readIntVQL(reader) {
  let value = 0;
  for (let n = 0; ; n += 7) {
    const next = reader.read(1);
    value |= (next.buffer[0] & 127) << n;
    if (!(next.buffer[0] & 128)) {
      return value;
    }
  }
}
var vqlZero = createOneByteBuffer(0);
function writeInt32VQL(writer, value) {
  if (value === 0) {
    writer.write(vqlZero);
    return;
  }
  let len = 0;
  for (let v2 = value; v2 !== 0; v2 = v2 >>> 7) {
    len++;
  }
  const scratch = $Ci.alloc(len);
  for (let i = 0; value !== 0; i++) {
    scratch.buffer[i] = value & 127;
    value = value >>> 7;
    if (value > 0) {
      scratch.buffer[i] |= 128;
    }
  }
  writer.write(scratch);
}
var $du = class {
  constructor(b) {
    this.b = b;
    this.a = 0;
  }
  read(bytes) {
    const result = this.b.slice(this.a, this.a + bytes);
    this.a += result.byteLength;
    return result;
  }
};
var $eu = class {
  constructor() {
    this.a = [];
  }
  get buffer() {
    return $Ci.concat(this.a);
  }
  write(buffer) {
    this.a.push(buffer);
  }
};
var DataType;
(function(DataType2) {
  DataType2[DataType2["Undefined"] = 0] = "Undefined";
  DataType2[DataType2["String"] = 1] = "String";
  DataType2[DataType2["Buffer"] = 2] = "Buffer";
  DataType2[DataType2["VSBuffer"] = 3] = "VSBuffer";
  DataType2[DataType2["Array"] = 4] = "Array";
  DataType2[DataType2["Object"] = 5] = "Object";
  DataType2[DataType2["Int"] = 6] = "Int";
})(DataType || (DataType = {}));
function createOneByteBuffer(value) {
  const result = $Ci.alloc(1);
  result.writeUInt8(value, 0);
  return result;
}
var BufferPresets = {
  Undefined: createOneByteBuffer(DataType.Undefined),
  String: createOneByteBuffer(DataType.String),
  Buffer: createOneByteBuffer(DataType.Buffer),
  VSBuffer: createOneByteBuffer(DataType.VSBuffer),
  Array: createOneByteBuffer(DataType.Array),
  Object: createOneByteBuffer(DataType.Object),
  Uint: createOneByteBuffer(DataType.Int)
};
var hasBuffer2 = typeof Buffer !== "undefined";
function $fu(writer, data) {
  if (typeof data === "undefined") {
    writer.write(BufferPresets.Undefined);
  } else if (typeof data === "string") {
    const buffer = $Ci.fromString(data);
    writer.write(BufferPresets.String);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  } else if (hasBuffer2 && Buffer.isBuffer(data)) {
    const buffer = $Ci.wrap(data);
    writer.write(BufferPresets.Buffer);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  } else if (data instanceof $Ci) {
    writer.write(BufferPresets.VSBuffer);
    writeInt32VQL(writer, data.byteLength);
    writer.write(data);
  } else if (Array.isArray(data)) {
    writer.write(BufferPresets.Array);
    writeInt32VQL(writer, data.length);
    for (const el of data) {
      $fu(writer, el);
    }
  } else if (typeof data === "number" && (data | 0) === data) {
    writer.write(BufferPresets.Uint);
    writeInt32VQL(writer, data);
  } else {
    const buffer = $Ci.fromString(JSON.stringify(data));
    writer.write(BufferPresets.Object);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  }
}
function $gu(reader) {
  const type = reader.read(1).readUInt8(0);
  switch (type) {
    case DataType.Undefined:
      return void 0;
    case DataType.String:
      return reader.read(readIntVQL(reader)).toString();
    case DataType.Buffer:
      return reader.read(readIntVQL(reader)).buffer;
    case DataType.VSBuffer:
      return reader.read(readIntVQL(reader));
    case DataType.Array: {
      const length = readIntVQL(reader);
      const result = [];
      for (let i = 0; i < length; i++) {
        result.push($gu(reader));
      }
      return result;
    }
    case DataType.Object:
      return JSON.parse(reader.read(readIntVQL(reader)).toString());
    case DataType.Int:
      return readIntVQL(reader);
  }
}
var RequestInitiator;
(function(RequestInitiator3) {
  RequestInitiator3[RequestInitiator3["LocalSide"] = 0] = "LocalSide";
  RequestInitiator3[RequestInitiator3["OtherSide"] = 1] = "OtherSide";
})(RequestInitiator || (RequestInitiator = {}));
var $iu = class {
  constructor(l, logger = null) {
    this.l = l;
    this.a = false;
    this.b = State.Uninitialized;
    this.d = /* @__PURE__ */ new Set();
    this.f = /* @__PURE__ */ new Map();
    this.g = 0;
    this.k = new $ze();
    this.onDidInitialize = this.k.event;
    this.h = this.l.onMessage((msg) => this.s(msg));
    this.j = logger;
  }
  getChannel(channelName) {
    const that = this;
    return {
      call(command, arg, cancellationToken) {
        if (that.a) {
          return Promise.reject(new $lb());
        }
        return that.m(channelName, command, arg, cancellationToken);
      },
      listen(event, arg) {
        if (that.a) {
          return Event.None;
        }
        return that.o(channelName, event, arg);
      }
    };
  }
  m(channelName, name, arg, cancellationToken = CancellationToken.None) {
    const id2 = this.g++;
    const type = 100;
    const request = { id: id2, type, channelName, name, arg };
    if (cancellationToken.isCancellationRequested) {
      return Promise.reject(new $lb());
    }
    let disposable;
    let disposableWithRequestCancel;
    const result = new Promise((c, e) => {
      if (cancellationToken.isCancellationRequested) {
        return e(new $lb());
      }
      const doRequest = () => {
        const handler = (response) => {
          switch (response.type) {
            case 201:
              this.f.delete(id2);
              c(response.data);
              break;
            case 202: {
              this.f.delete(id2);
              const error = new Error(response.data.message);
              error.stack = Array.isArray(response.data.stack) ? response.data.stack.join("\n") : response.data.stack;
              error.name = response.data.name;
              e(error);
              break;
            }
            case 203:
              this.f.delete(id2);
              e(response.data);
              break;
          }
        };
        this.f.set(id2, handler);
        this.p(request);
      };
      let uninitializedPromise = null;
      if (this.b === State.Idle) {
        doRequest();
      } else {
        uninitializedPromise = $Hh((_) => this.u());
        uninitializedPromise.then(() => {
          uninitializedPromise = null;
          doRequest();
        });
      }
      const cancel = () => {
        if (uninitializedPromise) {
          uninitializedPromise.cancel();
          uninitializedPromise = null;
        } else {
          this.p({
            id: id2,
            type: 101
            /* RequestType.PromiseCancel */
          });
        }
        e(new $lb());
      };
      disposable = cancellationToken.onCancellationRequested(cancel);
      disposableWithRequestCancel = {
        dispose: $Qc(() => {
          cancel();
          disposable.dispose();
        })
      };
      this.d.add(disposableWithRequestCancel);
    });
    return result.finally(() => {
      disposable.dispose();
      this.d.delete(disposableWithRequestCancel);
    });
  }
  o(channelName, name, arg) {
    const id2 = this.g++;
    const type = 102;
    const request = { id: id2, type, channelName, name, arg };
    let uninitializedPromise = null;
    const emitter = new $ze({
      onWillAddFirstListener: () => {
        const doRequest = () => {
          this.d.add(emitter);
          this.p(request);
        };
        if (this.b === State.Idle) {
          doRequest();
        } else {
          uninitializedPromise = $Hh((_) => this.u());
          uninitializedPromise.then(() => {
            uninitializedPromise = null;
            doRequest();
          });
        }
      },
      onDidRemoveLastListener: () => {
        if (uninitializedPromise) {
          uninitializedPromise.cancel();
          uninitializedPromise = null;
        } else {
          this.d.delete(emitter);
          this.p({
            id: id2,
            type: 103
            /* RequestType.EventDispose */
          });
        }
      }
    });
    const handler = (res) => emitter.fire(res.data);
    this.f.set(id2, handler);
    return emitter.event;
  }
  p(request) {
    switch (request.type) {
      case 100:
      case 102: {
        const msgLength = this.q([request.type, request.id, request.channelName, request.name], request.arg);
        this.j?.logOutgoing(msgLength, request.id, 0, `${requestTypeToStr(request.type)}: ${request.channelName}.${request.name}`, request.arg);
        return;
      }
      case 101:
      case 103: {
        const msgLength = this.q([request.type, request.id]);
        this.j?.logOutgoing(msgLength, request.id, 0, requestTypeToStr(request.type));
        return;
      }
    }
  }
  q(header, body = void 0) {
    const writer = new $eu();
    $fu(writer, header);
    $fu(writer, body);
    return this.r(writer.buffer);
  }
  r(message) {
    try {
      this.l.send(message);
      return message.byteLength;
    } catch (err) {
      return 0;
    }
  }
  s(message) {
    const reader = new $du(message);
    const header = $gu(reader);
    const body = $gu(reader);
    const type = header[0];
    switch (type) {
      case 200:
        this.j?.logIncoming(message.byteLength, 0, 0, responseTypeToStr(type));
        return this.t({ type: header[0] });
      case 201:
      case 202:
      case 204:
      case 203:
        this.j?.logIncoming(message.byteLength, header[1], 0, responseTypeToStr(type), body);
        return this.t({ type: header[0], id: header[1], data: body });
    }
  }
  t(response) {
    if (response.type === 200) {
      this.b = State.Idle;
      this.k.fire();
      return;
    }
    const handler = this.f.get(response.id);
    handler?.(response);
  }
  get onDidInitializePromise() {
    return Event.toPromise(this.onDidInitialize);
  }
  u() {
    if (this.b === State.Idle) {
      return Promise.resolve();
    } else {
      return this.onDidInitializePromise;
    }
  }
  dispose() {
    this.a = true;
    if (this.h) {
      this.h.dispose();
      this.h = null;
    }
    $Xc(this.d.values());
    this.d.clear();
  }
};
__decorate([
  $0t
], $iu.prototype, "onDidInitializePromise", null);
function $mu(channel) {
  let didTick = false;
  return {
    call(command, arg, cancellationToken) {
      if (didTick) {
        return channel.call(command, arg, cancellationToken);
      }
      return $Wh(0).then(() => didTick = true).then(() => channel.call(command, arg, cancellationToken));
    },
    listen(event, arg) {
      if (didTick) {
        return channel.listen(event, arg);
      }
      const relay = new $Ie();
      $Wh(0).then(() => didTick = true).then(() => relay.input = channel.listen(event, arg));
      return relay.event;
    }
  };
}
var ProxyChannel;
(function(ProxyChannel2) {
  function fromService(service, disposables, options2) {
    const handler = service;
    const disableMarshalling = options2 && options2.disableMarshalling;
    const mapEventNameToEvent = /* @__PURE__ */ new Map();
    for (const key in handler) {
      if (propertyIsEvent(key)) {
        mapEventNameToEvent.set(key, Event.buffer(handler[key], true, void 0, disposables));
      }
    }
    return new class {
      listen(_, event, arg) {
        const eventImpl = mapEventNameToEvent.get(event);
        if (eventImpl) {
          return eventImpl;
        }
        const target = handler[event];
        if (typeof target === "function") {
          if (propertyIsDynamicEvent(event)) {
            return target.call(handler, arg);
          }
          if (propertyIsEvent(event)) {
            mapEventNameToEvent.set(event, Event.buffer(handler[event], true, void 0, disposables));
            return mapEventNameToEvent.get(event);
          }
        }
        throw new $ub(`Event not found: ${event}`);
      }
      call(_, command, args2) {
        const target = handler[command];
        if (typeof target === "function") {
          if (!disableMarshalling && Array.isArray(args2)) {
            for (let i = 0; i < args2.length; i++) {
              args2[i] = $cu(args2[i]);
            }
          }
          let res = target.apply(handler, args2);
          if (!(res instanceof Promise)) {
            res = Promise.resolve(res);
          }
          return res;
        }
        throw new $ub(`Method not found: ${command}`);
      }
    }();
  }
  ProxyChannel2.fromService = fromService;
  function toService(channel, options2) {
    const disableMarshalling = options2 && options2.disableMarshalling;
    return new Proxy({}, {
      get(_target, propKey) {
        if (typeof propKey === "string") {
          if (options2?.properties?.has(propKey)) {
            return options2.properties.get(propKey);
          }
          if (propertyIsDynamicEvent(propKey)) {
            return function(arg) {
              return channel.listen(propKey, arg);
            };
          }
          if (propertyIsEvent(propKey)) {
            return channel.listen(propKey);
          }
          return async function(...args2) {
            let methodArgs;
            if (options2 && !$Ig(options2.context)) {
              methodArgs = [options2.context, ...args2];
            } else {
              methodArgs = args2;
            }
            const result = await channel.call(propKey, methodArgs);
            if (!disableMarshalling) {
              return $cu(result);
            }
            return result;
          };
        }
        throw new $ub(`Property not found: ${String(propKey)}`);
      }
    });
  }
  ProxyChannel2.toService = toService;
  function propertyIsEvent(name) {
    return name[0] === "o" && name[1] === "n" && $Zf(name.charCodeAt(2));
  }
  function propertyIsDynamicEvent(name) {
    return /^onDynamic/.test(name) && $Zf(name.charCodeAt(9));
  }
})(ProxyChannel || (ProxyChannel = {}));

// out-build/vs/base/parts/ipc/common/ipc.net.js
var SocketDiagnosticsEventType;
(function(SocketDiagnosticsEventType2) {
  SocketDiagnosticsEventType2["Created"] = "created";
  SocketDiagnosticsEventType2["Read"] = "read";
  SocketDiagnosticsEventType2["Write"] = "write";
  SocketDiagnosticsEventType2["Open"] = "open";
  SocketDiagnosticsEventType2["Error"] = "error";
  SocketDiagnosticsEventType2["Close"] = "close";
  SocketDiagnosticsEventType2["BrowserWebSocketBlobReceived"] = "browserWebSocketBlobReceived";
  SocketDiagnosticsEventType2["NodeEndReceived"] = "nodeEndReceived";
  SocketDiagnosticsEventType2["NodeEndSent"] = "nodeEndSent";
  SocketDiagnosticsEventType2["NodeDrainBegin"] = "nodeDrainBegin";
  SocketDiagnosticsEventType2["NodeDrainEnd"] = "nodeDrainEnd";
  SocketDiagnosticsEventType2["zlibInflateError"] = "zlibInflateError";
  SocketDiagnosticsEventType2["zlibInflateData"] = "zlibInflateData";
  SocketDiagnosticsEventType2["zlibInflateInitialWrite"] = "zlibInflateInitialWrite";
  SocketDiagnosticsEventType2["zlibInflateInitialFlushFired"] = "zlibInflateInitialFlushFired";
  SocketDiagnosticsEventType2["zlibInflateWrite"] = "zlibInflateWrite";
  SocketDiagnosticsEventType2["zlibInflateFlushFired"] = "zlibInflateFlushFired";
  SocketDiagnosticsEventType2["zlibDeflateError"] = "zlibDeflateError";
  SocketDiagnosticsEventType2["zlibDeflateData"] = "zlibDeflateData";
  SocketDiagnosticsEventType2["zlibDeflateWrite"] = "zlibDeflateWrite";
  SocketDiagnosticsEventType2["zlibDeflateFlushFired"] = "zlibDeflateFlushFired";
  SocketDiagnosticsEventType2["WebSocketNodeSocketWrite"] = "webSocketNodeSocketWrite";
  SocketDiagnosticsEventType2["WebSocketNodeSocketPeekedHeader"] = "webSocketNodeSocketPeekedHeader";
  SocketDiagnosticsEventType2["WebSocketNodeSocketReadHeader"] = "webSocketNodeSocketReadHeader";
  SocketDiagnosticsEventType2["WebSocketNodeSocketReadData"] = "webSocketNodeSocketReadData";
  SocketDiagnosticsEventType2["WebSocketNodeSocketUnmaskedData"] = "webSocketNodeSocketUnmaskedData";
  SocketDiagnosticsEventType2["WebSocketNodeSocketDrainBegin"] = "webSocketNodeSocketDrainBegin";
  SocketDiagnosticsEventType2["WebSocketNodeSocketDrainEnd"] = "webSocketNodeSocketDrainEnd";
  SocketDiagnosticsEventType2["ProtocolHeaderRead"] = "protocolHeaderRead";
  SocketDiagnosticsEventType2["ProtocolMessageRead"] = "protocolMessageRead";
  SocketDiagnosticsEventType2["ProtocolHeaderWrite"] = "protocolHeaderWrite";
  SocketDiagnosticsEventType2["ProtocolMessageWrite"] = "protocolMessageWrite";
  SocketDiagnosticsEventType2["ProtocolWrite"] = "protocolWrite";
})(SocketDiagnosticsEventType || (SocketDiagnosticsEventType = {}));
var SocketDiagnostics;
(function(SocketDiagnostics2) {
  SocketDiagnostics2.enableDiagnostics = false;
  SocketDiagnostics2.records = [];
  const socketIds = /* @__PURE__ */ new WeakMap();
  let lastUsedSocketId = 0;
  function getSocketId(nativeObject, label) {
    if (!socketIds.has(nativeObject)) {
      const id2 = String(++lastUsedSocketId);
      socketIds.set(nativeObject, id2);
    }
    return socketIds.get(nativeObject);
  }
  function traceSocketEvent(nativeObject, socketDebugLabel, type, data) {
    if (!SocketDiagnostics2.enableDiagnostics) {
      return;
    }
    const id2 = getSocketId(nativeObject, socketDebugLabel);
    if (data instanceof $Ci || data instanceof Uint8Array || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
      const copiedData = $Ci.alloc(data.byteLength);
      copiedData.set(data);
      SocketDiagnostics2.records.push({ timestamp: Date.now(), id: id2, label: socketDebugLabel, type, buff: copiedData });
    } else {
      SocketDiagnostics2.records.push({ timestamp: Date.now(), id: id2, label: socketDebugLabel, type, data });
    }
  }
  SocketDiagnostics2.traceSocketEvent = traceSocketEvent;
})(SocketDiagnostics || (SocketDiagnostics = {}));
var SocketCloseEventType;
(function(SocketCloseEventType2) {
  SocketCloseEventType2[SocketCloseEventType2["NodeSocketCloseEvent"] = 0] = "NodeSocketCloseEvent";
  SocketCloseEventType2[SocketCloseEventType2["WebSocketCloseEvent"] = 1] = "WebSocketCloseEvent";
})(SocketCloseEventType || (SocketCloseEventType = {}));
var emptyBuffer = null;
function getEmptyBuffer() {
  if (!emptyBuffer) {
    emptyBuffer = $Ci.alloc(0);
  }
  return emptyBuffer;
}
var $pu = class {
  get byteLength() {
    return this.b;
  }
  constructor() {
    this.a = [];
    this.b = 0;
  }
  acceptChunk(buff) {
    this.a.push(buff);
    this.b += buff.byteLength;
  }
  read(byteCount) {
    return this.c(byteCount, true);
  }
  peek(byteCount) {
    return this.c(byteCount, false);
  }
  c(byteCount, advance) {
    if (byteCount === 0) {
      return getEmptyBuffer();
    }
    if (byteCount > this.b) {
      throw new Error(`Cannot read so many bytes!`);
    }
    if (this.a[0].byteLength === byteCount) {
      const result2 = this.a[0];
      if (advance) {
        this.a.shift();
        this.b -= byteCount;
      }
      return result2;
    }
    if (this.a[0].byteLength > byteCount) {
      const result2 = this.a[0].slice(0, byteCount);
      if (advance) {
        this.a[0] = this.a[0].slice(byteCount);
        this.b -= byteCount;
      }
      return result2;
    }
    const result = $Ci.alloc(byteCount);
    let resultOffset = 0;
    let chunkIndex = 0;
    while (byteCount > 0) {
      const chunk = this.a[chunkIndex];
      if (chunk.byteLength > byteCount) {
        const chunkPart = chunk.slice(0, byteCount);
        result.set(chunkPart, resultOffset);
        resultOffset += byteCount;
        if (advance) {
          this.a[chunkIndex] = chunk.slice(byteCount);
          this.b -= byteCount;
        }
        byteCount -= byteCount;
      } else {
        result.set(chunk, resultOffset);
        resultOffset += chunk.byteLength;
        if (advance) {
          this.a.shift();
          this.b -= chunk.byteLength;
        } else {
          chunkIndex++;
        }
        byteCount -= chunk.byteLength;
      }
    }
    return result;
  }
};
var ProtocolMessageType;
(function(ProtocolMessageType2) {
  ProtocolMessageType2[ProtocolMessageType2["None"] = 0] = "None";
  ProtocolMessageType2[ProtocolMessageType2["Regular"] = 1] = "Regular";
  ProtocolMessageType2[ProtocolMessageType2["Control"] = 2] = "Control";
  ProtocolMessageType2[ProtocolMessageType2["Ack"] = 3] = "Ack";
  ProtocolMessageType2[ProtocolMessageType2["Disconnect"] = 5] = "Disconnect";
  ProtocolMessageType2[ProtocolMessageType2["ReplayRequest"] = 6] = "ReplayRequest";
  ProtocolMessageType2[ProtocolMessageType2["Pause"] = 7] = "Pause";
  ProtocolMessageType2[ProtocolMessageType2["Resume"] = 8] = "Resume";
  ProtocolMessageType2[ProtocolMessageType2["KeepAlive"] = 9] = "KeepAlive";
})(ProtocolMessageType || (ProtocolMessageType = {}));
function protocolMessageTypeToString(messageType) {
  switch (messageType) {
    case 0:
      return "None";
    case 1:
      return "Regular";
    case 2:
      return "Control";
    case 3:
      return "Ack";
    case 5:
      return "Disconnect";
    case 6:
      return "ReplayRequest";
    case 7:
      return "PauseWriting";
    case 8:
      return "ResumeWriting";
    case 9:
      return "KeepAlive";
  }
}
var ProtocolConstants;
(function(ProtocolConstants2) {
  ProtocolConstants2[ProtocolConstants2["HeaderLength"] = 13] = "HeaderLength";
  ProtocolConstants2[ProtocolConstants2["AcknowledgeTime"] = 2e3] = "AcknowledgeTime";
  ProtocolConstants2[ProtocolConstants2["TimeoutTime"] = 2e4] = "TimeoutTime";
  ProtocolConstants2[ProtocolConstants2["ReconnectionGraceTime"] = 108e5] = "ReconnectionGraceTime";
  ProtocolConstants2[ProtocolConstants2["ReconnectionShortGraceTime"] = 3e5] = "ReconnectionShortGraceTime";
  ProtocolConstants2[ProtocolConstants2["KeepAliveSendTime"] = 5e3] = "KeepAliveSendTime";
})(ProtocolConstants || (ProtocolConstants = {}));
var ProtocolMessage = class {
  constructor(type, id2, ack, data) {
    this.type = type;
    this.id = id2;
    this.ack = ack;
    this.data = data;
    this.writtenTime = 0;
  }
  get size() {
    return this.data.byteLength;
  }
};
var ProtocolReader = class extends $3c {
  constructor(socket) {
    super();
    this.f = this.B(new $ze());
    this.onMessage = this.f.event;
    this.g = {
      readHead: true,
      readLen: 13,
      messageType: 0,
      id: 0,
      ack: 0
    };
    this.a = socket;
    this.b = false;
    this.c = new $pu();
    this.B(this.a.onData((data) => this.acceptChunk(data)));
    this.lastReadTime = Date.now();
  }
  acceptChunk(data) {
    if (!data || data.byteLength === 0) {
      return;
    }
    this.lastReadTime = Date.now();
    this.c.acceptChunk(data);
    while (this.c.byteLength >= this.g.readLen) {
      const buff = this.c.read(this.g.readLen);
      if (this.g.readHead) {
        this.g.readHead = false;
        this.g.readLen = buff.readUInt32BE(9);
        this.g.messageType = buff.readUInt8(0);
        this.g.id = buff.readUInt32BE(1);
        this.g.ack = buff.readUInt32BE(5);
        this.a.traceSocketEvent("protocolHeaderRead", { messageType: protocolMessageTypeToString(this.g.messageType), id: this.g.id, ack: this.g.ack, messageSize: this.g.readLen });
      } else {
        const messageType = this.g.messageType;
        const id2 = this.g.id;
        const ack = this.g.ack;
        this.g.readHead = true;
        this.g.readLen = 13;
        this.g.messageType = 0;
        this.g.id = 0;
        this.g.ack = 0;
        this.a.traceSocketEvent("protocolMessageRead", buff);
        this.f.fire(new ProtocolMessage(messageType, id2, ack, buff));
        if (this.b) {
          break;
        }
      }
    }
  }
  readEntireBuffer() {
    return this.c.read(this.c.byteLength);
  }
  dispose() {
    this.b = true;
    super.dispose();
  }
};
var ProtocolWriter = class {
  constructor(socket) {
    this.k = null;
    this.a = false;
    this.b = false;
    this.c = socket;
    this.d = [];
    this.f = 0;
    this.lastWriteTime = 0;
  }
  dispose() {
    try {
      this.flush();
    } catch (err) {
    }
    this.a = true;
  }
  drain() {
    this.flush();
    return this.c.drain();
  }
  flush() {
    this.m();
  }
  pause() {
    this.b = true;
  }
  resume() {
    this.b = false;
    this.l();
  }
  write(msg) {
    if (this.a) {
      return;
    }
    msg.writtenTime = Date.now();
    this.lastWriteTime = Date.now();
    const header = $Ci.alloc(
      13
      /* ProtocolConstants.HeaderLength */
    );
    header.writeUInt8(msg.type, 0);
    header.writeUInt32BE(msg.id, 1);
    header.writeUInt32BE(msg.ack, 5);
    header.writeUInt32BE(msg.data.byteLength, 9);
    this.c.traceSocketEvent("protocolHeaderWrite", { messageType: protocolMessageTypeToString(msg.type), id: msg.id, ack: msg.ack, messageSize: msg.data.byteLength });
    this.c.traceSocketEvent("protocolMessageWrite", msg.data);
    this.j(header, msg.data);
  }
  g(head, body) {
    const wasEmpty = this.f === 0;
    this.d.push(head, body);
    this.f += head.byteLength + body.byteLength;
    return wasEmpty;
  }
  h() {
    const ret = $Ci.concat(this.d, this.f);
    this.d.length = 0;
    this.f = 0;
    return ret;
  }
  j(header, data) {
    if (this.g(header, data)) {
      this.l();
    }
  }
  l() {
    if (this.k) {
      return;
    }
    this.k = setTimeout(() => {
      this.k = null;
      this.m();
    });
  }
  m() {
    if (this.f === 0) {
      return;
    }
    if (this.b) {
      return;
    }
    const data = this.h();
    this.c.traceSocketEvent("protocolWrite", { byteLength: data.byteLength });
    this.c.write(data);
  }
};
var $su = class {
  constructor() {
    this.b = false;
    this.c = false;
    this.d = [];
    this.a = new $ze({
      onWillAddFirstListener: () => {
        this.b = true;
        queueMicrotask(() => this.f());
      },
      onDidRemoveLastListener: () => {
        this.b = false;
      }
    });
    this.event = this.a.event;
  }
  f() {
    if (this.c) {
      return;
    }
    this.c = true;
    while (this.b && this.d.length > 0) {
      this.a.fire(this.d.shift());
    }
    this.c = false;
  }
  fire(event) {
    if (this.b) {
      if (this.d.length > 0) {
        this.d.push(event);
      } else {
        this.a.fire(event);
      }
    } else {
      this.d.push(event);
    }
  }
  flushBuffer() {
    this.d = [];
  }
};
var QueueElement = class {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
};
var Queue = class {
  constructor() {
    this.a = null;
    this.b = null;
  }
  length() {
    let result = 0;
    let current = this.a;
    while (current) {
      current = current.next;
      result++;
    }
    return result;
  }
  peek() {
    if (!this.a) {
      return null;
    }
    return this.a.data;
  }
  toArray() {
    const result = [];
    let resultLen = 0;
    let it = this.a;
    while (it) {
      result[resultLen++] = it.data;
      it = it.next;
    }
    return result;
  }
  pop() {
    if (!this.a) {
      return;
    }
    if (this.a === this.b) {
      this.a = null;
      this.b = null;
      return;
    }
    this.a = this.a.next;
  }
  push(item) {
    const element = new QueueElement(item);
    if (!this.a) {
      this.a = element;
      this.b = element;
      return;
    }
    this.b.next = element;
    this.b = element;
  }
};
var LoadEstimator = class _LoadEstimator {
  static {
    this.a = 10;
  }
  static {
    this.b = null;
  }
  static getInstance() {
    if (!_LoadEstimator.b) {
      _LoadEstimator.b = new _LoadEstimator();
    }
    return _LoadEstimator.b;
  }
  constructor() {
    this.c = [];
    const now = Date.now();
    for (let i = 0; i < _LoadEstimator.a; i++) {
      this.c[i] = now - 1e3 * i;
    }
    setInterval(() => {
      for (let i = _LoadEstimator.a; i >= 1; i--) {
        this.c[i] = this.c[i - 1];
      }
      this.c[0] = Date.now();
    }, 1e3);
  }
  /**
   * returns an estimative number, from 0 (low load) to 1 (high load)
   */
  d() {
    const now = Date.now();
    const historyLimit = (1 + _LoadEstimator.a) * 1e3;
    let score = 0;
    for (let i = 0; i < _LoadEstimator.a; i++) {
      if (now - this.c[i] <= historyLimit) {
        score++;
      }
    }
    return 1 - score / _LoadEstimator.a;
  }
  hasHighLoad() {
    return this.d() >= 0.5;
  }
};
var $tu = class {
  get unacknowledgedCount() {
    return this.d - this.f;
  }
  constructor(opts) {
    this.v = new $su();
    this.onControlMessage = this.v.event;
    this.w = new $su();
    this.onMessage = this.w.event;
    this.x = new $su();
    this.onDidDispose = this.x.event;
    this.y = new $su();
    this.onSocketClose = this.y.event;
    this.z = new $su();
    this.onSocketTimeout = this.z.event;
    this.t = opts.loadEstimator ?? LoadEstimator.getInstance();
    this.u = opts.sendKeepAlive ?? true;
    this.a = false;
    this.c = new Queue();
    this.d = 0;
    this.f = 0;
    this.g = null;
    this.h = 0;
    this.j = 0;
    this.k = 0;
    this.l = null;
    this.n = 0;
    this.o = Date.now();
    this.s = new $2c();
    this.p = opts.socket;
    this.q = this.s.add(new ProtocolWriter(this.p));
    this.r = this.s.add(new ProtocolReader(this.p));
    this.s.add(this.r.onMessage((msg) => this.A(msg)));
    this.s.add(this.p.onClose((e) => this.y.fire(e)));
    if (opts.initialChunk) {
      this.r.acceptChunk(opts.initialChunk);
    }
    if (this.u) {
      this.m = setInterval(
        () => {
          this.E();
        },
        5e3
        /* ProtocolConstants.KeepAliveSendTime */
      );
    } else {
      this.m = null;
    }
  }
  dispose() {
    if (this.g) {
      clearTimeout(this.g);
      this.g = null;
    }
    if (this.l) {
      clearTimeout(this.l);
      this.l = null;
    }
    if (this.m) {
      clearInterval(this.m);
      this.m = null;
    }
    this.s.dispose();
  }
  drain() {
    return this.q.drain();
  }
  sendDisconnect() {
    if (!this.b) {
      this.b = true;
      const msg = new ProtocolMessage(5, 0, 0, getEmptyBuffer());
      this.q.write(msg);
      this.q.flush();
    }
  }
  sendPause() {
    const msg = new ProtocolMessage(7, 0, 0, getEmptyBuffer());
    this.q.write(msg);
  }
  sendResume() {
    const msg = new ProtocolMessage(8, 0, 0, getEmptyBuffer());
    this.q.write(msg);
  }
  pauseSocketWriting() {
    this.q.pause();
  }
  getSocket() {
    return this.p;
  }
  getMillisSinceLastIncomingData() {
    return Date.now() - this.r.lastReadTime;
  }
  beginAcceptReconnection(socket, initialDataChunk) {
    this.a = true;
    this.s.dispose();
    this.s = new $2c();
    this.v.flushBuffer();
    this.y.flushBuffer();
    this.z.flushBuffer();
    this.p.dispose();
    this.n = 0;
    this.o = Date.now();
    this.p = socket;
    this.q = this.s.add(new ProtocolWriter(this.p));
    this.r = this.s.add(new ProtocolReader(this.p));
    this.s.add(this.r.onMessage((msg) => this.A(msg)));
    this.s.add(this.p.onClose((e) => this.y.fire(e)));
    this.r.acceptChunk(initialDataChunk);
  }
  endAcceptReconnection() {
    this.a = false;
    this.j = this.h;
    const msg = new ProtocolMessage(3, 0, this.j, getEmptyBuffer());
    this.q.write(msg);
    const toSend = this.c.toArray();
    for (let i = 0, len = toSend.length; i < len; i++) {
      this.q.write(toSend[i]);
    }
    this.C();
  }
  acceptDisconnect() {
    this.x.fire();
  }
  A(msg) {
    if (msg.ack > this.f) {
      this.f = msg.ack;
      do {
        const first = this.c.peek();
        if (first && first.id <= msg.ack) {
          this.c.pop();
        } else {
          break;
        }
      } while (true);
    }
    switch (msg.type) {
      case 0: {
        break;
      }
      case 1: {
        if (msg.id > this.h) {
          if (msg.id !== this.h + 1) {
            const now = Date.now();
            if (now - this.n > 1e4) {
              this.n = now;
              this.q.write(new ProtocolMessage(6, 0, 0, getEmptyBuffer()));
            }
          } else {
            this.h = msg.id;
            this.k = Date.now();
            this.B();
            this.w.fire(msg.data);
          }
        }
        break;
      }
      case 2: {
        this.v.fire(msg.data);
        break;
      }
      case 3: {
        break;
      }
      case 5: {
        this.x.fire();
        break;
      }
      case 6: {
        const toSend = this.c.toArray();
        for (let i = 0, len = toSend.length; i < len; i++) {
          this.q.write(toSend[i]);
        }
        this.C();
        break;
      }
      case 7: {
        this.q.pause();
        break;
      }
      case 8: {
        this.q.resume();
        break;
      }
      case 9: {
        break;
      }
    }
  }
  readEntireBuffer() {
    return this.r.readEntireBuffer();
  }
  flush() {
    this.q.flush();
  }
  send(buffer) {
    const myId = ++this.d;
    this.j = this.h;
    const msg = new ProtocolMessage(1, myId, this.j, buffer);
    this.c.push(msg);
    if (!this.a) {
      this.q.write(msg);
      this.C();
    }
  }
  /**
   * Send a message which will not be part of the regular acknowledge flow.
   * Use this for early control messages which are repeated in case of reconnection.
   */
  sendControl(buffer) {
    const msg = new ProtocolMessage(2, 0, 0, buffer);
    this.q.write(msg);
  }
  B() {
    if (this.h <= this.j) {
      return;
    }
    if (this.l) {
      return;
    }
    const timeSinceLastIncomingMsg = Date.now() - this.k;
    if (timeSinceLastIncomingMsg >= 2e3) {
      this.D();
      return;
    }
    this.l = setTimeout(() => {
      this.l = null;
      this.B();
    }, 2e3 - timeSinceLastIncomingMsg + 5);
  }
  C() {
    if (this.d <= this.f) {
      return;
    }
    if (this.g) {
      return;
    }
    if (this.a) {
      return;
    }
    const oldestUnacknowledgedMsg = this.c.peek();
    const timeSinceOldestUnacknowledgedMsg = Date.now() - oldestUnacknowledgedMsg.writtenTime;
    const timeSinceLastReceivedSomeData = Date.now() - this.r.lastReadTime;
    const timeSinceLastTimeout = Date.now() - this.o;
    if (timeSinceOldestUnacknowledgedMsg >= 2e4 && timeSinceLastReceivedSomeData >= 2e4 && timeSinceLastTimeout >= 2e4) {
      if (!this.t.hasHighLoad()) {
        this.o = Date.now();
        this.z.fire({
          unacknowledgedMsgCount: this.c.length(),
          timeSinceOldestUnacknowledgedMsg,
          timeSinceLastReceivedSomeData
        });
        return;
      }
    }
    const minimumTimeUntilTimeout = Math.max(2e4 - timeSinceOldestUnacknowledgedMsg, 2e4 - timeSinceLastReceivedSomeData, 2e4 - timeSinceLastTimeout, 500);
    this.g = setTimeout(() => {
      this.g = null;
      this.C();
    }, minimumTimeUntilTimeout);
  }
  D() {
    if (this.h <= this.j) {
      return;
    }
    this.j = this.h;
    const msg = new ProtocolMessage(3, 0, this.j, getEmptyBuffer());
    this.q.write(msg);
  }
  E() {
    this.j = this.h;
    const msg = new ProtocolMessage(9, 0, this.j, getEmptyBuffer());
    this.q.write(msg);
  }
};

// out-build/vs/base/parts/ipc/node/ipc.net.js
import { createHash } from "crypto";
import { createServer, createConnection } from "net";
import { tmpdir as tmpdir2 } from "os";
import { createDeflateRaw, createInflateRaw } from "zlib";

// out-build/vs/base/common/uuid.js
var $ps = 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 generateUuid() {
    getRandomValues(_data);
    _data[6] = _data[6] & 15 | 64;
    _data[8] = _data[8] & 63 | 128;
    let i = 0;
    let result = "";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += "-";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += "-";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += "-";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += "-";
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    result += _hex[_data[i++]];
    return result;
  };
}();

// out-build/vs/base/parts/ipc/node/ipc.net.js
var socketEndTimeoutMs = 3e4;
var $uu = class {
  traceSocketEvent(type, data) {
    SocketDiagnostics.traceSocketEvent(this.socket, this.debugLabel, type, data);
  }
  constructor(socket, debugLabel = "") {
    this.f = true;
    this.debugLabel = debugLabel;
    this.socket = socket;
    this.traceSocketEvent("created", { type: "NodeSocket" });
    this.a = (err) => {
      this.traceSocketEvent("error", { code: err?.code, message: err?.message });
      if (err) {
        if (err.code === "EPIPE") {
          return;
        }
        $gb(err);
      }
    };
    this.socket.on("error", this.a);
    let endTimeoutHandle;
    this.b = (hadError) => {
      this.traceSocketEvent("close", { hadError });
      this.f = false;
      if (endTimeoutHandle) {
        clearTimeout(endTimeoutHandle);
      }
    };
    this.socket.on("close", this.b);
    this.d = () => {
      this.traceSocketEvent(
        "nodeEndReceived"
        /* SocketDiagnosticsEventType.NodeEndReceived */
      );
      this.f = false;
      endTimeoutHandle = setTimeout(() => socket.destroy(), socketEndTimeoutMs);
    };
    this.socket.on("end", this.d);
  }
  dispose() {
    this.socket.off("error", this.a);
    this.socket.off("close", this.b);
    this.socket.off("end", this.d);
    this.socket.destroy();
  }
  onData(_listener) {
    const listener = (buff) => {
      this.traceSocketEvent("read", buff);
      _listener($Ci.wrap(buff));
    };
    this.socket.on("data", listener);
    return {
      dispose: () => this.socket.off("data", listener)
    };
  }
  onClose(listener) {
    const adapter = (hadError) => {
      listener({
        type: 0,
        hadError,
        error: void 0
      });
    };
    this.socket.on("close", adapter);
    return {
      dispose: () => this.socket.off("close", adapter)
    };
  }
  onEnd(listener) {
    const adapter = () => {
      listener();
    };
    this.socket.on("end", adapter);
    return {
      dispose: () => this.socket.off("end", adapter)
    };
  }
  write(buffer) {
    if (this.socket.destroyed || !this.f) {
      return;
    }
    try {
      this.traceSocketEvent("write", buffer);
      this.socket.write(buffer.buffer, (err) => {
        if (err) {
          if (err.code === "EPIPE") {
            return;
          }
          $gb(err);
        }
      });
    } catch (err) {
      if (err.code === "EPIPE") {
        return;
      }
      $gb(err);
    }
  }
  end() {
    this.traceSocketEvent(
      "nodeEndSent"
      /* SocketDiagnosticsEventType.NodeEndSent */
    );
    this.socket.end();
  }
  drain() {
    this.traceSocketEvent(
      "nodeDrainBegin"
      /* SocketDiagnosticsEventType.NodeDrainBegin */
    );
    return new Promise((resolve, reject) => {
      if (this.socket.bufferSize === 0) {
        this.traceSocketEvent(
          "nodeDrainEnd"
          /* SocketDiagnosticsEventType.NodeDrainEnd */
        );
        resolve();
        return;
      }
      const finished = () => {
        this.socket.off("close", finished);
        this.socket.off("end", finished);
        this.socket.off("error", finished);
        this.socket.off("timeout", finished);
        this.socket.off("drain", finished);
        this.traceSocketEvent(
          "nodeDrainEnd"
          /* SocketDiagnosticsEventType.NodeDrainEnd */
        );
        resolve();
      };
      this.socket.on("close", finished);
      this.socket.on("end", finished);
      this.socket.on("error", finished);
      this.socket.on("timeout", finished);
      this.socket.on("drain", finished);
    });
  }
};
var Constants;
(function(Constants3) {
  Constants3[Constants3["MinHeaderByteSize"] = 2] = "MinHeaderByteSize";
  Constants3[Constants3["MaxWebSocketMessageLength"] = 262144] = "MaxWebSocketMessageLength";
})(Constants || (Constants = {}));
var ReadState;
(function(ReadState2) {
  ReadState2[ReadState2["PeekHeader"] = 1] = "PeekHeader";
  ReadState2[ReadState2["ReadHeader"] = 2] = "ReadHeader";
  ReadState2[ReadState2["ReadBody"] = 3] = "ReadBody";
  ReadState2[ReadState2["Fin"] = 4] = "Fin";
})(ReadState || (ReadState = {}));
var $vu = class extends $3c {
  get permessageDeflate() {
    return this.a.permessageDeflate;
  }
  get recordedInflateBytes() {
    return this.a.recordedInflateBytes;
  }
  traceSocketEvent(type, data) {
    this.socket.traceSocketEvent(type, data);
  }
  /**
   * Create a socket which can communicate using WebSocket frames.
   *
   * **NOTE**: When using the permessage-deflate WebSocket extension, if parts of inflating was done
   *  in a different zlib instance, we need to pass all those bytes into zlib, otherwise the inflate
   *  might hit an inflated portion referencing a distance too far back.
   *
   * @param socket The underlying socket
   * @param permessageDeflate Use the permessage-deflate WebSocket extension
   * @param inflateBytes "Seed" zlib inflate with these bytes.
   * @param recordInflateBytes Record all bytes sent to inflate
   */
  constructor(socket, permessageDeflate, inflateBytes, recordInflateBytes) {
    super();
    this.f = this.B(new $ze());
    this.g = this.B(new $ze());
    this.h = false;
    this.j = {
      state: 1,
      readLen: 2,
      fin: 0,
      compressed: false,
      firstFrameOfMessage: true,
      mask: 0,
      opcode: 0
    };
    this.socket = socket;
    this.traceSocketEvent("created", { type: "WebSocketNodeSocket", permessageDeflate, inflateBytesLength: inflateBytes?.byteLength || 0, recordInflateBytes });
    this.a = this.B(new WebSocketFlowManager(this, permessageDeflate, inflateBytes, recordInflateBytes, this.f, (data, options2) => this.m(data, options2)));
    this.B(this.a.onError((err) => {
      console.error(err);
      $gb(err);
      this.g.fire({
        type: 0,
        hadError: true,
        error: err
      });
    }));
    this.b = new $pu();
    this.B(this.socket.onData((data) => this.n(data)));
    this.B(this.socket.onClose(async (e) => {
      if (this.a.isProcessingReadQueue()) {
        await Event.toPromise(this.a.onDidFinishProcessingReadQueue);
      }
      this.g.fire(e);
    }));
  }
  dispose() {
    if (this.a.isProcessingWriteQueue()) {
      this.B(this.a.onDidFinishProcessingWriteQueue(() => {
        this.dispose();
      }));
    } else {
      this.socket.dispose();
      super.dispose();
    }
  }
  onData(listener) {
    return this.f.event(listener);
  }
  onClose(listener) {
    return this.g.event(listener);
  }
  onEnd(listener) {
    return this.socket.onEnd(listener);
  }
  write(buffer) {
    let start = 0;
    while (start < buffer.byteLength) {
      this.a.writeMessage(buffer.slice(start, Math.min(start + 262144, buffer.byteLength)), {
        compressed: true,
        opcode: 2
        /* Binary frame */
      });
      start += 262144;
    }
  }
  m(buffer, { compressed, opcode }) {
    if (this.h) {
      return;
    }
    this.traceSocketEvent("webSocketNodeSocketWrite", buffer);
    let headerLen = 2;
    if (buffer.byteLength < 126) {
      headerLen += 0;
    } else if (buffer.byteLength < 2 ** 16) {
      headerLen += 2;
    } else {
      headerLen += 8;
    }
    const header = $Ci.alloc(headerLen);
    const compressedFlag = compressed ? 64 : 0;
    const opcodeFlag = opcode & 15;
    header.writeUInt8(128 | compressedFlag | opcodeFlag, 0);
    if (buffer.byteLength < 126) {
      header.writeUInt8(buffer.byteLength, 1);
    } else if (buffer.byteLength < 2 ** 16) {
      header.writeUInt8(126, 1);
      let offset = 1;
      header.writeUInt8(buffer.byteLength >>> 8 & 255, ++offset);
      header.writeUInt8(buffer.byteLength >>> 0 & 255, ++offset);
    } else {
      header.writeUInt8(127, 1);
      let offset = 1;
      header.writeUInt8(0, ++offset);
      header.writeUInt8(0, ++offset);
      header.writeUInt8(0, ++offset);
      header.writeUInt8(0, ++offset);
      header.writeUInt8(buffer.byteLength >>> 24 & 255, ++offset);
      header.writeUInt8(buffer.byteLength >>> 16 & 255, ++offset);
      header.writeUInt8(buffer.byteLength >>> 8 & 255, ++offset);
      header.writeUInt8(buffer.byteLength >>> 0 & 255, ++offset);
    }
    this.socket.write($Ci.concat([header, buffer]));
  }
  end() {
    this.h = true;
    this.socket.end();
  }
  n(data) {
    if (data.byteLength === 0) {
      return;
    }
    this.b.acceptChunk(data);
    while (this.b.byteLength >= this.j.readLen) {
      if (this.j.state === 1) {
        const peekHeader = this.b.peek(this.j.readLen);
        const firstByte = peekHeader.readUInt8(0);
        const finBit = (firstByte & 128) >>> 7;
        const rsv1Bit = (firstByte & 64) >>> 6;
        const opcode = firstByte & 15;
        const secondByte = peekHeader.readUInt8(1);
        const hasMask = (secondByte & 128) >>> 7;
        const len = secondByte & 127;
        this.j.state = 2;
        this.j.readLen = 2 + (hasMask ? 4 : 0) + (len === 126 ? 2 : 0) + (len === 127 ? 8 : 0);
        this.j.fin = finBit;
        if (this.j.firstFrameOfMessage) {
          this.j.compressed = Boolean(rsv1Bit);
        }
        this.j.firstFrameOfMessage = Boolean(finBit);
        this.j.mask = 0;
        this.j.opcode = opcode;
        this.traceSocketEvent("webSocketNodeSocketPeekedHeader", { headerSize: this.j.readLen, compressed: this.j.compressed, fin: this.j.fin, opcode: this.j.opcode });
      } else if (this.j.state === 2) {
        const header = this.b.read(this.j.readLen);
        const secondByte = header.readUInt8(1);
        const hasMask = (secondByte & 128) >>> 7;
        let len = secondByte & 127;
        let offset = 1;
        if (len === 126) {
          len = header.readUInt8(++offset) * 2 ** 8 + header.readUInt8(++offset);
        } else if (len === 127) {
          len = header.readUInt8(++offset) * 0 + header.readUInt8(++offset) * 0 + header.readUInt8(++offset) * 0 + header.readUInt8(++offset) * 0 + header.readUInt8(++offset) * 2 ** 24 + header.readUInt8(++offset) * 2 ** 16 + header.readUInt8(++offset) * 2 ** 8 + header.readUInt8(++offset);
        }
        let mask = 0;
        if (hasMask) {
          mask = header.readUInt8(++offset) * 2 ** 24 + header.readUInt8(++offset) * 2 ** 16 + header.readUInt8(++offset) * 2 ** 8 + header.readUInt8(++offset);
        }
        this.j.state = 3;
        this.j.readLen = len;
        this.j.mask = mask;
        this.traceSocketEvent("webSocketNodeSocketPeekedHeader", { bodySize: this.j.readLen, compressed: this.j.compressed, fin: this.j.fin, mask: this.j.mask, opcode: this.j.opcode });
      } else if (this.j.state === 3) {
        const body = this.b.read(this.j.readLen);
        this.traceSocketEvent("webSocketNodeSocketReadData", body);
        unmask(body, this.j.mask);
        this.traceSocketEvent("webSocketNodeSocketUnmaskedData", body);
        this.j.state = 1;
        this.j.readLen = 2;
        this.j.mask = 0;
        if (this.j.opcode <= 2) {
          this.a.acceptFrame(body, this.j.compressed, !!this.j.fin);
        } else if (this.j.opcode === 9) {
          this.a.writeMessage(body, {
            compressed: false,
            opcode: 10
            /* Pong frame */
          });
        }
      }
    }
  }
  async drain() {
    this.traceSocketEvent(
      "webSocketNodeSocketDrainBegin"
      /* SocketDiagnosticsEventType.WebSocketNodeSocketDrainBegin */
    );
    if (this.a.isProcessingWriteQueue()) {
      await Event.toPromise(this.a.onDidFinishProcessingWriteQueue);
    }
    await this.socket.drain();
    this.traceSocketEvent(
      "webSocketNodeSocketDrainEnd"
      /* SocketDiagnosticsEventType.WebSocketNodeSocketDrainEnd */
    );
  }
};
var WebSocketFlowManager = class extends $3c {
  get permessageDeflate() {
    return Boolean(this.b && this.f);
  }
  get recordedInflateBytes() {
    if (this.b) {
      return this.b.recordedInflateBytes;
    }
    return $Ci.alloc(0);
  }
  constructor(n, permessageDeflate, inflateBytes, recordInflateBytes, r, s) {
    super();
    this.n = n;
    this.r = r;
    this.s = s;
    this.a = this.B(new $ze());
    this.onError = this.a.event;
    this.g = [];
    this.h = [];
    this.j = this.B(new $ze());
    this.onDidFinishProcessingReadQueue = this.j.event;
    this.m = this.B(new $ze());
    this.onDidFinishProcessingWriteQueue = this.m.event;
    this.t = false;
    this.y = false;
    if (permessageDeflate) {
      this.b = this.B(new ZlibInflateStream(this.n, recordInflateBytes, inflateBytes, { windowBits: 15 }));
      this.f = this.B(new ZlibDeflateStream(this.n, { windowBits: 15 }));
      this.B(this.b.onError((err) => this.a.fire(err)));
      this.B(this.f.onError((err) => this.a.fire(err)));
    } else {
      this.b = null;
      this.f = null;
    }
  }
  writeMessage(data, options2) {
    this.g.push({ data, options: options2 });
    this.u();
  }
  async u() {
    if (this.t) {
      return;
    }
    this.t = true;
    while (this.g.length > 0) {
      const { data, options: options2 } = this.g.shift();
      if (this.f && options2.compressed) {
        const compressedData = await this.w(this.f, data);
        this.s(compressedData, options2);
      } else {
        this.s(data, { ...options2, compressed: false });
      }
    }
    this.t = false;
    this.m.fire();
  }
  isProcessingWriteQueue() {
    return this.t;
  }
  /**
   * Subsequent calls should wait for the previous `_deflateBuffer` call to complete.
   */
  w(zlibDeflateStream, buffer) {
    return new Promise((resolve, reject) => {
      zlibDeflateStream.write(buffer);
      zlibDeflateStream.flush((data) => resolve(data));
    });
  }
  acceptFrame(data, isCompressed, isLastFrameOfMessage) {
    this.h.push({ data, isCompressed, isLastFrameOfMessage });
    this.z();
  }
  async z() {
    if (this.y) {
      return;
    }
    this.y = true;
    while (this.h.length > 0) {
      const frameInfo = this.h.shift();
      if (this.b && frameInfo.isCompressed) {
        const data = await this.C(this.b, frameInfo.data, frameInfo.isLastFrameOfMessage);
        this.r.fire(data);
      } else {
        this.r.fire(frameInfo.data);
      }
    }
    this.y = false;
    this.j.fire();
  }
  isProcessingReadQueue() {
    return this.y;
  }
  /**
   * Subsequent calls should wait for the previous `transformRead` call to complete.
   */
  C(zlibInflateStream, buffer, isLastFrameOfMessage) {
    return new Promise((resolve, reject) => {
      zlibInflateStream.write(buffer);
      if (isLastFrameOfMessage) {
        zlibInflateStream.write($Ci.fromByteArray([0, 0, 255, 255]));
      }
      zlibInflateStream.flush((data) => resolve(data));
    });
  }
};
var ZlibInflateStream = class extends $3c {
  get recordedInflateBytes() {
    if (this.j) {
      return $Ci.concat(this.f);
    }
    return $Ci.alloc(0);
  }
  constructor(h, j, inflateBytes, options2) {
    super();
    this.h = h;
    this.j = j;
    this.a = this.B(new $ze());
    this.onError = this.a.event;
    this.f = [];
    this.g = [];
    this.b = createInflateRaw(options2);
    this.b.on("error", (err) => {
      this.h.traceSocketEvent("zlibInflateError", { message: err?.message, code: err?.code });
      this.a.fire(err);
    });
    this.b.on("data", (data) => {
      this.h.traceSocketEvent("zlibInflateData", data);
      this.g.push($Ci.wrap(data));
    });
    if (inflateBytes) {
      this.h.traceSocketEvent("zlibInflateInitialWrite", inflateBytes.buffer);
      this.b.write(inflateBytes.buffer);
      this.b.flush(() => {
        this.h.traceSocketEvent(
          "zlibInflateInitialFlushFired"
          /* SocketDiagnosticsEventType.zlibInflateInitialFlushFired */
        );
        this.g.length = 0;
      });
    }
  }
  write(buffer) {
    if (this.j) {
      this.f.push(buffer.clone());
    }
    this.h.traceSocketEvent("zlibInflateWrite", buffer);
    this.b.write(buffer.buffer);
  }
  flush(callback) {
    this.b.flush(() => {
      this.h.traceSocketEvent(
        "zlibInflateFlushFired"
        /* SocketDiagnosticsEventType.zlibInflateFlushFired */
      );
      const data = $Ci.concat(this.g);
      this.g.length = 0;
      callback(data);
    });
  }
};
var ZlibDeflateStream = class extends $3c {
  constructor(g, options2) {
    super();
    this.g = g;
    this.a = this.B(new $ze());
    this.onError = this.a.event;
    this.f = [];
    this.b = createDeflateRaw({
      windowBits: 15
    });
    this.b.on("error", (err) => {
      this.g.traceSocketEvent("zlibDeflateError", { message: err?.message, code: err?.code });
      this.a.fire(err);
    });
    this.b.on("data", (data) => {
      this.g.traceSocketEvent("zlibDeflateData", data);
      this.f.push($Ci.wrap(data));
    });
  }
  write(buffer) {
    this.g.traceSocketEvent("zlibDeflateWrite", buffer.buffer);
    this.b.write(buffer.buffer);
  }
  flush(callback) {
    this.b.flush(
      /*Z_SYNC_FLUSH*/
      2,
      () => {
        this.g.traceSocketEvent(
          "zlibDeflateFlushFired"
          /* SocketDiagnosticsEventType.zlibDeflateFlushFired */
        );
        let data = $Ci.concat(this.f);
        this.f.length = 0;
        data = data.slice(0, data.byteLength - 4);
        callback(data);
      }
    );
  }
};
function unmask(buffer, mask) {
  if (mask === 0) {
    return;
  }
  const cnt = buffer.byteLength >>> 2;
  for (let i = 0; i < cnt; i++) {
    const v = buffer.readUInt32BE(i * 4);
    buffer.writeUInt32BE(v ^ mask, i * 4);
  }
  const offset = cnt * 4;
  const bytesLeft = buffer.byteLength - offset;
  const m3 = mask >>> 24 & 255;
  const m2 = mask >>> 16 & 255;
  const m1 = mask >>> 8 & 255;
  if (bytesLeft >= 1) {
    buffer.writeUInt8(buffer.readUInt8(offset) ^ m3, offset);
  }
  if (bytesLeft >= 2) {
    buffer.writeUInt8(buffer.readUInt8(offset + 1) ^ m2, offset + 1);
  }
  if (bytesLeft >= 3) {
    buffer.writeUInt8(buffer.readUInt8(offset + 2) ^ m1, offset + 2);
  }
}
var $wu = process.env["XDG_RUNTIME_DIR"];
var safeIpcPathLengths = {
  [
    2
    /* Platform.Linux */
  ]: 107,
  [
    1
    /* Platform.Mac */
  ]: 103
};
function $xu() {
  const randomSuffix = $ps();
  if (process.platform === "win32") {
    return `\\\\.\\pipe\\vscode-ipc-${randomSuffix}-sock`;
  }
  const basePath = process.platform !== "darwin" && $wu ? $wu : tmpdir2();
  const result = $nc(basePath, `vscode-ipc-${randomSuffix}.sock`);
  validateIPCHandleLength(result);
  return result;
}
function validateIPCHandleLength(handle) {
  const limit = safeIpcPathLengths[$x];
  if (typeof limit === "number" && handle.length >= limit) {
    console.warn(`WARNING: IPC handle "${handle}" is longer than ${limit} chars, try a shorter --user-data-dir`);
  }
}

// out-build/vs/base/common/objects.js
function $Lv(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  if (obj instanceof RegExp) {
    return obj;
  }
  const result = Array.isArray(obj) ? [] : {};
  Object.entries(obj).forEach(([key, value]) => {
    result[key] = value && typeof value === "object" ? $Lv(value) : value;
  });
  return result;
}
function $Mv(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) && !$Cg(prop)) {
          stack.push(prop);
        }
      }
    }
  }
  return obj;
}
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function $Nv(obj, changer) {
  return _cloneAndChange(obj, changer, /* @__PURE__ */ new Set());
}
function _cloneAndChange(obj, changer, seen) {
  if ($Ig(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, seen));
    }
    return r1;
  }
  if ($Bg(obj)) {
    if (seen.has(obj)) {
      throw new Error("Cannot clone recursive data-structure");
    }
    seen.add(obj);
    const r2 = {};
    for (const i2 in obj) {
      if (_hasOwnProperty.call(obj, i2)) {
        r2[i2] = _cloneAndChange(obj[i2], changer, seen);
      }
    }
    seen.delete(obj);
    return r2;
  }
  return obj;
}
function $Ov(destination, source, overwrite = true) {
  if (!$Bg(destination)) {
    return source;
  }
  if ($Bg(source)) {
    Object.keys(source).forEach((key) => {
      if (key in destination) {
        if (overwrite) {
          if ($Bg(destination[key]) && $Bg(source[key])) {
            $Ov(destination[key], source[key], overwrite);
          } else {
            destination[key] = source[key];
          }
        }
      } else {
        destination[key] = source[key];
      }
    });
  }
  return destination;
}
function $Pv(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 (!$Pv(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 (!$Pv(oneKeys, otherKeys)) {
      return false;
    }
    for (i = 0; i < oneKeys.length; i++) {
      if (!$Pv(one[oneKeys[i]], other[oneKeys[i]])) {
        return false;
      }
    }
  }
  return true;
}
function $Qv(obj) {
  const seen = /* @__PURE__ */ new Set();
  return JSON.stringify(obj, (key, value) => {
    if ($Bg(value) || Array.isArray(value)) {
      if (seen.has(value)) {
        return "[Circular]";
      } else {
        seen.add(value);
      }
    }
    if (typeof value === "bigint") {
      return `[BigInt ${value.toString()}]`;
    }
    return value;
  });
}
function $Tv(obj, predicate) {
  const result = /* @__PURE__ */ Object.create(null);
  for (const [key, value] of Object.entries(obj)) {
    if (predicate(key, value)) {
      result[key] = value;
    }
  }
  return result;
}

// out-build/vs/editor/common/core/textModelDefaults.js
var $HD = {
  tabSize: 4,
  indentSize: 4,
  insertSpaces: true,
  detectIndentation: true,
  trimAutoWhitespace: true,
  largeFileOptimizations: true,
  bracketPairColorizationOptions: {
    enabled: true,
    independentColorPoolPerBracketType: false
  }
};

// out-build/vs/editor/common/core/wordHelper.js
var $ID = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";
function createWordRegExp(allowInWords = "") {
  let source = "(-?\\d*\\.\\d\\w*)|([^";
  for (const sep2 of $ID) {
    if (allowInWords.indexOf(sep2) >= 0) {
      continue;
    }
    source += "\\" + sep2;
  }
  source += "\\s]+)";
  return new RegExp(source, "g");
}
var $JD = createWordRegExp();
function $KD(wordDefinition) {
  let result = $JD;
  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";
      }
      result = new RegExp(wordDefinition.source, flags);
    } else {
      result = wordDefinition;
    }
  }
  result.lastIndex = 0;
  return result;
}
var _defaultConfig = new $cd();
_defaultConfig.unshift({
  maxLen: 1e3,
  windowSize: 15,
  timeBudget: 150
});
function $MD(column, wordDefinition, text, textOffset, config) {
  wordDefinition = $KD(wordDefinition);
  if (!config) {
    config = Iterable.first(_defaultConfig);
  }
  if (text.length > config.maxLen) {
    let start = column - config.maxLen / 2;
    if (start < 0) {
      start = 0;
    } else {
      textOffset += start;
    }
    text = text.substring(start, column + config.maxLen / 2);
    return $MD(column, wordDefinition, text, textOffset, config);
  }
  const t1 = Date.now();
  const pos = column - 1 - textOffset;
  let prevRegexIndex = -1;
  let match = null;
  for (let i = 1; ; i++) {
    if (Date.now() - t1 >= config.timeBudget) {
      break;
    }
    const regexIndex = pos - config.windowSize * i;
    wordDefinition.lastIndex = Math.max(0, regexIndex);
    const thisMatch = _findRegexMatchEnclosingPosition(wordDefinition, text, pos, prevRegexIndex);
    if (!thisMatch && match) {
      break;
    }
    match = thisMatch;
    if (regexIndex <= 0) {
      break;
    }
    prevRegexIndex = regexIndex;
  }
  if (match) {
    const result = {
      word: match[0],
      startColumn: textOffset + 1 + match.index,
      endColumn: textOffset + 1 + match.index + match[0].length
    };
    wordDefinition.lastIndex = 0;
    return result;
  }
  return null;
}
function _findRegexMatchEnclosingPosition(wordDefinition, text, pos, stopPos) {
  let match;
  while (match = wordDefinition.exec(text)) {
    const matchIndex = match.index || 0;
    if (matchIndex <= pos && wordDefinition.lastIndex >= pos) {
      return match;
    } else if (stopPos > 0 && matchIndex > stopPos) {
      return null;
    }
  }
  return null;
}

// out-build/vs/editor/common/config/editorOptions.js
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 MINIMAP_GUTTER_WIDTH = 8;
var ComputeOptionsMemory = class {
  constructor() {
    this.stableMinimapLayoutInput = null;
    this.stableFitMaxMinimapScale = 0;
    this.stableFitRemainingWidth = 0;
  }
};
var BaseEditorOption = class {
  constructor(id2, name, defaultValue, schema) {
    this.id = id2;
    this.name = name;
    this.defaultValue = defaultValue;
    this.schema = schema;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  compute(env2, options2, value) {
    return value;
  }
};
var ApplyUpdateResult = class {
  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) && $zb(value, update);
    return new ApplyUpdateResult(update, !arrayEquals);
  }
  let didChange = false;
  for (const key in update) {
    if (update.hasOwnProperty(key)) {
      const result = applyUpdate(value[key], update[key]);
      if (result.didChange) {
        value[key] = result.newValue;
        didChange = true;
      }
    }
  }
  return new ApplyUpdateResult(value, didChange);
}
var ComputedEditorOption = class {
  constructor(id2) {
    this.schema = void 0;
    this.id = id2;
    this.name = "_never_";
    this.defaultValue = void 0;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  validate(input) {
    return this.defaultValue;
  }
};
var SimpleEditorOption = class {
  constructor(id2, name, defaultValue, schema) {
    this.id = id2;
    this.name = name;
    this.defaultValue = defaultValue;
    this.schema = schema;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    return input;
  }
  compute(env2, options2, value) {
    return value;
  }
};
function boolean(value, defaultValue) {
  if (typeof value === "undefined") {
    return defaultValue;
  }
  if (value === "false") {
    return false;
  }
  return Boolean(value);
}
var EditorBooleanOption = class extends SimpleEditorOption {
  constructor(id2, name, defaultValue, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "boolean";
      schema.default = defaultValue;
    }
    super(id2, name, defaultValue, schema);
  }
  validate(input) {
    return boolean(input, 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;
}
var EditorIntOption = class _EditorIntOption extends SimpleEditorOption {
  static clampedInt(value, defaultValue, minimum, maximum) {
    return clampedInt(value, defaultValue, minimum, maximum);
  }
  constructor(id2, name, defaultValue, minimum, maximum, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "integer";
      schema.default = defaultValue;
      schema.minimum = minimum;
      schema.maximum = maximum;
    }
    super(id2, name, defaultValue, schema);
    this.minimum = minimum;
    this.maximum = maximum;
  }
  validate(input) {
    return _EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum);
  }
};
var EditorFloatOption = class _EditorFloatOption extends SimpleEditorOption {
  static clamp(n, min, max) {
    if (n < min) {
      return min;
    }
    if (n > max) {
      return max;
    }
    return n;
  }
  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(id2, name, defaultValue, validationFn, schema) {
    if (typeof schema !== "undefined") {
      schema.type = "number";
      schema.default = defaultValue;
    }
    super(id2, name, defaultValue, schema);
    this.validationFn = validationFn;
  }
  validate(input) {
    return this.validationFn(_EditorFloatOption.float(input, this.defaultValue));
  }
};
var EditorStringOption = class _EditorStringOption extends SimpleEditorOption {
  static string(value, defaultValue) {
    if (typeof value !== "string") {
      return defaultValue;
    }
    return value;
  }
  constructor(id2, name, defaultValue, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.default = defaultValue;
    }
    super(id2, name, defaultValue, schema);
  }
  validate(input) {
    return _EditorStringOption.string(input, 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;
}
var EditorStringEnumOption = class extends SimpleEditorOption {
  constructor(id2, name, defaultValue, allowedValues, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.enum = allowedValues;
      schema.default = defaultValue;
    }
    super(id2, name, defaultValue, schema);
    this.c = allowedValues;
  }
  validate(input) {
    return stringSet(input, this.defaultValue, this.c);
  }
};
var EditorEnumOption = class extends BaseEditorOption {
  constructor(id2, name, defaultValue, defaultStringValue, allowedValues, convert, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.enum = allowedValues;
      schema.default = defaultStringValue;
    }
    super(id2, name, defaultValue, schema);
    this.c = allowedValues;
    this.d = convert;
  }
  validate(input) {
    if (typeof input !== "string") {
      return this.defaultValue;
    }
    if (this.c.indexOf(input) === -1) {
      return this.defaultValue;
    }
    return this.d(input);
  }
};
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;
  }
}
var EditorAccessibilitySupport = class extends BaseEditorOption {
  constructor() {
    super(2, "accessibilitySupport", 0, {
      type: "string",
      enum: ["auto", "on", "off"],
      enumDescriptions: [
        localize(309, null),
        localize(310, null),
        localize(311, null)
      ],
      default: "auto",
      tags: ["accessibility"],
      description: localize(312, null)
    });
  }
  validate(input) {
    switch (input) {
      case "auto":
        return 0;
      case "off":
        return 1;
      case "on":
        return 2;
    }
    return this.defaultValue;
  }
  compute(env2, options2, value) {
    if (value === 0) {
      return env2.accessibilitySupport;
    }
    return value;
  }
};
var EditorComments = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      insertSpace: true,
      ignoreEmptyLines: true
    };
    super(23, "comments", defaults, {
      "editor.comments.insertSpace": {
        type: "boolean",
        default: defaults.insertSpace,
        description: localize(313, null)
      },
      "editor.comments.ignoreEmptyLines": {
        type: "boolean",
        default: defaults.ignoreEmptyLines,
        description: localize(314, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      insertSpace: boolean(input.insertSpace, this.defaultValue.insertSpace),
      ignoreEmptyLines: boolean(input.ignoreEmptyLines, this.defaultValue.ignoreEmptyLines)
    };
  }
};
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 = {}));
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;
(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 = {}));
function cursorStyleFromString(cursorStyle) {
  switch (cursorStyle) {
    case "line":
      return TextEditorCursorStyle.Line;
    case "block":
      return TextEditorCursorStyle.Block;
    case "underline":
      return TextEditorCursorStyle.Underline;
    case "line-thin":
      return TextEditorCursorStyle.LineThin;
    case "block-outline":
      return TextEditorCursorStyle.BlockOutline;
    case "underline-thin":
      return TextEditorCursorStyle.UnderlineThin;
  }
}
var EditorClassName = class extends ComputedEditorOption {
  constructor() {
    super(
      148
      /* EditorOption.editorClassName */
    );
  }
  compute(env2, options2, _) {
    const classNames = ["monaco-editor"];
    if (options2.get(
      41
      /* EditorOption.extraEditorClassName */
    )) {
      classNames.push(options2.get(
        41
        /* EditorOption.extraEditorClassName */
      ));
    }
    if (env2.extraEditorClassName) {
      classNames.push(env2.extraEditorClassName);
    }
    if (options2.get(
      75
      /* EditorOption.mouseStyle */
    ) === "default") {
      classNames.push("mouse-default");
    } else if (options2.get(
      75
      /* EditorOption.mouseStyle */
    ) === "copy") {
      classNames.push("mouse-copy");
    }
    if (options2.get(
      116
      /* EditorOption.showUnused */
    )) {
      classNames.push("showUnused");
    }
    if (options2.get(
      145
      /* EditorOption.showDeprecated */
    )) {
      classNames.push("showDeprecated");
    }
    return classNames.join(" ");
  }
};
var EditorEmptySelectionClipboard = class extends EditorBooleanOption {
  constructor() {
    super(38, "emptySelectionClipboard", true, { description: localize(315, null) });
  }
  compute(env2, options2, value) {
    return value && env2.emptySelectionClipboard;
  }
};
var EditorFind = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      cursorMoveOnType: true,
      seedSearchStringFromSelection: "always",
      autoFindInSelection: "never",
      globalFindClipboard: false,
      addExtraSpaceOnTop: true,
      loop: true,
      history: "workspace"
    };
    super(43, "find", defaults, {
      "editor.find.cursorMoveOnType": {
        type: "boolean",
        default: defaults.cursorMoveOnType,
        description: localize(316, null)
      },
      "editor.find.seedSearchStringFromSelection": {
        type: "string",
        enum: ["never", "always", "selection"],
        default: defaults.seedSearchStringFromSelection,
        enumDescriptions: [
          localize(317, null),
          localize(318, null),
          localize(319, null)
        ],
        description: localize(320, null)
      },
      "editor.find.autoFindInSelection": {
        type: "string",
        enum: ["never", "always", "multiline"],
        default: defaults.autoFindInSelection,
        enumDescriptions: [
          localize(321, null),
          localize(322, null),
          localize(323, null)
        ],
        description: localize(324, null)
      },
      "editor.find.globalFindClipboard": {
        type: "boolean",
        default: defaults.globalFindClipboard,
        description: localize(325, null),
        included: $m
      },
      "editor.find.addExtraSpaceOnTop": {
        type: "boolean",
        default: defaults.addExtraSpaceOnTop,
        description: localize(326, null)
      },
      "editor.find.loop": {
        type: "boolean",
        default: defaults.loop,
        description: localize(327, null)
      },
      "editor.find.history": {
        type: "string",
        enum: ["never", "workspace"],
        default: "workspace",
        enumDescriptions: [
          localize(328, null),
          localize(329, null)
        ],
        description: localize(330, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      cursorMoveOnType: boolean(input.cursorMoveOnType, this.defaultValue.cursorMoveOnType),
      seedSearchStringFromSelection: typeof _input.seedSearchStringFromSelection === "boolean" ? _input.seedSearchStringFromSelection ? "always" : "never" : stringSet(input.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection, ["never", "always", "selection"]),
      autoFindInSelection: typeof _input.autoFindInSelection === "boolean" ? _input.autoFindInSelection ? "always" : "never" : stringSet(input.autoFindInSelection, this.defaultValue.autoFindInSelection, ["never", "always", "multiline"]),
      globalFindClipboard: boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard),
      addExtraSpaceOnTop: boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop),
      loop: boolean(input.loop, this.defaultValue.loop),
      history: stringSet(input.history, this.defaultValue.history, ["never", "workspace"])
    };
  }
};
var EditorFontLigatures = class _EditorFontLigatures extends BaseEditorOption {
  static {
    this.OFF = '"liga" off, "calt" off';
  }
  static {
    this.ON = '"liga" on, "calt" on';
  }
  constructor() {
    super(53, "fontLigatures", _EditorFontLigatures.OFF, {
      anyOf: [
        {
          type: "boolean",
          description: localize(331, null)
        },
        {
          type: "string",
          description: localize(332, null)
        }
      ],
      description: localize(333, null),
      default: false
    });
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    if (typeof input === "string") {
      if (input === "false" || input.length === 0) {
        return _EditorFontLigatures.OFF;
      }
      if (input === "true") {
        return _EditorFontLigatures.ON;
      }
      return input;
    }
    if (Boolean(input)) {
      return _EditorFontLigatures.ON;
    }
    return _EditorFontLigatures.OFF;
  }
};
var EditorFontVariations = class _EditorFontVariations extends BaseEditorOption {
  static {
    this.OFF = "normal";
  }
  static {
    this.TRANSLATE = "translate";
  }
  constructor() {
    super(56, "fontVariations", _EditorFontVariations.OFF, {
      anyOf: [
        {
          type: "boolean",
          description: localize(334, null)
        },
        {
          type: "string",
          description: localize(335, null)
        }
      ],
      description: localize(336, null),
      default: false
    });
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    if (typeof input === "string") {
      if (input === "false") {
        return _EditorFontVariations.OFF;
      }
      if (input === "true") {
        return _EditorFontVariations.TRANSLATE;
      }
      return input;
    }
    if (Boolean(input)) {
      return _EditorFontVariations.TRANSLATE;
    }
    return _EditorFontVariations.OFF;
  }
  compute(env2, options2, value) {
    return env2.fontInfo.fontVariationSettings;
  }
};
var EditorFontInfo = class extends ComputedEditorOption {
  constructor() {
    super(
      52
      /* EditorOption.fontInfo */
    );
  }
  compute(env2, options2, _) {
    return env2.fontInfo;
  }
};
var EffectiveCursorStyle = class extends ComputedEditorOption {
  constructor() {
    super(
      147
      /* EditorOption.effectiveCursorStyle */
    );
  }
  compute(env2, options2, _) {
    return env2.inputMode === "overtype" ? options2.get(
      84
      /* EditorOption.overtypeCursorStyle */
    ) : options2.get(
      28
      /* EditorOption.cursorStyle */
    );
  }
};
var EditorFontSize = class extends SimpleEditorOption {
  constructor() {
    super(54, "fontSize", EDITOR_FONT_DEFAULTS.fontSize, {
      type: "number",
      minimum: 6,
      maximum: 100,
      default: EDITOR_FONT_DEFAULTS.fontSize,
      description: localize(337, null)
    });
  }
  validate(input) {
    const r = EditorFloatOption.float(input, this.defaultValue);
    if (r === 0) {
      return EDITOR_FONT_DEFAULTS.fontSize;
    }
    return EditorFloatOption.clamp(r, 6, 100);
  }
  compute(env2, options2, value) {
    return env2.fontInfo.fontSize;
  }
};
var EditorFontWeight = class _EditorFontWeight extends BaseEditorOption {
  static {
    this.c = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
  }
  static {
    this.d = 1;
  }
  static {
    this.e = 1e3;
  }
  constructor() {
    super(55, "fontWeight", EDITOR_FONT_DEFAULTS.fontWeight, {
      anyOf: [
        {
          type: "number",
          minimum: _EditorFontWeight.d,
          maximum: _EditorFontWeight.e,
          errorMessage: localize(338, null)
        },
        {
          type: "string",
          pattern: "^(normal|bold|1000|[1-9][0-9]{0,2})$"
        },
        {
          enum: _EditorFontWeight.c
        }
      ],
      default: EDITOR_FONT_DEFAULTS.fontWeight,
      description: localize(339, null)
    });
  }
  validate(input) {
    if (input === "normal" || input === "bold") {
      return input;
    }
    return String(EditorIntOption.clampedInt(input, EDITOR_FONT_DEFAULTS.fontWeight, _EditorFontWeight.d, _EditorFontWeight.e));
  }
};
var EditorGoToLocation = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      multiple: "peek",
      multipleDefinitions: "peek",
      multipleTypeDefinitions: "peek",
      multipleDeclarations: "peek",
      multipleImplementations: "peek",
      multipleReferences: "peek",
      multipleTests: "peek",
      alternativeDefinitionCommand: "editor.action.goToReferences",
      alternativeTypeDefinitionCommand: "editor.action.goToReferences",
      alternativeDeclarationCommand: "editor.action.goToReferences",
      alternativeImplementationCommand: "",
      alternativeReferenceCommand: "",
      alternativeTestsCommand: ""
    };
    const jsonSubset = {
      type: "string",
      enum: ["peek", "gotoAndPeek", "goto"],
      default: defaults.multiple,
      enumDescriptions: [
        localize(340, null),
        localize(341, null),
        localize(342, null)
      ]
    };
    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(60, "gotoLocation", defaults, {
      "editor.gotoLocation.multiple": {
        deprecationMessage: localize(343, null)
      },
      "editor.gotoLocation.multipleDefinitions": {
        description: localize(344, null),
        ...jsonSubset
      },
      "editor.gotoLocation.multipleTypeDefinitions": {
        description: localize(345, null),
        ...jsonSubset
      },
      "editor.gotoLocation.multipleDeclarations": {
        description: localize(346, null),
        ...jsonSubset
      },
      "editor.gotoLocation.multipleImplementations": {
        description: localize(347, null),
        ...jsonSubset
      },
      "editor.gotoLocation.multipleReferences": {
        description: localize(348, null),
        ...jsonSubset
      },
      "editor.gotoLocation.alternativeDefinitionCommand": {
        type: "string",
        default: defaults.alternativeDefinitionCommand,
        enum: alternativeCommandOptions,
        description: localize(349, null)
      },
      "editor.gotoLocation.alternativeTypeDefinitionCommand": {
        type: "string",
        default: defaults.alternativeTypeDefinitionCommand,
        enum: alternativeCommandOptions,
        description: localize(350, null)
      },
      "editor.gotoLocation.alternativeDeclarationCommand": {
        type: "string",
        default: defaults.alternativeDeclarationCommand,
        enum: alternativeCommandOptions,
        description: localize(351, null)
      },
      "editor.gotoLocation.alternativeImplementationCommand": {
        type: "string",
        default: defaults.alternativeImplementationCommand,
        enum: alternativeCommandOptions,
        description: localize(352, null)
      },
      "editor.gotoLocation.alternativeReferenceCommand": {
        type: "string",
        default: defaults.alternativeReferenceCommand,
        enum: alternativeCommandOptions,
        description: localize(353, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      multiple: stringSet(input.multiple, this.defaultValue.multiple, ["peek", "gotoAndPeek", "goto"]),
      multipleDefinitions: input.multipleDefinitions ?? stringSet(input.multipleDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleTypeDefinitions: input.multipleTypeDefinitions ?? stringSet(input.multipleTypeDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleDeclarations: input.multipleDeclarations ?? stringSet(input.multipleDeclarations, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleImplementations: input.multipleImplementations ?? stringSet(input.multipleImplementations, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleReferences: input.multipleReferences ?? stringSet(input.multipleReferences, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleTests: input.multipleTests ?? stringSet(input.multipleTests, "peek", ["peek", "gotoAndPeek", "goto"]),
      alternativeDefinitionCommand: EditorStringOption.string(input.alternativeDefinitionCommand, this.defaultValue.alternativeDefinitionCommand),
      alternativeTypeDefinitionCommand: EditorStringOption.string(input.alternativeTypeDefinitionCommand, this.defaultValue.alternativeTypeDefinitionCommand),
      alternativeDeclarationCommand: EditorStringOption.string(input.alternativeDeclarationCommand, this.defaultValue.alternativeDeclarationCommand),
      alternativeImplementationCommand: EditorStringOption.string(input.alternativeImplementationCommand, this.defaultValue.alternativeImplementationCommand),
      alternativeReferenceCommand: EditorStringOption.string(input.alternativeReferenceCommand, this.defaultValue.alternativeReferenceCommand),
      alternativeTestsCommand: EditorStringOption.string(input.alternativeTestsCommand, this.defaultValue.alternativeTestsCommand)
    };
  }
};
var EditorHover = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      delay: 300,
      hidingDelay: 300,
      sticky: true,
      above: true
    };
    super(62, "hover", defaults, {
      "editor.hover.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(354, null)
      },
      "editor.hover.delay": {
        type: "number",
        default: defaults.delay,
        minimum: 0,
        maximum: 1e4,
        description: localize(355, null)
      },
      "editor.hover.sticky": {
        type: "boolean",
        default: defaults.sticky,
        description: localize(356, null)
      },
      "editor.hover.hidingDelay": {
        type: "integer",
        minimum: 0,
        default: defaults.hidingDelay,
        description: localize(357, null)
      },
      "editor.hover.above": {
        type: "boolean",
        default: defaults.above,
        description: localize(358, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 1e4),
      sticky: boolean(input.sticky, this.defaultValue.sticky),
      hidingDelay: EditorIntOption.clampedInt(input.hidingDelay, this.defaultValue.hidingDelay, 0, 6e5),
      above: boolean(input.above, this.defaultValue.above)
    };
  }
};
var RenderMinimap;
(function(RenderMinimap2) {
  RenderMinimap2[RenderMinimap2["None"] = 0] = "None";
  RenderMinimap2[RenderMinimap2["Text"] = 1] = "Text";
  RenderMinimap2[RenderMinimap2["Blocks"] = 2] = "Blocks";
})(RenderMinimap || (RenderMinimap = {}));
var EditorLayoutInfoComputer = class _EditorLayoutInfoComputer extends ComputedEditorOption {
  constructor() {
    super(
      151
      /* EditorOption.layoutInfo */
    );
  }
  compute(env2, options2, _) {
    return _EditorLayoutInfoComputer.computeLayout(options2, {
      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(input) {
    const typicalViewportLineCount = input.height / input.lineHeight;
    const extraLinesBeforeFirstLine = Math.floor(input.paddingTop / input.lineHeight);
    let extraLinesBeyondLastLine = Math.floor(input.paddingBottom / input.lineHeight);
    if (input.scrollBeyondLastLine) {
      extraLinesBeyondLastLine = Math.max(extraLinesBeyondLastLine, typicalViewportLineCount - 1);
    }
    const desiredRatio = (extraLinesBeforeFirstLine + input.viewLineCount + extraLinesBeyondLastLine) / (input.pixelRatio * input.height);
    const minimapLineCount = Math.floor(input.viewLineCount / desiredRatio);
    return { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount };
  }
  static c(input, memory) {
    const outerWidth = input.outerWidth;
    const outerHeight = input.outerHeight;
    const pixelRatio = input.pixelRatio;
    if (!input.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 && input.outerHeight === stableMinimapLayoutInput.outerHeight && input.lineHeight === stableMinimapLayoutInput.lineHeight && input.typicalHalfwidthCharacterWidth === stableMinimapLayoutInput.typicalHalfwidthCharacterWidth && input.pixelRatio === stableMinimapLayoutInput.pixelRatio && input.scrollBeyondLastLine === stableMinimapLayoutInput.scrollBeyondLastLine && input.paddingTop === stableMinimapLayoutInput.paddingTop && input.paddingBottom === stableMinimapLayoutInput.paddingBottom && input.minimap.enabled === stableMinimapLayoutInput.minimap.enabled && input.minimap.side === stableMinimapLayoutInput.minimap.side && input.minimap.size === stableMinimapLayoutInput.minimap.size && input.minimap.showSlider === stableMinimapLayoutInput.minimap.showSlider && input.minimap.renderCharacters === stableMinimapLayoutInput.minimap.renderCharacters && input.minimap.maxColumn === stableMinimapLayoutInput.minimap.maxColumn && input.minimap.scale === stableMinimapLayoutInput.minimap.scale && input.verticalScrollbarWidth === stableMinimapLayoutInput.verticalScrollbarWidth && input.isViewportWrapping === stableMinimapLayoutInput.isViewportWrapping;
    const lineHeight = input.lineHeight;
    const typicalHalfwidthCharacterWidth = input.typicalHalfwidthCharacterWidth;
    const scrollBeyondLastLine = input.scrollBeyondLastLine;
    const minimapRenderCharacters = input.minimap.renderCharacters;
    let minimapScale = pixelRatio >= 2 ? Math.round(input.minimap.scale * 2) : input.minimap.scale;
    const minimapMaxColumn = input.minimap.maxColumn;
    const minimapSize = input.minimap.size;
    const minimapSide = input.minimap.side;
    const verticalScrollbarWidth = input.verticalScrollbarWidth;
    const viewLineCount = input.viewLineCount;
    const remainingWidth = input.remainingWidth;
    const isViewportWrapping = input.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: input.paddingTop,
        paddingBottom: input.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 = input;
            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(options2, 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 = options2.get(
      142
      /* EditorOption.wordWrapOverride2 */
    );
    const wordWrapOverride1 = wordWrapOverride2 === "inherit" ? options2.get(
      141
      /* EditorOption.wordWrapOverride1 */
    ) : wordWrapOverride2;
    const wordWrap = wordWrapOverride1 === "inherit" ? options2.get(
      137
      /* EditorOption.wordWrap */
    ) : wordWrapOverride1;
    const wordWrapColumn = options2.get(
      140
      /* EditorOption.wordWrapColumn */
    );
    const isDominatedByLongLines = env2.isDominatedByLongLines;
    const showGlyphMargin = options2.get(
      59
      /* EditorOption.glyphMargin */
    );
    const showLineNumbers = options2.get(
      69
      /* EditorOption.lineNumbers */
    ).renderType !== 0;
    const lineNumbersMinChars = options2.get(
      70
      /* EditorOption.lineNumbersMinChars */
    );
    const scrollBeyondLastLine = options2.get(
      110
      /* EditorOption.scrollBeyondLastLine */
    );
    const padding = options2.get(
      88
      /* EditorOption.padding */
    );
    const minimap = options2.get(
      74
      /* EditorOption.minimap */
    );
    const scrollbar = options2.get(
      108
      /* EditorOption.scrollbar */
    );
    const verticalScrollbarWidth = scrollbar.verticalScrollbarSize;
    const verticalScrollbarHasArrows = scrollbar.verticalHasArrows;
    const scrollbarArrowSize = scrollbar.arrowSize;
    const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize;
    const folding = options2.get(
      45
      /* EditorOption.folding */
    );
    const showFoldingDecoration = options2.get(
      115
      /* EditorOption.showFoldingControls */
    ) !== "never";
    let lineDecorationsWidth = options2.get(
      67
      /* EditorOption.lineDecorationsWidth */
    );
    if (folding && showFoldingDecoration) {
      lineDecorationsWidth += 16;
    }
    let lineNumbersWidth = 0;
    if (showLineNumbers) {
      const digitCount = Math.max(lineNumbersDigitCount, lineNumbersMinChars);
      lineNumbersWidth = Math.round(digitCount * 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.c({
      outerWidth,
      outerHeight,
      lineHeight,
      typicalHalfwidthCharacterWidth,
      pixelRatio,
      scrollBeyondLastLine,
      paddingTop: padding.top,
      paddingBottom: padding.bottom,
      minimap,
      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
      }
    };
  }
};
var WrappingStrategy = class extends BaseEditorOption {
  constructor() {
    super(144, "wrappingStrategy", "simple", {
      "editor.wrappingStrategy": {
        enumDescriptions: [
          localize(359, null),
          localize(360, null)
        ],
        type: "string",
        enum: ["simple", "advanced"],
        default: "simple",
        description: localize(361, null)
      }
    });
  }
  validate(input) {
    return stringSet(input, "simple", ["simple", "advanced"]);
  }
  compute(env2, options2, value) {
    const accessibilitySupport = options2.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    if (accessibilitySupport === 2) {
      return "advanced";
    }
    return value;
  }
};
var ShowLightbulbIconMode;
(function(ShowLightbulbIconMode2) {
  ShowLightbulbIconMode2["Off"] = "off";
  ShowLightbulbIconMode2["OnCode"] = "onCode";
  ShowLightbulbIconMode2["On"] = "on";
})(ShowLightbulbIconMode || (ShowLightbulbIconMode = {}));
var EditorLightbulb = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: ShowLightbulbIconMode.OnCode };
    super(66, "lightbulb", defaults, {
      "editor.lightbulb.enabled": {
        type: "string",
        enum: [ShowLightbulbIconMode.Off, ShowLightbulbIconMode.OnCode, ShowLightbulbIconMode.On],
        default: defaults.enabled,
        enumDescriptions: [
          localize(362, null),
          localize(363, null),
          localize(364, null)
        ],
        description: localize(365, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: stringSet(input.enabled, this.defaultValue.enabled, [ShowLightbulbIconMode.Off, ShowLightbulbIconMode.OnCode, ShowLightbulbIconMode.On])
    };
  }
};
var EditorStickyScroll = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true, maxLineCount: 5, defaultModel: "outlineModel", scrollWithEditor: true };
    super(120, "stickyScroll", defaults, {
      "editor.stickyScroll.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(366, null)
      },
      "editor.stickyScroll.maxLineCount": {
        type: "number",
        default: defaults.maxLineCount,
        minimum: 1,
        maximum: 20,
        description: localize(367, null)
      },
      "editor.stickyScroll.defaultModel": {
        type: "string",
        enum: ["outlineModel", "foldingProviderModel", "indentationModel"],
        default: defaults.defaultModel,
        description: localize(368, null)
      },
      "editor.stickyScroll.scrollWithEditor": {
        type: "boolean",
        default: defaults.scrollWithEditor,
        description: localize(369, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      maxLineCount: EditorIntOption.clampedInt(input.maxLineCount, this.defaultValue.maxLineCount, 1, 20),
      defaultModel: stringSet(input.defaultModel, this.defaultValue.defaultModel, ["outlineModel", "foldingProviderModel", "indentationModel"]),
      scrollWithEditor: boolean(input.scrollWithEditor, this.defaultValue.scrollWithEditor)
    };
  }
};
var EditorInlayHints = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: "on", fontSize: 0, fontFamily: "", padding: false, maximumLength: 43 };
    super(146, "inlayHints", defaults, {
      "editor.inlayHints.enabled": {
        type: "string",
        default: defaults.enabled,
        description: localize(370, null),
        enum: ["on", "onUnlessPressed", "offUnlessPressed", "off"],
        markdownEnumDescriptions: [
          localize(371, null),
          localize(372, null, $m ? `Ctrl+Option` : `Ctrl+Alt`),
          localize(373, null, $m ? `Ctrl+Option` : `Ctrl+Alt`),
          localize(374, null)
        ]
      },
      "editor.inlayHints.fontSize": {
        type: "number",
        default: defaults.fontSize,
        markdownDescription: localize(375, null, "`#editor.fontSize#`", "`5`")
      },
      "editor.inlayHints.fontFamily": {
        type: "string",
        default: defaults.fontFamily,
        markdownDescription: localize(376, null, "`#editor.fontFamily#`")
      },
      "editor.inlayHints.padding": {
        type: "boolean",
        default: defaults.padding,
        description: localize(377, null)
      },
      "editor.inlayHints.maximumLength": {
        type: "number",
        default: defaults.maximumLength,
        markdownDescription: localize(378, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    if (typeof input.enabled === "boolean") {
      input.enabled = input.enabled ? "on" : "off";
    }
    return {
      enabled: stringSet(input.enabled, this.defaultValue.enabled, ["on", "off", "offUnlessPressed", "onUnlessPressed"]),
      fontSize: EditorIntOption.clampedInt(input.fontSize, this.defaultValue.fontSize, 0, 100),
      fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily),
      padding: boolean(input.padding, this.defaultValue.padding),
      maximumLength: EditorIntOption.clampedInt(input.maximumLength, this.defaultValue.maximumLength, 0, Number.MAX_SAFE_INTEGER)
    };
  }
};
var EditorLineDecorationsWidth = class extends BaseEditorOption {
  constructor() {
    super(67, "lineDecorationsWidth", 10);
  }
  validate(input) {
    if (typeof input === "string" && /^\d+(\.\d+)?ch$/.test(input)) {
      const multiple = parseFloat(input.substring(0, input.length - 2));
      return -multiple;
    } else {
      return EditorIntOption.clampedInt(input, this.defaultValue, 0, 1e3);
    }
  }
  compute(env2, options2, value) {
    if (value < 0) {
      return EditorIntOption.clampedInt(-value * env2.fontInfo.typicalHalfwidthCharacterWidth, this.defaultValue, 0, 1e3);
    } else {
      return value;
    }
  }
};
var EditorLineHeight = class extends EditorFloatOption {
  constructor() {
    super(68, "lineHeight", EDITOR_FONT_DEFAULTS.lineHeight, (x) => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: localize(379, null) });
  }
  compute(env2, options2, value) {
    return env2.fontInfo.lineHeight;
  }
};
var EditorMinimap = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      size: "proportional",
      side: "right",
      showSlider: "mouseover",
      autohide: false,
      renderCharacters: true,
      maxColumn: 120,
      scale: 1,
      showRegionSectionHeaders: true,
      showMarkSectionHeaders: true,
      sectionHeaderFontSize: 9,
      sectionHeaderLetterSpacing: 1
    };
    super(74, "minimap", defaults, {
      "editor.minimap.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(380, null)
      },
      "editor.minimap.autohide": {
        type: "boolean",
        default: defaults.autohide,
        description: localize(381, null)
      },
      "editor.minimap.size": {
        type: "string",
        enum: ["proportional", "fill", "fit"],
        enumDescriptions: [
          localize(382, null),
          localize(383, null),
          localize(384, null)
        ],
        default: defaults.size,
        description: localize(385, null)
      },
      "editor.minimap.side": {
        type: "string",
        enum: ["left", "right"],
        default: defaults.side,
        description: localize(386, null)
      },
      "editor.minimap.showSlider": {
        type: "string",
        enum: ["always", "mouseover"],
        default: defaults.showSlider,
        description: localize(387, null)
      },
      "editor.minimap.scale": {
        type: "number",
        default: defaults.scale,
        minimum: 1,
        maximum: 3,
        enum: [1, 2, 3],
        description: localize(388, null)
      },
      "editor.minimap.renderCharacters": {
        type: "boolean",
        default: defaults.renderCharacters,
        description: localize(389, null)
      },
      "editor.minimap.maxColumn": {
        type: "number",
        default: defaults.maxColumn,
        description: localize(390, null)
      },
      "editor.minimap.showRegionSectionHeaders": {
        type: "boolean",
        default: defaults.showRegionSectionHeaders,
        description: localize(391, null)
      },
      "editor.minimap.showMarkSectionHeaders": {
        type: "boolean",
        default: defaults.showMarkSectionHeaders,
        description: localize(392, null)
      },
      "editor.minimap.sectionHeaderFontSize": {
        type: "number",
        default: defaults.sectionHeaderFontSize,
        description: localize(393, null)
      },
      "editor.minimap.sectionHeaderLetterSpacing": {
        type: "number",
        default: defaults.sectionHeaderLetterSpacing,
        description: localize(394, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      autohide: boolean(input.autohide, this.defaultValue.autohide),
      size: stringSet(input.size, this.defaultValue.size, ["proportional", "fill", "fit"]),
      side: stringSet(input.side, this.defaultValue.side, ["right", "left"]),
      showSlider: stringSet(input.showSlider, this.defaultValue.showSlider, ["always", "mouseover"]),
      renderCharacters: boolean(input.renderCharacters, this.defaultValue.renderCharacters),
      scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3),
      maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 1e4),
      showRegionSectionHeaders: boolean(input.showRegionSectionHeaders, this.defaultValue.showRegionSectionHeaders),
      showMarkSectionHeaders: boolean(input.showMarkSectionHeaders, this.defaultValue.showMarkSectionHeaders),
      sectionHeaderFontSize: EditorFloatOption.clamp(input.sectionHeaderFontSize ?? this.defaultValue.sectionHeaderFontSize, 4, 32),
      sectionHeaderLetterSpacing: EditorFloatOption.clamp(input.sectionHeaderLetterSpacing ?? this.defaultValue.sectionHeaderLetterSpacing, 0, 5)
    };
  }
};
function _multiCursorModifierFromString(multiCursorModifier) {
  if (multiCursorModifier === "ctrlCmd") {
    return $m ? "metaKey" : "ctrlKey";
  }
  return "altKey";
}
var EditorPadding = class extends BaseEditorOption {
  constructor() {
    super(88, "padding", { top: 0, bottom: 0 }, {
      "editor.padding.top": {
        type: "number",
        default: 0,
        minimum: 0,
        maximum: 1e3,
        description: localize(395, null)
      },
      "editor.padding.bottom": {
        type: "number",
        default: 0,
        minimum: 0,
        maximum: 1e3,
        description: localize(396, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      top: EditorIntOption.clampedInt(input.top, 0, 0, 1e3),
      bottom: EditorIntOption.clampedInt(input.bottom, 0, 0, 1e3)
    };
  }
};
var EditorParameterHints = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      cycle: true
    };
    super(90, "parameterHints", defaults, {
      "editor.parameterHints.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(397, null)
      },
      "editor.parameterHints.cycle": {
        type: "boolean",
        default: defaults.cycle,
        description: localize(398, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      cycle: boolean(input.cycle, this.defaultValue.cycle)
    };
  }
};
var EditorPixelRatio = class extends ComputedEditorOption {
  constructor() {
    super(
      149
      /* EditorOption.pixelRatio */
    );
  }
  compute(env2, options2, _) {
    return env2.pixelRatio;
  }
};
var PlaceholderOption = class extends BaseEditorOption {
  constructor() {
    super(92, "placeholder", void 0);
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    if (typeof input === "string") {
      return input;
    }
    return this.defaultValue;
  }
};
var EditorQuickSuggestions = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      other: "on",
      comments: "off",
      strings: "off"
    };
    const types = [
      { type: "boolean" },
      {
        type: "string",
        enum: ["on", "inline", "off"],
        enumDescriptions: [localize(399, null), localize(400, null), localize(401, null)]
      }
    ];
    super(94, "quickSuggestions", defaults, {
      type: "object",
      additionalProperties: false,
      properties: {
        strings: {
          anyOf: types,
          default: defaults.strings,
          description: localize(402, null)
        },
        comments: {
          anyOf: types,
          default: defaults.comments,
          description: localize(403, null)
        },
        other: {
          anyOf: types,
          default: defaults.other,
          description: localize(404, null)
        }
      },
      default: defaults,
      markdownDescription: localize(405, null, "`#editor.suggestOnTriggerCharacters#`")
    });
    this.defaultValue = defaults;
  }
  validate(input) {
    if (typeof input === "boolean") {
      const value = input ? "on" : "off";
      return { comments: value, strings: value, other: value };
    }
    if (!input || typeof input !== "object") {
      return this.defaultValue;
    }
    const { other, comments, strings } = input;
    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
    };
  }
};
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 EditorRenderLineNumbersOption = class extends BaseEditorOption {
  constructor() {
    super(69, "lineNumbers", { renderType: 1, renderFn: null }, {
      type: "string",
      enum: ["off", "on", "relative", "interval"],
      enumDescriptions: [
        localize(406, null),
        localize(407, null),
        localize(408, null),
        localize(409, null)
      ],
      default: "on",
      description: localize(410, null)
    });
  }
  validate(lineNumbers) {
    let renderType = this.defaultValue.renderType;
    let renderFn = this.defaultValue.renderFn;
    if (typeof lineNumbers !== "undefined") {
      if (typeof lineNumbers === "function") {
        renderType = 4;
        renderFn = lineNumbers;
      } else if (lineNumbers === "interval") {
        renderType = 3;
      } else if (lineNumbers === "relative") {
        renderType = 2;
      } else if (lineNumbers === "on") {
        renderType = 1;
      } else {
        renderType = 0;
      }
    }
    return {
      renderType,
      renderFn
    };
  }
};
var EditorRulers = class extends BaseEditorOption {
  constructor() {
    const defaults = [];
    const columnSchema = { type: "number", description: localize(411, null) };
    super(107, "rulers", defaults, {
      type: "array",
      items: {
        anyOf: [
          columnSchema,
          {
            type: [
              "object"
            ],
            properties: {
              column: columnSchema,
              color: {
                type: "string",
                description: localize(412, null),
                format: "color-hex"
              }
            }
          }
        ]
      },
      default: defaults,
      description: localize(413, null)
    });
  }
  validate(input) {
    if (Array.isArray(input)) {
      const rulers = [];
      for (const _element of input) {
        if (typeof _element === "number") {
          rulers.push({
            column: EditorIntOption.clampedInt(_element, 0, 0, 1e4),
            color: null
          });
        } else if (_element && typeof _element === "object") {
          const element = _element;
          rulers.push({
            column: EditorIntOption.clampedInt(element.column, 0, 0, 1e4),
            color: element.color
          });
        }
      }
      rulers.sort((a, b) => a.column - b.column);
      return rulers;
    }
    return this.defaultValue;
  }
};
var ReadonlyMessage = class extends BaseEditorOption {
  constructor() {
    const defaults = void 0;
    super(97, "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;
  }
}
var EditorScrollbar = class 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,
      ignoreHorizontalScrollbarInContentHeight: false
    };
    super(108, "scrollbar", defaults, {
      "editor.scrollbar.vertical": {
        type: "string",
        enum: ["auto", "visible", "hidden"],
        enumDescriptions: [
          localize(414, null),
          localize(415, null),
          localize(416, null)
        ],
        default: "auto",
        description: localize(417, null)
      },
      "editor.scrollbar.horizontal": {
        type: "string",
        enum: ["auto", "visible", "hidden"],
        enumDescriptions: [
          localize(418, null),
          localize(419, null),
          localize(420, null)
        ],
        default: "auto",
        description: localize(421, null)
      },
      "editor.scrollbar.verticalScrollbarSize": {
        type: "number",
        default: defaults.verticalScrollbarSize,
        description: localize(422, null)
      },
      "editor.scrollbar.horizontalScrollbarSize": {
        type: "number",
        default: defaults.horizontalScrollbarSize,
        description: localize(423, null)
      },
      "editor.scrollbar.scrollByPage": {
        type: "boolean",
        default: defaults.scrollByPage,
        description: localize(424, null)
      },
      "editor.scrollbar.ignoreHorizontalScrollbarInContentHeight": {
        type: "boolean",
        default: defaults.ignoreHorizontalScrollbarInContentHeight,
        description: localize(425, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    const horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1e3);
    const verticalScrollbarSize = EditorIntOption.clampedInt(input.verticalScrollbarSize, this.defaultValue.verticalScrollbarSize, 0, 1e3);
    return {
      arrowSize: EditorIntOption.clampedInt(input.arrowSize, this.defaultValue.arrowSize, 0, 1e3),
      vertical: _scrollbarVisibilityFromString(input.vertical, this.defaultValue.vertical),
      horizontal: _scrollbarVisibilityFromString(input.horizontal, this.defaultValue.horizontal),
      useShadows: boolean(input.useShadows, this.defaultValue.useShadows),
      verticalHasArrows: boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows),
      horizontalHasArrows: boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows),
      handleMouseWheel: boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel),
      alwaysConsumeMouseWheel: boolean(input.alwaysConsumeMouseWheel, this.defaultValue.alwaysConsumeMouseWheel),
      horizontalScrollbarSize,
      horizontalSliderSize: EditorIntOption.clampedInt(input.horizontalSliderSize, horizontalScrollbarSize, 0, 1e3),
      verticalScrollbarSize,
      verticalSliderSize: EditorIntOption.clampedInt(input.verticalSliderSize, verticalScrollbarSize, 0, 1e3),
      scrollByPage: boolean(input.scrollByPage, this.defaultValue.scrollByPage),
      ignoreHorizontalScrollbarInContentHeight: boolean(input.ignoreHorizontalScrollbarInContentHeight, this.defaultValue.ignoreHorizontalScrollbarInContentHeight)
    };
  }
};
var inUntrustedWorkspace = "inUntrustedWorkspace";
var 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"
};
var UnicodeHighlight = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      nonBasicASCII: inUntrustedWorkspace,
      invisibleCharacters: true,
      ambiguousCharacters: true,
      includeComments: inUntrustedWorkspace,
      includeStrings: true,
      allowedCharacters: {},
      allowedLocales: { _os: true, _vscode: true }
    };
    super(130, "unicodeHighlight", defaults, {
      [unicodeHighlightConfigKeys.nonBasicASCII]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.nonBasicASCII,
        description: localize(426, null)
      },
      [unicodeHighlightConfigKeys.invisibleCharacters]: {
        restricted: true,
        type: "boolean",
        default: defaults.invisibleCharacters,
        description: localize(427, null)
      },
      [unicodeHighlightConfigKeys.ambiguousCharacters]: {
        restricted: true,
        type: "boolean",
        default: defaults.ambiguousCharacters,
        description: localize(428, null)
      },
      [unicodeHighlightConfigKeys.includeComments]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.includeComments,
        description: localize(429, null)
      },
      [unicodeHighlightConfigKeys.includeStrings]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.includeStrings,
        description: localize(430, null)
      },
      [unicodeHighlightConfigKeys.allowedCharacters]: {
        restricted: true,
        type: "object",
        default: defaults.allowedCharacters,
        description: localize(431, null),
        additionalProperties: {
          type: "boolean"
        }
      },
      [unicodeHighlightConfigKeys.allowedLocales]: {
        restricted: true,
        type: "object",
        additionalProperties: {
          type: "boolean"
        },
        default: defaults.allowedLocales,
        description: localize(432, null)
      }
    });
  }
  applyUpdate(value, update) {
    let didChange = false;
    if (update.allowedCharacters && value) {
      if (!$Pv(value.allowedCharacters, update.allowedCharacters)) {
        value = { ...value, allowedCharacters: update.allowedCharacters };
        didChange = true;
      }
    }
    if (update.allowedLocales && value) {
      if (!$Pv(value.allowedLocales, update.allowedLocales)) {
        value = { ...value, allowedLocales: update.allowedLocales };
        didChange = true;
      }
    }
    const result = super.applyUpdate(value, update);
    if (didChange) {
      return new ApplyUpdateResult(result.newValue, true);
    }
    return result;
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      nonBasicASCII: primitiveSet(input.nonBasicASCII, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      invisibleCharacters: boolean(input.invisibleCharacters, this.defaultValue.invisibleCharacters),
      ambiguousCharacters: boolean(input.ambiguousCharacters, this.defaultValue.ambiguousCharacters),
      includeComments: primitiveSet(input.includeComments, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      includeStrings: primitiveSet(input.includeStrings, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      allowedCharacters: this.c(_input.allowedCharacters, this.defaultValue.allowedCharacters),
      allowedLocales: this.c(_input.allowedLocales, this.defaultValue.allowedLocales)
    };
  }
  c(map, defaultValue) {
    if (typeof map !== "object" || !map) {
      return defaultValue;
    }
    const result = {};
    for (const [key, value] of Object.entries(map)) {
      if (value === true) {
        result[key] = true;
      }
    }
    return result;
  }
};
var InlineEditorSuggest = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      mode: "subwordSmart",
      showToolbar: "onHover",
      suppressSuggestions: false,
      keepOnBlur: false,
      fontFamily: "default",
      syntaxHighlightingEnabled: false,
      edits: {
        experimental: {
          enabled: true,
          useMixedLinesDiff: "never",
          useInterleavedLinesDiff: "never",
          onlyShowWhenCloseToCursor: true
        }
      }
    };
    super(64, "inlineSuggest", defaults, {
      "editor.inlineSuggest.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(433, null)
      },
      "editor.inlineSuggest.showToolbar": {
        type: "string",
        default: defaults.showToolbar,
        enum: ["always", "onHover", "never"],
        enumDescriptions: [
          localize(434, null),
          localize(435, null),
          localize(436, null)
        ],
        description: localize(437, null)
      },
      "editor.inlineSuggest.syntaxHighlightingEnabled": {
        type: "boolean",
        default: defaults.syntaxHighlightingEnabled,
        description: localize(438, null)
      },
      "editor.inlineSuggest.suppressSuggestions": {
        type: "boolean",
        default: defaults.suppressSuggestions,
        description: localize(439, null)
      },
      "editor.inlineSuggest.fontFamily": {
        type: "string",
        default: defaults.fontFamily,
        description: localize(440, null)
      },
      "editor.inlineSuggest.edits.experimental.enabled": {
        type: "boolean",
        default: defaults.edits.experimental.enabled,
        description: localize(441, null)
      },
      "editor.inlineSuggest.edits.experimental.useMixedLinesDiff": {
        type: "string",
        default: defaults.edits.experimental.useMixedLinesDiff,
        description: localize(442, null),
        enum: ["never", "whenPossible"]
      },
      "editor.inlineSuggest.edits.experimental.useInterleavedLinesDiff": {
        type: "string",
        default: defaults.edits.experimental.useInterleavedLinesDiff,
        description: localize(443, null),
        enum: ["never", "always", "afterJump"]
      },
      "editor.inlineSuggest.edits.experimental.onlyShowWhenCloseToCursor": {
        type: "boolean",
        default: defaults.edits.experimental.onlyShowWhenCloseToCursor,
        description: localize(444, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      mode: stringSet(input.mode, this.defaultValue.mode, ["prefix", "subword", "subwordSmart"]),
      showToolbar: stringSet(input.showToolbar, this.defaultValue.showToolbar, ["always", "onHover", "never"]),
      suppressSuggestions: boolean(input.suppressSuggestions, this.defaultValue.suppressSuggestions),
      keepOnBlur: boolean(input.keepOnBlur, this.defaultValue.keepOnBlur),
      fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily),
      syntaxHighlightingEnabled: boolean(input.syntaxHighlightingEnabled, this.defaultValue.syntaxHighlightingEnabled),
      edits: {
        experimental: {
          enabled: boolean(input.edits?.experimental?.enabled, this.defaultValue.edits.experimental.enabled),
          useMixedLinesDiff: stringSet(input.edits?.experimental?.useMixedLinesDiff, this.defaultValue.edits.experimental.useMixedLinesDiff, ["never", "whenPossible", "afterJumpWhenPossible"]),
          useInterleavedLinesDiff: stringSet(input.edits?.experimental?.useInterleavedLinesDiff, this.defaultValue.edits.experimental.useInterleavedLinesDiff, ["never", "always", "afterJump"]),
          onlyShowWhenCloseToCursor: boolean(input.edits?.experimental?.onlyShowWhenCloseToCursor, this.defaultValue.edits.experimental.onlyShowWhenCloseToCursor)
        }
      }
    };
  }
};
var BracketPairColorization = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: $HD.bracketPairColorizationOptions.enabled,
      independentColorPoolPerBracketType: $HD.bracketPairColorizationOptions.independentColorPoolPerBracketType
    };
    super(15, "bracketPairColorization", defaults, {
      "editor.bracketPairColorization.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize(445, null, "`#workbench.colorCustomizations#`")
      },
      "editor.bracketPairColorization.independentColorPoolPerBracketType": {
        type: "boolean",
        default: defaults.independentColorPoolPerBracketType,
        description: localize(446, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      independentColorPoolPerBracketType: boolean(input.independentColorPoolPerBracketType, this.defaultValue.independentColorPoolPerBracketType)
    };
  }
};
var GuideOptions = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      bracketPairs: false,
      bracketPairsHorizontal: "active",
      highlightActiveBracketPair: true,
      indentation: true,
      highlightActiveIndentation: true
    };
    super(16, "guides", defaults, {
      "editor.guides.bracketPairs": {
        type: ["boolean", "string"],
        enum: [true, "active", false],
        enumDescriptions: [
          localize(447, null),
          localize(448, null),
          localize(449, null)
        ],
        default: defaults.bracketPairs,
        description: localize(450, null)
      },
      "editor.guides.bracketPairsHorizontal": {
        type: ["boolean", "string"],
        enum: [true, "active", false],
        enumDescriptions: [
          localize(451, null),
          localize(452, null),
          localize(453, null)
        ],
        default: defaults.bracketPairsHorizontal,
        description: localize(454, null)
      },
      "editor.guides.highlightActiveBracketPair": {
        type: "boolean",
        default: defaults.highlightActiveBracketPair,
        description: localize(455, null)
      },
      "editor.guides.indentation": {
        type: "boolean",
        default: defaults.indentation,
        description: localize(456, null)
      },
      "editor.guides.highlightActiveIndentation": {
        type: ["boolean", "string"],
        enum: [true, "always", false],
        enumDescriptions: [
          localize(457, null),
          localize(458, null),
          localize(459, null)
        ],
        default: defaults.highlightActiveIndentation,
        description: localize(460, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      bracketPairs: primitiveSet(input.bracketPairs, this.defaultValue.bracketPairs, [true, false, "active"]),
      bracketPairsHorizontal: primitiveSet(input.bracketPairsHorizontal, this.defaultValue.bracketPairsHorizontal, [true, false, "active"]),
      highlightActiveBracketPair: boolean(input.highlightActiveBracketPair, this.defaultValue.highlightActiveBracketPair),
      indentation: boolean(input.indentation, this.defaultValue.indentation),
      highlightActiveIndentation: primitiveSet(input.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];
}
var EditorSuggest = class 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(123, "suggest", defaults, {
      "editor.suggest.insertMode": {
        type: "string",
        enum: ["insert", "replace"],
        enumDescriptions: [
          localize(461, null),
          localize(462, null)
        ],
        default: defaults.insertMode,
        description: localize(463, null)
      },
      "editor.suggest.filterGraceful": {
        type: "boolean",
        default: defaults.filterGraceful,
        description: localize(464, null)
      },
      "editor.suggest.localityBonus": {
        type: "boolean",
        default: defaults.localityBonus,
        description: localize(465, null)
      },
      "editor.suggest.shareSuggestSelections": {
        type: "boolean",
        default: defaults.shareSuggestSelections,
        markdownDescription: localize(466, null)
      },
      "editor.suggest.selectionMode": {
        type: "string",
        enum: ["always", "never", "whenTriggerCharacter", "whenQuickSuggestion"],
        enumDescriptions: [
          localize(467, null),
          localize(468, null),
          localize(469, null),
          localize(470, null)
        ],
        default: defaults.selectionMode,
        markdownDescription: localize(471, null, "`#editor.quickSuggestions#`", "`#editor.suggestOnTriggerCharacters#`")
      },
      "editor.suggest.snippetsPreventQuickSuggestions": {
        type: "boolean",
        default: defaults.snippetsPreventQuickSuggestions,
        description: localize(472, null)
      },
      "editor.suggest.showIcons": {
        type: "boolean",
        default: defaults.showIcons,
        description: localize(473, null)
      },
      "editor.suggest.showStatusBar": {
        type: "boolean",
        default: defaults.showStatusBar,
        description: localize(474, null)
      },
      "editor.suggest.preview": {
        type: "boolean",
        default: defaults.preview,
        description: localize(475, null)
      },
      "editor.suggest.showInlineDetails": {
        type: "boolean",
        default: defaults.showInlineDetails,
        description: localize(476, null)
      },
      "editor.suggest.maxVisibleSuggestions": {
        type: "number",
        deprecationMessage: localize(477, null)
      },
      "editor.suggest.filteredTypes": {
        type: "object",
        deprecationMessage: localize(478, null)
      },
      "editor.suggest.showMethods": {
        type: "boolean",
        default: true,
        markdownDescription: localize(479, null)
      },
      "editor.suggest.showFunctions": {
        type: "boolean",
        default: true,
        markdownDescription: localize(480, null)
      },
      "editor.suggest.showConstructors": {
        type: "boolean",
        default: true,
        markdownDescription: localize(481, null)
      },
      "editor.suggest.showDeprecated": {
        type: "boolean",
        default: true,
        markdownDescription: localize(482, null)
      },
      "editor.suggest.matchOnWordStartOnly": {
        type: "boolean",
        default: true,
        markdownDescription: localize(483, null)
      },
      "editor.suggest.showFields": {
        type: "boolean",
        default: true,
        markdownDescription: localize(484, null)
      },
      "editor.suggest.showVariables": {
        type: "boolean",
        default: true,
        markdownDescription: localize(485, null)
      },
      "editor.suggest.showClasses": {
        type: "boolean",
        default: true,
        markdownDescription: localize(486, null)
      },
      "editor.suggest.showStructs": {
        type: "boolean",
        default: true,
        markdownDescription: localize(487, null)
      },
      "editor.suggest.showInterfaces": {
        type: "boolean",
        default: true,
        markdownDescription: localize(488, null)
      },
      "editor.suggest.showModules": {
        type: "boolean",
        default: true,
        markdownDescription: localize(489, null)
      },
      "editor.suggest.showProperties": {
        type: "boolean",
        default: true,
        markdownDescription: localize(490, null)
      },
      "editor.suggest.showEvents": {
        type: "boolean",
        default: true,
        markdownDescription: localize(491, null)
      },
      "editor.suggest.showOperators": {
        type: "boolean",
        default: true,
        markdownDescription: localize(492, null)
      },
      "editor.suggest.showUnits": {
        type: "boolean",
        default: true,
        markdownDescription: localize(493, null)
      },
      "editor.suggest.showValues": {
        type: "boolean",
        default: true,
        markdownDescription: localize(494, null)
      },
      "editor.suggest.showConstants": {
        type: "boolean",
        default: true,
        markdownDescription: localize(495, null)
      },
      "editor.suggest.showEnums": {
        type: "boolean",
        default: true,
        markdownDescription: localize(496, null)
      },
      "editor.suggest.showEnumMembers": {
        type: "boolean",
        default: true,
        markdownDescription: localize(497, null)
      },
      "editor.suggest.showKeywords": {
        type: "boolean",
        default: true,
        markdownDescription: localize(498, null)
      },
      "editor.suggest.showWords": {
        type: "boolean",
        default: true,
        markdownDescription: localize(499, null)
      },
      "editor.suggest.showColors": {
        type: "boolean",
        default: true,
        markdownDescription: localize(500, null)
      },
      "editor.suggest.showFiles": {
        type: "boolean",
        default: true,
        markdownDescription: localize(501, null)
      },
      "editor.suggest.showReferences": {
        type: "boolean",
        default: true,
        markdownDescription: localize(502, null)
      },
      "editor.suggest.showCustomcolors": {
        type: "boolean",
        default: true,
        markdownDescription: localize(503, null)
      },
      "editor.suggest.showFolders": {
        type: "boolean",
        default: true,
        markdownDescription: localize(504, null)
      },
      "editor.suggest.showTypeParameters": {
        type: "boolean",
        default: true,
        markdownDescription: localize(505, null)
      },
      "editor.suggest.showSnippets": {
        type: "boolean",
        default: true,
        markdownDescription: localize(506, null)
      },
      "editor.suggest.showUsers": {
        type: "boolean",
        default: true,
        markdownDescription: localize(507, null)
      },
      "editor.suggest.showIssues": {
        type: "boolean",
        default: true,
        markdownDescription: localize(508, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      insertMode: stringSet(input.insertMode, this.defaultValue.insertMode, ["insert", "replace"]),
      filterGraceful: boolean(input.filterGraceful, this.defaultValue.filterGraceful),
      snippetsPreventQuickSuggestions: boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful),
      localityBonus: boolean(input.localityBonus, this.defaultValue.localityBonus),
      shareSuggestSelections: boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections),
      selectionMode: stringSet(input.selectionMode, this.defaultValue.selectionMode, ["always", "never", "whenQuickSuggestion", "whenTriggerCharacter"]),
      showIcons: boolean(input.showIcons, this.defaultValue.showIcons),
      showStatusBar: boolean(input.showStatusBar, this.defaultValue.showStatusBar),
      preview: boolean(input.preview, this.defaultValue.preview),
      previewMode: stringSet(input.previewMode, this.defaultValue.previewMode, ["prefix", "subword", "subwordSmart"]),
      showInlineDetails: boolean(input.showInlineDetails, this.defaultValue.showInlineDetails),
      showMethods: boolean(input.showMethods, this.defaultValue.showMethods),
      showFunctions: boolean(input.showFunctions, this.defaultValue.showFunctions),
      showConstructors: boolean(input.showConstructors, this.defaultValue.showConstructors),
      showDeprecated: boolean(input.showDeprecated, this.defaultValue.showDeprecated),
      matchOnWordStartOnly: boolean(input.matchOnWordStartOnly, this.defaultValue.matchOnWordStartOnly),
      showFields: boolean(input.showFields, this.defaultValue.showFields),
      showVariables: boolean(input.showVariables, this.defaultValue.showVariables),
      showClasses: boolean(input.showClasses, this.defaultValue.showClasses),
      showStructs: boolean(input.showStructs, this.defaultValue.showStructs),
      showInterfaces: boolean(input.showInterfaces, this.defaultValue.showInterfaces),
      showModules: boolean(input.showModules, this.defaultValue.showModules),
      showProperties: boolean(input.showProperties, this.defaultValue.showProperties),
      showEvents: boolean(input.showEvents, this.defaultValue.showEvents),
      showOperators: boolean(input.showOperators, this.defaultValue.showOperators),
      showUnits: boolean(input.showUnits, this.defaultValue.showUnits),
      showValues: boolean(input.showValues, this.defaultValue.showValues),
      showConstants: boolean(input.showConstants, this.defaultValue.showConstants),
      showEnums: boolean(input.showEnums, this.defaultValue.showEnums),
      showEnumMembers: boolean(input.showEnumMembers, this.defaultValue.showEnumMembers),
      showKeywords: boolean(input.showKeywords, this.defaultValue.showKeywords),
      showWords: boolean(input.showWords, this.defaultValue.showWords),
      showColors: boolean(input.showColors, this.defaultValue.showColors),
      showFiles: boolean(input.showFiles, this.defaultValue.showFiles),
      showReferences: boolean(input.showReferences, this.defaultValue.showReferences),
      showFolders: boolean(input.showFolders, this.defaultValue.showFolders),
      showTypeParameters: boolean(input.showTypeParameters, this.defaultValue.showTypeParameters),
      showSnippets: boolean(input.showSnippets, this.defaultValue.showSnippets),
      showUsers: boolean(input.showUsers, this.defaultValue.showUsers),
      showIssues: boolean(input.showIssues, this.defaultValue.showIssues)
    };
  }
};
var SmartSelect = class extends BaseEditorOption {
  constructor() {
    super(118, "smartSelect", {
      selectLeadingAndTrailingWhitespace: true,
      selectSubwords: true
    }, {
      "editor.smartSelect.selectLeadingAndTrailingWhitespace": {
        description: localize(509, null),
        default: true,
        type: "boolean"
      },
      "editor.smartSelect.selectSubwords": {
        description: localize(510, null),
        default: true,
        type: "boolean"
      }
    });
  }
  validate(input) {
    if (!input || typeof input !== "object") {
      return this.defaultValue;
    }
    return {
      selectLeadingAndTrailingWhitespace: boolean(input.selectLeadingAndTrailingWhitespace, this.defaultValue.selectLeadingAndTrailingWhitespace),
      selectSubwords: boolean(input.selectSubwords, this.defaultValue.selectSubwords)
    };
  }
};
var WordSegmenterLocales = class extends BaseEditorOption {
  constructor() {
    const defaults = [];
    super(135, "wordSegmenterLocales", defaults, {
      anyOf: [
        {
          description: localize(511, null),
          type: "string"
        },
        {
          description: localize(512, null),
          type: "array",
          items: {
            type: "string"
          }
        }
      ]
    });
  }
  validate(input) {
    if (typeof input === "string") {
      input = [input];
    }
    if (Array.isArray(input)) {
      const validLocales = [];
      for (const locale of input) {
        if (typeof locale === "string") {
          try {
            if (Intl.Segmenter.supportedLocalesOf(locale).length > 0) {
              validLocales.push(locale);
            }
          } catch {
          }
        }
      }
      return validLocales;
    }
    return this.defaultValue;
  }
};
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 = {}));
var WrappingIndentOption = class extends BaseEditorOption {
  constructor() {
    super(143, "wrappingIndent", 1, {
      "editor.wrappingIndent": {
        type: "string",
        enum: ["none", "same", "indent", "deepIndent"],
        enumDescriptions: [
          localize(513, null),
          localize(514, null),
          localize(515, null),
          localize(516, null)
        ],
        description: localize(517, null),
        default: "same"
      }
    });
  }
  validate(input) {
    switch (input) {
      case "none":
        return 0;
      case "same":
        return 1;
      case "indent":
        return 2;
      case "deepIndent":
        return 3;
    }
    return 1;
  }
  compute(env2, options2, value) {
    const accessibilitySupport = options2.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    if (accessibilitySupport === 2) {
      return 0;
    }
    return value;
  }
};
var EditorWrappingInfoComputer = class extends ComputedEditorOption {
  constructor() {
    super(
      152
      /* EditorOption.wrappingInfo */
    );
  }
  compute(env2, options2, _) {
    const layoutInfo = options2.get(
      151
      /* EditorOption.layoutInfo */
    );
    return {
      isDominatedByLongLines: env2.isDominatedByLongLines,
      isWordWrapMinified: layoutInfo.isWordWrapMinified,
      isViewportWrapping: layoutInfo.isViewportWrapping,
      wrappingColumn: layoutInfo.wrappingColumn
    };
  }
};
var EditorDropIntoEditor = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true, showDropSelector: "afterDrop" };
    super(36, "dropIntoEditor", defaults, {
      "editor.dropIntoEditor.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize(518, null)
      },
      "editor.dropIntoEditor.showDropSelector": {
        type: "string",
        markdownDescription: localize(519, null),
        enum: [
          "afterDrop",
          "never"
        ],
        enumDescriptions: [
          localize(520, null),
          localize(521, null)
        ],
        default: "afterDrop"
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      showDropSelector: stringSet(input.showDropSelector, this.defaultValue.showDropSelector, ["afterDrop", "never"])
    };
  }
};
var EditorPasteAs = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true, showPasteSelector: "afterPaste" };
    super(89, "pasteAs", defaults, {
      "editor.pasteAs.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize(522, null)
      },
      "editor.pasteAs.showPasteSelector": {
        type: "string",
        markdownDescription: localize(523, null),
        enum: [
          "afterPaste",
          "never"
        ],
        enumDescriptions: [
          localize(524, null),
          localize(525, null)
        ],
        default: "afterPaste"
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      showPasteSelector: stringSet(input.showPasteSelector, this.defaultValue.showPasteSelector, ["afterPaste", "never"])
    };
  }
};
var DEFAULT_WINDOWS_FONT_FAMILY = "Consolas, 'Courier New', monospace";
var DEFAULT_MAC_FONT_FAMILY = "Menlo, Monaco, 'Courier New', monospace";
var DEFAULT_LINUX_FONT_FAMILY = "'Droid Sans Mono', 'monospace', monospace";
var EDITOR_FONT_DEFAULTS = {
  fontFamily: $m ? DEFAULT_MAC_FONT_FAMILY : $n ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY,
  fontWeight: "normal",
  fontSize: $m ? 12 : 14,
  lineHeight: 0,
  letterSpacing: 0
};
var editorOptionsRegistry = [];
function register(option) {
  editorOptionsRegistry[option.id] = option;
  return option;
}
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["autoClosingComments"] = 7] = "autoClosingComments";
  EditorOption2[EditorOption2["screenReaderAnnounceInlineSuggestion"] = 8] = "screenReaderAnnounceInlineSuggestion";
  EditorOption2[EditorOption2["autoClosingDelete"] = 9] = "autoClosingDelete";
  EditorOption2[EditorOption2["autoClosingOvertype"] = 10] = "autoClosingOvertype";
  EditorOption2[EditorOption2["autoClosingQuotes"] = 11] = "autoClosingQuotes";
  EditorOption2[EditorOption2["autoIndent"] = 12] = "autoIndent";
  EditorOption2[EditorOption2["automaticLayout"] = 13] = "automaticLayout";
  EditorOption2[EditorOption2["autoSurround"] = 14] = "autoSurround";
  EditorOption2[EditorOption2["bracketPairColorization"] = 15] = "bracketPairColorization";
  EditorOption2[EditorOption2["guides"] = 16] = "guides";
  EditorOption2[EditorOption2["codeLens"] = 17] = "codeLens";
  EditorOption2[EditorOption2["codeLensFontFamily"] = 18] = "codeLensFontFamily";
  EditorOption2[EditorOption2["codeLensFontSize"] = 19] = "codeLensFontSize";
  EditorOption2[EditorOption2["colorDecorators"] = 20] = "colorDecorators";
  EditorOption2[EditorOption2["colorDecoratorsLimit"] = 21] = "colorDecoratorsLimit";
  EditorOption2[EditorOption2["columnSelection"] = 22] = "columnSelection";
  EditorOption2[EditorOption2["comments"] = 23] = "comments";
  EditorOption2[EditorOption2["contextmenu"] = 24] = "contextmenu";
  EditorOption2[EditorOption2["copyWithSyntaxHighlighting"] = 25] = "copyWithSyntaxHighlighting";
  EditorOption2[EditorOption2["cursorBlinking"] = 26] = "cursorBlinking";
  EditorOption2[EditorOption2["cursorSmoothCaretAnimation"] = 27] = "cursorSmoothCaretAnimation";
  EditorOption2[EditorOption2["cursorStyle"] = 28] = "cursorStyle";
  EditorOption2[EditorOption2["cursorSurroundingLines"] = 29] = "cursorSurroundingLines";
  EditorOption2[EditorOption2["cursorSurroundingLinesStyle"] = 30] = "cursorSurroundingLinesStyle";
  EditorOption2[EditorOption2["cursorWidth"] = 31] = "cursorWidth";
  EditorOption2[EditorOption2["disableLayerHinting"] = 32] = "disableLayerHinting";
  EditorOption2[EditorOption2["disableMonospaceOptimizations"] = 33] = "disableMonospaceOptimizations";
  EditorOption2[EditorOption2["domReadOnly"] = 34] = "domReadOnly";
  EditorOption2[EditorOption2["dragAndDrop"] = 35] = "dragAndDrop";
  EditorOption2[EditorOption2["dropIntoEditor"] = 36] = "dropIntoEditor";
  EditorOption2[EditorOption2["experimentalEditContextEnabled"] = 37] = "experimentalEditContextEnabled";
  EditorOption2[EditorOption2["emptySelectionClipboard"] = 38] = "emptySelectionClipboard";
  EditorOption2[EditorOption2["experimentalGpuAcceleration"] = 39] = "experimentalGpuAcceleration";
  EditorOption2[EditorOption2["experimentalWhitespaceRendering"] = 40] = "experimentalWhitespaceRendering";
  EditorOption2[EditorOption2["extraEditorClassName"] = 41] = "extraEditorClassName";
  EditorOption2[EditorOption2["fastScrollSensitivity"] = 42] = "fastScrollSensitivity";
  EditorOption2[EditorOption2["find"] = 43] = "find";
  EditorOption2[EditorOption2["fixedOverflowWidgets"] = 44] = "fixedOverflowWidgets";
  EditorOption2[EditorOption2["folding"] = 45] = "folding";
  EditorOption2[EditorOption2["foldingStrategy"] = 46] = "foldingStrategy";
  EditorOption2[EditorOption2["foldingHighlight"] = 47] = "foldingHighlight";
  EditorOption2[EditorOption2["foldingImportsByDefault"] = 48] = "foldingImportsByDefault";
  EditorOption2[EditorOption2["foldingMaximumRegions"] = 49] = "foldingMaximumRegions";
  EditorOption2[EditorOption2["unfoldOnClickAfterEndOfLine"] = 50] = "unfoldOnClickAfterEndOfLine";
  EditorOption2[EditorOption2["fontFamily"] = 51] = "fontFamily";
  EditorOption2[EditorOption2["fontInfo"] = 52] = "fontInfo";
  EditorOption2[EditorOption2["fontLigatures"] = 53] = "fontLigatures";
  EditorOption2[EditorOption2["fontSize"] = 54] = "fontSize";
  EditorOption2[EditorOption2["fontWeight"] = 55] = "fontWeight";
  EditorOption2[EditorOption2["fontVariations"] = 56] = "fontVariations";
  EditorOption2[EditorOption2["formatOnPaste"] = 57] = "formatOnPaste";
  EditorOption2[EditorOption2["formatOnType"] = 58] = "formatOnType";
  EditorOption2[EditorOption2["glyphMargin"] = 59] = "glyphMargin";
  EditorOption2[EditorOption2["gotoLocation"] = 60] = "gotoLocation";
  EditorOption2[EditorOption2["hideCursorInOverviewRuler"] = 61] = "hideCursorInOverviewRuler";
  EditorOption2[EditorOption2["hover"] = 62] = "hover";
  EditorOption2[EditorOption2["inDiffEditor"] = 63] = "inDiffEditor";
  EditorOption2[EditorOption2["inlineSuggest"] = 64] = "inlineSuggest";
  EditorOption2[EditorOption2["letterSpacing"] = 65] = "letterSpacing";
  EditorOption2[EditorOption2["lightbulb"] = 66] = "lightbulb";
  EditorOption2[EditorOption2["lineDecorationsWidth"] = 67] = "lineDecorationsWidth";
  EditorOption2[EditorOption2["lineHeight"] = 68] = "lineHeight";
  EditorOption2[EditorOption2["lineNumbers"] = 69] = "lineNumbers";
  EditorOption2[EditorOption2["lineNumbersMinChars"] = 70] = "lineNumbersMinChars";
  EditorOption2[EditorOption2["linkedEditing"] = 71] = "linkedEditing";
  EditorOption2[EditorOption2["links"] = 72] = "links";
  EditorOption2[EditorOption2["matchBrackets"] = 73] = "matchBrackets";
  EditorOption2[EditorOption2["minimap"] = 74] = "minimap";
  EditorOption2[EditorOption2["mouseStyle"] = 75] = "mouseStyle";
  EditorOption2[EditorOption2["mouseWheelScrollSensitivity"] = 76] = "mouseWheelScrollSensitivity";
  EditorOption2[EditorOption2["mouseWheelZoom"] = 77] = "mouseWheelZoom";
  EditorOption2[EditorOption2["multiCursorMergeOverlapping"] = 78] = "multiCursorMergeOverlapping";
  EditorOption2[EditorOption2["multiCursorModifier"] = 79] = "multiCursorModifier";
  EditorOption2[EditorOption2["multiCursorPaste"] = 80] = "multiCursorPaste";
  EditorOption2[EditorOption2["multiCursorLimit"] = 81] = "multiCursorLimit";
  EditorOption2[EditorOption2["occurrencesHighlight"] = 82] = "occurrencesHighlight";
  EditorOption2[EditorOption2["occurrencesHighlightDelay"] = 83] = "occurrencesHighlightDelay";
  EditorOption2[EditorOption2["overtypeCursorStyle"] = 84] = "overtypeCursorStyle";
  EditorOption2[EditorOption2["overtypeOnPaste"] = 85] = "overtypeOnPaste";
  EditorOption2[EditorOption2["overviewRulerBorder"] = 86] = "overviewRulerBorder";
  EditorOption2[EditorOption2["overviewRulerLanes"] = 87] = "overviewRulerLanes";
  EditorOption2[EditorOption2["padding"] = 88] = "padding";
  EditorOption2[EditorOption2["pasteAs"] = 89] = "pasteAs";
  EditorOption2[EditorOption2["parameterHints"] = 90] = "parameterHints";
  EditorOption2[EditorOption2["peekWidgetDefaultFocus"] = 91] = "peekWidgetDefaultFocus";
  EditorOption2[EditorOption2["placeholder"] = 92] = "placeholder";
  EditorOption2[EditorOption2["definitionLinkOpensInPeek"] = 93] = "definitionLinkOpensInPeek";
  EditorOption2[EditorOption2["quickSuggestions"] = 94] = "quickSuggestions";
  EditorOption2[EditorOption2["quickSuggestionsDelay"] = 95] = "quickSuggestionsDelay";
  EditorOption2[EditorOption2["readOnly"] = 96] = "readOnly";
  EditorOption2[EditorOption2["readOnlyMessage"] = 97] = "readOnlyMessage";
  EditorOption2[EditorOption2["renameOnType"] = 98] = "renameOnType";
  EditorOption2[EditorOption2["renderControlCharacters"] = 99] = "renderControlCharacters";
  EditorOption2[EditorOption2["renderFinalNewline"] = 100] = "renderFinalNewline";
  EditorOption2[EditorOption2["renderLineHighlight"] = 101] = "renderLineHighlight";
  EditorOption2[EditorOption2["renderLineHighlightOnlyWhenFocus"] = 102] = "renderLineHighlightOnlyWhenFocus";
  EditorOption2[EditorOption2["renderValidationDecorations"] = 103] = "renderValidationDecorations";
  EditorOption2[EditorOption2["renderWhitespace"] = 104] = "renderWhitespace";
  EditorOption2[EditorOption2["revealHorizontalRightPadding"] = 105] = "revealHorizontalRightPadding";
  EditorOption2[EditorOption2["roundedSelection"] = 106] = "roundedSelection";
  EditorOption2[EditorOption2["rulers"] = 107] = "rulers";
  EditorOption2[EditorOption2["scrollbar"] = 108] = "scrollbar";
  EditorOption2[EditorOption2["scrollBeyondLastColumn"] = 109] = "scrollBeyondLastColumn";
  EditorOption2[EditorOption2["scrollBeyondLastLine"] = 110] = "scrollBeyondLastLine";
  EditorOption2[EditorOption2["scrollPredominantAxis"] = 111] = "scrollPredominantAxis";
  EditorOption2[EditorOption2["selectionClipboard"] = 112] = "selectionClipboard";
  EditorOption2[EditorOption2["selectionHighlight"] = 113] = "selectionHighlight";
  EditorOption2[EditorOption2["selectOnLineNumbers"] = 114] = "selectOnLineNumbers";
  EditorOption2[EditorOption2["showFoldingControls"] = 115] = "showFoldingControls";
  EditorOption2[EditorOption2["showUnused"] = 116] = "showUnused";
  EditorOption2[EditorOption2["snippetSuggestions"] = 117] = "snippetSuggestions";
  EditorOption2[EditorOption2["smartSelect"] = 118] = "smartSelect";
  EditorOption2[EditorOption2["smoothScrolling"] = 119] = "smoothScrolling";
  EditorOption2[EditorOption2["stickyScroll"] = 120] = "stickyScroll";
  EditorOption2[EditorOption2["stickyTabStops"] = 121] = "stickyTabStops";
  EditorOption2[EditorOption2["stopRenderingLineAfter"] = 122] = "stopRenderingLineAfter";
  EditorOption2[EditorOption2["suggest"] = 123] = "suggest";
  EditorOption2[EditorOption2["suggestFontSize"] = 124] = "suggestFontSize";
  EditorOption2[EditorOption2["suggestLineHeight"] = 125] = "suggestLineHeight";
  EditorOption2[EditorOption2["suggestOnTriggerCharacters"] = 126] = "suggestOnTriggerCharacters";
  EditorOption2[EditorOption2["suggestSelection"] = 127] = "suggestSelection";
  EditorOption2[EditorOption2["tabCompletion"] = 128] = "tabCompletion";
  EditorOption2[EditorOption2["tabIndex"] = 129] = "tabIndex";
  EditorOption2[EditorOption2["unicodeHighlighting"] = 130] = "unicodeHighlighting";
  EditorOption2[EditorOption2["unusualLineTerminators"] = 131] = "unusualLineTerminators";
  EditorOption2[EditorOption2["useShadowDOM"] = 132] = "useShadowDOM";
  EditorOption2[EditorOption2["useTabStops"] = 133] = "useTabStops";
  EditorOption2[EditorOption2["wordBreak"] = 134] = "wordBreak";
  EditorOption2[EditorOption2["wordSegmenterLocales"] = 135] = "wordSegmenterLocales";
  EditorOption2[EditorOption2["wordSeparators"] = 136] = "wordSeparators";
  EditorOption2[EditorOption2["wordWrap"] = 137] = "wordWrap";
  EditorOption2[EditorOption2["wordWrapBreakAfterCharacters"] = 138] = "wordWrapBreakAfterCharacters";
  EditorOption2[EditorOption2["wordWrapBreakBeforeCharacters"] = 139] = "wordWrapBreakBeforeCharacters";
  EditorOption2[EditorOption2["wordWrapColumn"] = 140] = "wordWrapColumn";
  EditorOption2[EditorOption2["wordWrapOverride1"] = 141] = "wordWrapOverride1";
  EditorOption2[EditorOption2["wordWrapOverride2"] = 142] = "wordWrapOverride2";
  EditorOption2[EditorOption2["wrappingIndent"] = 143] = "wrappingIndent";
  EditorOption2[EditorOption2["wrappingStrategy"] = 144] = "wrappingStrategy";
  EditorOption2[EditorOption2["showDeprecated"] = 145] = "showDeprecated";
  EditorOption2[EditorOption2["inlayHints"] = 146] = "inlayHints";
  EditorOption2[EditorOption2["effectiveCursorStyle"] = 147] = "effectiveCursorStyle";
  EditorOption2[EditorOption2["editorClassName"] = 148] = "editorClassName";
  EditorOption2[EditorOption2["pixelRatio"] = 149] = "pixelRatio";
  EditorOption2[EditorOption2["tabFocusMode"] = 150] = "tabFocusMode";
  EditorOption2[EditorOption2["layoutInfo"] = 151] = "layoutInfo";
  EditorOption2[EditorOption2["wrappingInfo"] = 152] = "wrappingInfo";
  EditorOption2[EditorOption2["defaultColorDecorators"] = 153] = "defaultColorDecorators";
  EditorOption2[EditorOption2["colorDecoratorsActivatedOn"] = 154] = "colorDecoratorsActivatedOn";
  EditorOption2[EditorOption2["inlineCompletionsAccessibilityVerbose"] = 155] = "inlineCompletionsAccessibilityVerbose";
})(EditorOption || (EditorOption = {}));
var EditorOptions = {
  acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0, "acceptSuggestionOnCommitCharacter", true, { markdownDescription: localize(526, null) })),
  acceptSuggestionOnEnter: register(new EditorStringEnumOption(1, "acceptSuggestionOnEnter", "on", ["on", "smart", "off"], {
    markdownEnumDescriptions: [
      "",
      localize(527, null),
      ""
    ],
    markdownDescription: localize(528, null)
  })),
  accessibilitySupport: register(new EditorAccessibilitySupport()),
  accessibilityPageSize: register(new EditorIntOption(3, "accessibilityPageSize", 10, 1, 1073741824, {
    description: localize(529, null),
    tags: ["accessibility"]
  })),
  ariaLabel: register(new EditorStringOption(4, "ariaLabel", localize(530, null))),
  ariaRequired: register(new EditorBooleanOption(5, "ariaRequired", false, void 0)),
  screenReaderAnnounceInlineSuggestion: register(new EditorBooleanOption(8, "screenReaderAnnounceInlineSuggestion", true, {
    description: localize(531, null),
    tags: ["accessibility"]
  })),
  autoClosingBrackets: register(new EditorStringEnumOption(6, "autoClosingBrackets", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize(532, null),
      localize(533, null),
      ""
    ],
    description: localize(534, null)
  })),
  autoClosingComments: register(new EditorStringEnumOption(7, "autoClosingComments", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize(535, null),
      localize(536, null),
      ""
    ],
    description: localize(537, null)
  })),
  autoClosingDelete: register(new EditorStringEnumOption(9, "autoClosingDelete", "auto", ["always", "auto", "never"], {
    enumDescriptions: [
      "",
      localize(538, null),
      ""
    ],
    description: localize(539, null)
  })),
  autoClosingOvertype: register(new EditorStringEnumOption(10, "autoClosingOvertype", "auto", ["always", "auto", "never"], {
    enumDescriptions: [
      "",
      localize(540, null),
      ""
    ],
    description: localize(541, null)
  })),
  autoClosingQuotes: register(new EditorStringEnumOption(11, "autoClosingQuotes", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize(542, null),
      localize(543, null),
      ""
    ],
    description: localize(544, null)
  })),
  autoIndent: register(new EditorEnumOption(12, "autoIndent", 4, "full", ["none", "keep", "brackets", "advanced", "full"], _autoIndentFromString, {
    enumDescriptions: [
      localize(545, null),
      localize(546, null),
      localize(547, null),
      localize(548, null),
      localize(549, null)
    ],
    description: localize(550, null)
  })),
  automaticLayout: register(new EditorBooleanOption(13, "automaticLayout", false)),
  autoSurround: register(new EditorStringEnumOption(14, "autoSurround", "languageDefined", ["languageDefined", "quotes", "brackets", "never"], {
    enumDescriptions: [
      localize(551, null),
      localize(552, null),
      localize(553, null),
      ""
    ],
    description: localize(554, null)
  })),
  bracketPairColorization: register(new BracketPairColorization()),
  bracketPairGuides: register(new GuideOptions()),
  stickyTabStops: register(new EditorBooleanOption(121, "stickyTabStops", false, { description: localize(555, null) })),
  codeLens: register(new EditorBooleanOption(17, "codeLens", true, { description: localize(556, null) })),
  codeLensFontFamily: register(new EditorStringOption(18, "codeLensFontFamily", "", { description: localize(557, null) })),
  codeLensFontSize: register(new EditorIntOption(19, "codeLensFontSize", 0, 0, 100, {
    type: "number",
    default: 0,
    minimum: 0,
    maximum: 100,
    markdownDescription: localize(558, null)
  })),
  colorDecorators: register(new EditorBooleanOption(20, "colorDecorators", true, { description: localize(559, null) })),
  colorDecoratorActivatedOn: register(new EditorStringEnumOption(154, "colorDecoratorsActivatedOn", "clickAndHover", ["clickAndHover", "hover", "click"], {
    enumDescriptions: [
      localize(560, null),
      localize(561, null),
      localize(562, null)
    ],
    description: localize(563, null)
  })),
  colorDecoratorsLimit: register(new EditorIntOption(21, "colorDecoratorsLimit", 500, 1, 1e6, {
    markdownDescription: localize(564, null)
  })),
  columnSelection: register(new EditorBooleanOption(22, "columnSelection", false, { description: localize(565, null) })),
  comments: register(new EditorComments()),
  contextmenu: register(new EditorBooleanOption(24, "contextmenu", true)),
  copyWithSyntaxHighlighting: register(new EditorBooleanOption(25, "copyWithSyntaxHighlighting", true, { description: localize(566, null) })),
  cursorBlinking: register(new EditorEnumOption(26, "cursorBlinking", 1, "blink", ["blink", "smooth", "phase", "expand", "solid"], cursorBlinkingStyleFromString, { description: localize(567, null) })),
  cursorSmoothCaretAnimation: register(new EditorStringEnumOption(27, "cursorSmoothCaretAnimation", "off", ["off", "explicit", "on"], {
    enumDescriptions: [
      localize(568, null),
      localize(569, null),
      localize(570, null)
    ],
    description: localize(571, null)
  })),
  cursorStyle: register(new EditorEnumOption(28, "cursorStyle", TextEditorCursorStyle.Line, "line", ["line", "block", "underline", "line-thin", "block-outline", "underline-thin"], cursorStyleFromString, { description: localize(572, null) })),
  overtypeCursorStyle: register(new EditorEnumOption(84, "overtypeCursorStyle", TextEditorCursorStyle.Block, "block", ["line", "block", "underline", "line-thin", "block-outline", "underline-thin"], cursorStyleFromString, { description: localize(573, null) })),
  cursorSurroundingLines: register(new EditorIntOption(29, "cursorSurroundingLines", 0, 0, 1073741824, { description: localize(574, null) })),
  cursorSurroundingLinesStyle: register(new EditorStringEnumOption(30, "cursorSurroundingLinesStyle", "default", ["default", "all"], {
    enumDescriptions: [
      localize(575, null),
      localize(576, null)
    ],
    markdownDescription: localize(577, null)
  })),
  cursorWidth: register(new EditorIntOption(31, "cursorWidth", 0, 0, 1073741824, { markdownDescription: localize(578, null) })),
  disableLayerHinting: register(new EditorBooleanOption(32, "disableLayerHinting", false)),
  disableMonospaceOptimizations: register(new EditorBooleanOption(33, "disableMonospaceOptimizations", false)),
  domReadOnly: register(new EditorBooleanOption(34, "domReadOnly", false)),
  dragAndDrop: register(new EditorBooleanOption(35, "dragAndDrop", true, { description: localize(579, null) })),
  emptySelectionClipboard: register(new EditorEmptySelectionClipboard()),
  dropIntoEditor: register(new EditorDropIntoEditor()),
  experimentalEditContextEnabled: register(new EditorBooleanOption(37, "experimentalEditContextEnabled", false, {
    description: localize(580, null),
    included: $H || $K || $p
  })),
  stickyScroll: register(new EditorStickyScroll()),
  experimentalGpuAcceleration: register(new EditorStringEnumOption(
    39,
    "experimentalGpuAcceleration",
    "off",
    ["off", "on"],
    void 0
    // TODO: Uncomment when we want to expose the setting to VS Code users
    // {
    // 	enumDescriptions: [
    // 		nls.localize('experimentalGpuAcceleration.off', "Use regular DOM-based rendering."),
    // 		nls.localize('experimentalGpuAcceleration.on', "Use GPU acceleration."),
    // 	],
    // 	description: nls.localize('experimentalGpuAcceleration', "Controls whether to use the (very) experimental GPU acceleration to render the editor.")
    // }
  )),
  experimentalWhitespaceRendering: register(new EditorStringEnumOption(40, "experimentalWhitespaceRendering", "svg", ["svg", "font", "off"], {
    enumDescriptions: [
      localize(581, null),
      localize(582, null),
      localize(583, null)
    ],
    description: localize(584, null)
  })),
  extraEditorClassName: register(new EditorStringOption(41, "extraEditorClassName", "")),
  fastScrollSensitivity: register(new EditorFloatOption(42, "fastScrollSensitivity", 5, (x) => x <= 0 ? 5 : x, { markdownDescription: localize(585, null) })),
  find: register(new EditorFind()),
  fixedOverflowWidgets: register(new EditorBooleanOption(44, "fixedOverflowWidgets", false)),
  folding: register(new EditorBooleanOption(45, "folding", true, { description: localize(586, null) })),
  foldingStrategy: register(new EditorStringEnumOption(46, "foldingStrategy", "auto", ["auto", "indentation"], {
    enumDescriptions: [
      localize(587, null),
      localize(588, null)
    ],
    description: localize(589, null)
  })),
  foldingHighlight: register(new EditorBooleanOption(47, "foldingHighlight", true, { description: localize(590, null) })),
  foldingImportsByDefault: register(new EditorBooleanOption(48, "foldingImportsByDefault", false, { description: localize(591, null) })),
  foldingMaximumRegions: register(new EditorIntOption(
    49,
    "foldingMaximumRegions",
    5e3,
    10,
    65e3,
    // limit must be less than foldingRanges MAX_FOLDING_REGIONS
    { description: localize(592, null) }
  )),
  unfoldOnClickAfterEndOfLine: register(new EditorBooleanOption(50, "unfoldOnClickAfterEndOfLine", false, { description: localize(593, null) })),
  fontFamily: register(new EditorStringOption(51, "fontFamily", EDITOR_FONT_DEFAULTS.fontFamily, { description: localize(594, null) })),
  fontInfo: register(new EditorFontInfo()),
  fontLigatures2: register(new EditorFontLigatures()),
  fontSize: register(new EditorFontSize()),
  fontWeight: register(new EditorFontWeight()),
  fontVariations: register(new EditorFontVariations()),
  formatOnPaste: register(new EditorBooleanOption(57, "formatOnPaste", false, { description: localize(595, null) })),
  formatOnType: register(new EditorBooleanOption(58, "formatOnType", false, { description: localize(596, null) })),
  glyphMargin: register(new EditorBooleanOption(59, "glyphMargin", true, { description: localize(597, null) })),
  gotoLocation: register(new EditorGoToLocation()),
  hideCursorInOverviewRuler: register(new EditorBooleanOption(61, "hideCursorInOverviewRuler", false, { description: localize(598, null) })),
  hover: register(new EditorHover()),
  inDiffEditor: register(new EditorBooleanOption(63, "inDiffEditor", false)),
  letterSpacing: register(new EditorFloatOption(65, "letterSpacing", EDITOR_FONT_DEFAULTS.letterSpacing, (x) => EditorFloatOption.clamp(x, -5, 20), { description: localize(599, null) })),
  lightbulb: register(new EditorLightbulb()),
  lineDecorationsWidth: register(new EditorLineDecorationsWidth()),
  lineHeight: register(new EditorLineHeight()),
  lineNumbers: register(new EditorRenderLineNumbersOption()),
  lineNumbersMinChars: register(new EditorIntOption(70, "lineNumbersMinChars", 5, 1, 300)),
  linkedEditing: register(new EditorBooleanOption(71, "linkedEditing", false, { description: localize(600, null) })),
  links: register(new EditorBooleanOption(72, "links", true, { description: localize(601, null) })),
  matchBrackets: register(new EditorStringEnumOption(73, "matchBrackets", "always", ["always", "near", "never"], { description: localize(602, null) })),
  minimap: register(new EditorMinimap()),
  mouseStyle: register(new EditorStringEnumOption(75, "mouseStyle", "text", ["text", "default", "copy"])),
  mouseWheelScrollSensitivity: register(new EditorFloatOption(76, "mouseWheelScrollSensitivity", 1, (x) => x === 0 ? 1 : x, { markdownDescription: localize(603, null) })),
  mouseWheelZoom: register(new EditorBooleanOption(77, "mouseWheelZoom", false, {
    markdownDescription: $m ? localize(604, null) : localize(605, null)
  })),
  multiCursorMergeOverlapping: register(new EditorBooleanOption(78, "multiCursorMergeOverlapping", true, { description: localize(606, null) })),
  multiCursorModifier: register(new EditorEnumOption(79, "multiCursorModifier", "altKey", "alt", ["ctrlCmd", "alt"], _multiCursorModifierFromString, {
    markdownEnumDescriptions: [
      localize(607, null),
      localize(608, null)
    ],
    markdownDescription: localize(609, null)
  })),
  multiCursorPaste: register(new EditorStringEnumOption(80, "multiCursorPaste", "spread", ["spread", "full"], {
    markdownEnumDescriptions: [
      localize(610, null),
      localize(611, null)
    ],
    markdownDescription: localize(612, null)
  })),
  multiCursorLimit: register(new EditorIntOption(81, "multiCursorLimit", 1e4, 1, 1e5, {
    markdownDescription: localize(613, null)
  })),
  occurrencesHighlight: register(new EditorStringEnumOption(82, "occurrencesHighlight", "singleFile", ["off", "singleFile", "multiFile"], {
    markdownEnumDescriptions: [
      localize(614, null),
      localize(615, null),
      localize(616, null)
    ],
    markdownDescription: localize(617, null)
  })),
  occurrencesHighlightDelay: register(new EditorIntOption(83, "occurrencesHighlightDelay", 250, 0, 2e3, {
    description: localize(618, null),
    tags: ["preview"]
  })),
  overtypeOnPaste: register(new EditorBooleanOption(85, "overtypeOnPaste", true, { description: localize(619, null) })),
  overviewRulerBorder: register(new EditorBooleanOption(86, "overviewRulerBorder", true, { description: localize(620, null) })),
  overviewRulerLanes: register(new EditorIntOption(87, "overviewRulerLanes", 3, 0, 3)),
  padding: register(new EditorPadding()),
  pasteAs: register(new EditorPasteAs()),
  parameterHints: register(new EditorParameterHints()),
  peekWidgetDefaultFocus: register(new EditorStringEnumOption(91, "peekWidgetDefaultFocus", "tree", ["tree", "editor"], {
    enumDescriptions: [
      localize(621, null),
      localize(622, null)
    ],
    description: localize(623, null)
  })),
  placeholder: register(new PlaceholderOption()),
  definitionLinkOpensInPeek: register(new EditorBooleanOption(93, "definitionLinkOpensInPeek", false, { description: localize(624, null) })),
  quickSuggestions: register(new EditorQuickSuggestions()),
  quickSuggestionsDelay: register(new EditorIntOption(95, "quickSuggestionsDelay", 10, 0, 1073741824, { description: localize(625, null) })),
  readOnly: register(new EditorBooleanOption(96, "readOnly", false)),
  readOnlyMessage: register(new ReadonlyMessage()),
  renameOnType: register(new EditorBooleanOption(98, "renameOnType", false, { description: localize(626, null), markdownDeprecationMessage: localize(627, null) })),
  renderControlCharacters: register(new EditorBooleanOption(99, "renderControlCharacters", true, { description: localize(628, null), restricted: true })),
  renderFinalNewline: register(new EditorStringEnumOption(100, "renderFinalNewline", $n ? "dimmed" : "on", ["off", "on", "dimmed"], { description: localize(629, null) })),
  renderLineHighlight: register(new EditorStringEnumOption(101, "renderLineHighlight", "line", ["none", "gutter", "line", "all"], {
    enumDescriptions: [
      "",
      "",
      "",
      localize(630, null)
    ],
    description: localize(631, null)
  })),
  renderLineHighlightOnlyWhenFocus: register(new EditorBooleanOption(102, "renderLineHighlightOnlyWhenFocus", false, { description: localize(632, null) })),
  renderValidationDecorations: register(new EditorStringEnumOption(103, "renderValidationDecorations", "editable", ["editable", "on", "off"])),
  renderWhitespace: register(new EditorStringEnumOption(104, "renderWhitespace", "selection", ["none", "boundary", "selection", "trailing", "all"], {
    enumDescriptions: [
      "",
      localize(633, null),
      localize(634, null),
      localize(635, null),
      ""
    ],
    description: localize(636, null)
  })),
  revealHorizontalRightPadding: register(new EditorIntOption(105, "revealHorizontalRightPadding", 15, 0, 1e3)),
  roundedSelection: register(new EditorBooleanOption(106, "roundedSelection", true, { description: localize(637, null) })),
  rulers: register(new EditorRulers()),
  scrollbar: register(new EditorScrollbar()),
  scrollBeyondLastColumn: register(new EditorIntOption(109, "scrollBeyondLastColumn", 4, 0, 1073741824, { description: localize(638, null) })),
  scrollBeyondLastLine: register(new EditorBooleanOption(110, "scrollBeyondLastLine", true, { description: localize(639, null) })),
  scrollPredominantAxis: register(new EditorBooleanOption(111, "scrollPredominantAxis", true, { description: localize(640, null) })),
  selectionClipboard: register(new EditorBooleanOption(112, "selectionClipboard", true, {
    description: localize(641, null),
    included: $n
  })),
  selectionHighlight: register(new EditorBooleanOption(113, "selectionHighlight", true, { description: localize(642, null) })),
  selectOnLineNumbers: register(new EditorBooleanOption(114, "selectOnLineNumbers", true)),
  showFoldingControls: register(new EditorStringEnumOption(115, "showFoldingControls", "mouseover", ["always", "never", "mouseover"], {
    enumDescriptions: [
      localize(643, null),
      localize(644, null),
      localize(645, null)
    ],
    description: localize(646, null)
  })),
  showUnused: register(new EditorBooleanOption(116, "showUnused", true, { description: localize(647, null) })),
  showDeprecated: register(new EditorBooleanOption(145, "showDeprecated", true, { description: localize(648, null) })),
  inlayHints: register(new EditorInlayHints()),
  snippetSuggestions: register(new EditorStringEnumOption(117, "snippetSuggestions", "inline", ["top", "bottom", "inline", "none"], {
    enumDescriptions: [
      localize(649, null),
      localize(650, null),
      localize(651, null),
      localize(652, null)
    ],
    description: localize(653, null)
  })),
  smartSelect: register(new SmartSelect()),
  smoothScrolling: register(new EditorBooleanOption(119, "smoothScrolling", false, { description: localize(654, null) })),
  stopRenderingLineAfter: register(new EditorIntOption(
    122,
    "stopRenderingLineAfter",
    1e4,
    -1,
    1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  )),
  suggest: register(new EditorSuggest()),
  inlineSuggest: register(new InlineEditorSuggest()),
  inlineCompletionsAccessibilityVerbose: register(new EditorBooleanOption(155, "inlineCompletionsAccessibilityVerbose", false, { description: localize(655, null) })),
  suggestFontSize: register(new EditorIntOption(124, "suggestFontSize", 0, 0, 1e3, { markdownDescription: localize(656, null, "`0`", "`#editor.fontSize#`") })),
  suggestLineHeight: register(new EditorIntOption(125, "suggestLineHeight", 0, 0, 1e3, { markdownDescription: localize(657, null, "`0`", "`#editor.lineHeight#`") })),
  suggestOnTriggerCharacters: register(new EditorBooleanOption(126, "suggestOnTriggerCharacters", true, { description: localize(658, null) })),
  suggestSelection: register(new EditorStringEnumOption(127, "suggestSelection", "first", ["first", "recentlyUsed", "recentlyUsedByPrefix"], {
    markdownEnumDescriptions: [
      localize(659, null),
      localize(660, null),
      localize(661, null)
    ],
    description: localize(662, null)
  })),
  tabCompletion: register(new EditorStringEnumOption(128, "tabCompletion", "off", ["on", "off", "onlySnippets"], {
    enumDescriptions: [
      localize(663, null),
      localize(664, null),
      localize(665, null)
    ],
    description: localize(666, null)
  })),
  tabIndex: register(new EditorIntOption(
    129,
    "tabIndex",
    0,
    -1,
    1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  )),
  unicodeHighlight: register(new UnicodeHighlight()),
  unusualLineTerminators: register(new EditorStringEnumOption(131, "unusualLineTerminators", "prompt", ["auto", "off", "prompt"], {
    enumDescriptions: [
      localize(667, null),
      localize(668, null),
      localize(669, null)
    ],
    description: localize(670, null)
  })),
  useShadowDOM: register(new EditorBooleanOption(132, "useShadowDOM", true)),
  useTabStops: register(new EditorBooleanOption(133, "useTabStops", true, { description: localize(671, null) })),
  wordBreak: register(new EditorStringEnumOption(134, "wordBreak", "normal", ["normal", "keepAll"], {
    markdownEnumDescriptions: [
      localize(672, null),
      localize(673, null)
    ],
    description: localize(674, null)
  })),
  wordSegmenterLocales: register(new WordSegmenterLocales()),
  wordSeparators: register(new EditorStringOption(136, "wordSeparators", $ID, { description: localize(675, null) })),
  wordWrap: register(new EditorStringEnumOption(137, "wordWrap", "off", ["off", "on", "wordWrapColumn", "bounded"], {
    markdownEnumDescriptions: [
      localize(676, null),
      localize(677, null),
      localize(678, null),
      localize(679, null)
    ],
    description: localize(680, null)
  })),
  wordWrapBreakAfterCharacters: register(new EditorStringOption(
    138,
    "wordWrapBreakAfterCharacters",
    // allow-any-unicode-next-line
    " 	})]?|/&.,;\xA2\xB0\u2032\u2033\u2030\u2103\u3001\u3002\uFF61\uFF64\uFFE0\uFF0C\uFF0E\uFF1A\uFF1B\uFF1F\uFF01\uFF05\u30FB\uFF65\u309D\u309E\u30FD\u30FE\u30FC\u30A1\u30A3\u30A5\u30A7\u30A9\u30C3\u30E3\u30E5\u30E7\u30EE\u30F5\u30F6\u3041\u3043\u3045\u3047\u3049\u3063\u3083\u3085\u3087\u308E\u3095\u3096\u31F0\u31F1\u31F2\u31F3\u31F4\u31F5\u31F6\u31F7\u31F8\u31F9\u31FA\u31FB\u31FC\u31FD\u31FE\u31FF\u3005\u303B\uFF67\uFF68\uFF69\uFF6A\uFF6B\uFF6C\uFF6D\uFF6E\uFF6F\uFF70\u201D\u3009\u300B\u300D\u300F\u3011\u3015\uFF09\uFF3D\uFF5D\uFF63"
  )),
  wordWrapBreakBeforeCharacters: register(new EditorStringOption(
    139,
    "wordWrapBreakBeforeCharacters",
    // allow-any-unicode-next-line
    "([{\u2018\u201C\u3008\u300A\u300C\u300E\u3010\u3014\uFF08\uFF3B\uFF5B\uFF62\xA3\xA5\uFF04\uFFE1\uFFE5+\uFF0B"
  )),
  wordWrapColumn: register(new EditorIntOption(140, "wordWrapColumn", 80, 1, 1073741824, {
    markdownDescription: localize(681, null)
  })),
  wordWrapOverride1: register(new EditorStringEnumOption(141, "wordWrapOverride1", "inherit", ["off", "on", "inherit"])),
  wordWrapOverride2: register(new EditorStringEnumOption(142, "wordWrapOverride2", "inherit", ["off", "on", "inherit"])),
  // Leave these at the end (because they have dependencies!)
  effectiveCursorStyle: register(new EffectiveCursorStyle()),
  editorClassName: register(new EditorClassName()),
  defaultColorDecorators: register(new EditorStringEnumOption(153, "defaultColorDecorators", "auto", ["auto", "always", "never"], {
    enumDescriptions: [
      localize(682, null),
      localize(683, null),
      localize(684, null)
    ],
    description: localize(685, null)
  })),
  pixelRatio: register(new EditorPixelRatio()),
  tabFocusMode: register(new EditorBooleanOption(150, "tabFocusMode", false, { markdownDescription: localize(686, null) })),
  layoutInfo: register(new EditorLayoutInfoComputer()),
  wrappingInfo: register(new EditorWrappingInfoComputer()),
  wrappingIndent: register(new WrappingIndentOption()),
  wrappingStrategy: register(new WrappingStrategy())
};

// out-build/vs/platform/product/common/product.js
var product;
var vscodeGlobal2 = globalThis.vscode;
if (typeof vscodeGlobal2 !== "undefined" && typeof vscodeGlobal2.context !== "undefined") {
  const configuration = vscodeGlobal2.context.configuration();
  if (configuration) {
    product = configuration.product;
  } else {
    throw new Error("Sandbox: unable to resolve product configuration from preload script.");
  }
} else if (globalThis._VSCODE_PRODUCT_JSON && globalThis._VSCODE_PACKAGE_JSON) {
  product = globalThis._VSCODE_PRODUCT_JSON;
  if (env["VSCODE_DEV"]) {
    Object.assign(product, {
      nameShort: `${product.nameShort} Dev`,
      nameLong: `${product.nameLong} Dev`,
      dataFolderName: `${product.dataFolderName}-dev`,
      serverDataFolderName: product.serverDataFolderName ? `${product.serverDataFolderName}-dev` : void 0
    });
  }
  if (!product.version) {
    const pkg = globalThis._VSCODE_PACKAGE_JSON;
    Object.assign(product, {
      version: pkg.version
    });
  }
  if (env["EXTENSIONS_GALLERY"]) {
    Object.assign(product, {
      extensionsGallery: JSON.parse(env["EXTENSIONS_GALLERY"])
    });
  }
} else {
  product = { "nameShort": "Code - OSS with Posit Workbench", "nameLong": "Code - OSS with Posit Workbench", "applicationName": "code-server", "dataFolderName": ".vscode-server", "win32MutexName": "vscodeoss", "licenseName": "MIT", "serverLicenseUrl": "https://posit.co/about/eula/", "licenseUrl": "https://posit.co/about/eula/", "serverGreeting": [], "serverLicense": [], "serverLicensePrompt": "", "serverApplicationName": "vscode-server", "serverDataFolderName": ".vscode-server", "tunnelApplicationName": "vscode-tunnel", "win32DirName": "Microsoft Code OSS", "win32NameVersion": "Microsoft Code OSS", "win32RegValueName": "CodeOSS", "win32AppId": "{{F9502347-C9F5-4EBE-8794-75836AAAD88D}", "win32x64AppId": "{{8DA74215-C267-4C6C-A88D-CD657F897B03}", "win32arm64AppId": "{{3AEBF0C8-F733-4AD4-BADE-FDB816D53D7B}", "win32UserAppId": "{{BA70F482-04D8-4BD6-B6C5-976E94C73E13}", "win32x64UserAppId": "{{D4272F45-0AAB-432E-89DE-DBC7DFA87F7D}", "win32arm64UserAppId": "{{B9BE1090-E373-4510-829E-D98C416CB4D9}", "win32AppUserModelId": "Microsoft.CodeOSS", "win32ShellNameShort": "C&ode - OSS", "win32TunnelServiceMutex": "vscodeoss-tunnelservice", "win32TunnelMutex": "vscodeoss-tunnel", "darwinBundleIdentifier": "com.visualstudio.code.oss", "linuxIconName": "code-oss", "licenseFileName": "LICENSE.txt", "reportIssueUrl": "https://github.com/microsoft/vscode/issues/new", "nodejsRepository": "https://nodejs.org", "urlProtocol": "vscode-server", "webviewContentExternalBaseUrlTemplate": "https://{{uuid}}.vscode-cdn.net/insider/ef65ac1ba57f57f2a3961bfe94aa20481caca4c6/out/vs/workbench/contrib/webview/browser/pre/", "builtInExtensions": [{ "name": "ms-vscode.js-debug-companion", "version": "1.1.3", "sha256": "7380a890787452f14b2db7835dfa94de538caf358ebc263f9d46dd68ac52de93", "repo": "https://github.com/microsoft/vscode-js-debug-companion", "metadata": { "id": "99cb0b7f-7354-4278-b8da-6cc79972169d", "publisherId": { "publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee", "publisherName": "ms-vscode", "displayName": "Microsoft", "flags": "verified" }, "publisherDisplayName": "Microsoft" } }, { "name": "ms-vscode.js-debug", "version": "1.96.0", "sha256": "278cd8b129c133d834a8105d0e0699f2f940c5c159fa5c821c7b9a4f7ffd3581", "repo": "https://github.com/microsoft/vscode-js-debug", "metadata": { "id": "25629058-ddac-4e17-abba-74678e126c5d", "publisherId": { "publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee", "publisherName": "ms-vscode", "displayName": "Microsoft", "flags": "verified" }, "publisherDisplayName": "Microsoft" } }, { "name": "ms-vscode.vscode-js-profile-table", "version": "1.0.10", "sha256": "7361748ddf9fd09d8a2ed1f2a2d7376a2cf9aae708692820b799708385c38e08", "repo": "https://github.com/microsoft/vscode-js-profile-visualizer", "metadata": { "id": "7e52b41b-71ad-457b-ab7e-0620f1fc4feb", "publisherId": { "publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee", "publisherName": "ms-vscode", "displayName": "Microsoft", "flags": "verified" }, "publisherDisplayName": "Microsoft" } }, { "name": "rstudio.rstudio-workbench", "version": "1.5.28", "positUrl": "https://cdn.posit.co/pwb-components/extension", "type": "reh-web", "sha256": "a1052e6cf884977b68883950360d29b394acdbdd2a84f0b17a7cc9887436918f", "metadata": { "publisherDisplayName": "Posit PBC" } }], "extensionsGallery": { "serviceUrl": "https://open-vsx.org/vscode/gallery", "itemUrl": "https://open-vsx.org/vscode/item", "resourceUrlTemplate": "https://open-vsx.org/vscode/asset/{publisher}/{name}/{version}/Microsoft.VisualStudio.Code.WebResources/{path}", "controlUrl": "", "recommendationsUrl": "" }, "linkProtectionTrustedDomains": ["https://open-vsx.org"], "version": "1.96.0", "commit": "b53f4ab975dd2f3b4cf7cd418ed669697450b40a", "date": "2025-02-18T16:54:01.014Z" };
  if (Object.keys(product).length === 0) {
    Object.assign(product, {
      version: "1.95.0-dev",
      nameShort: "Code - OSS Dev",
      nameLong: "Code - OSS Dev",
      applicationName: "code-oss",
      dataFolderName: ".vscode-oss",
      urlProtocol: "code-oss",
      reportIssueUrl: "https://github.com/microsoft/vscode/issues/new",
      licenseName: "MIT",
      licenseUrl: "https://github.com/microsoft/vscode/blob/main/LICENSE.txt",
      serverLicenseUrl: "https://github.com/microsoft/vscode/blob/main/LICENSE.txt"
    });
  }
}
var product_default = product;

// out-build/vs/workbench/services/extensions/common/proxyIdentifier.js
var $BS = class _$BS {
  static {
    this.count = 0;
  }
  constructor(sid) {
    this._proxyIdentifierBrand = void 0;
    this.sid = sid;
    this.nid = ++_$BS.count;
  }
};
var identifiers = [];
function $CS(identifier) {
  const result = new $BS(identifier);
  identifiers[result.nid] = result;
  return result;
}
function $DS(nid) {
  return identifiers[nid].sid;
}
var $ES = class {
  constructor(value) {
    this.value = value;
  }
};

// out-build/vs/workbench/api/common/extHost.protocol.js
var TextEditorRevealType;
(function(TextEditorRevealType3) {
  TextEditorRevealType3[TextEditorRevealType3["Default"] = 0] = "Default";
  TextEditorRevealType3[TextEditorRevealType3["InCenter"] = 1] = "InCenter";
  TextEditorRevealType3[TextEditorRevealType3["InCenterIfOutsideViewport"] = 2] = "InCenterIfOutsideViewport";
  TextEditorRevealType3[TextEditorRevealType3["AtTop"] = 3] = "AtTop";
})(TextEditorRevealType || (TextEditorRevealType = {}));
var TabInputKind;
(function(TabInputKind2) {
  TabInputKind2[TabInputKind2["UnknownInput"] = 0] = "UnknownInput";
  TabInputKind2[TabInputKind2["TextInput"] = 1] = "TextInput";
  TabInputKind2[TabInputKind2["TextDiffInput"] = 2] = "TextDiffInput";
  TabInputKind2[TabInputKind2["TextMergeInput"] = 3] = "TextMergeInput";
  TabInputKind2[TabInputKind2["NotebookInput"] = 4] = "NotebookInput";
  TabInputKind2[TabInputKind2["NotebookDiffInput"] = 5] = "NotebookDiffInput";
  TabInputKind2[TabInputKind2["CustomEditorInput"] = 6] = "CustomEditorInput";
  TabInputKind2[TabInputKind2["WebviewEditorInput"] = 7] = "WebviewEditorInput";
  TabInputKind2[TabInputKind2["TerminalEditorInput"] = 8] = "TerminalEditorInput";
  TabInputKind2[TabInputKind2["InteractiveEditorInput"] = 9] = "InteractiveEditorInput";
  TabInputKind2[TabInputKind2["ChatEditorInput"] = 10] = "ChatEditorInput";
  TabInputKind2[TabInputKind2["MultiDiffEditorInput"] = 11] = "MultiDiffEditorInput";
})(TabInputKind || (TabInputKind = {}));
var TabModelOperationKind;
(function(TabModelOperationKind2) {
  TabModelOperationKind2[TabModelOperationKind2["TAB_OPEN"] = 0] = "TAB_OPEN";
  TabModelOperationKind2[TabModelOperationKind2["TAB_CLOSE"] = 1] = "TAB_CLOSE";
  TabModelOperationKind2[TabModelOperationKind2["TAB_UPDATE"] = 2] = "TAB_UPDATE";
  TabModelOperationKind2[TabModelOperationKind2["TAB_MOVE"] = 3] = "TAB_MOVE";
})(TabModelOperationKind || (TabModelOperationKind = {}));
var WebviewEditorCapabilities;
(function(WebviewEditorCapabilities2) {
  WebviewEditorCapabilities2[WebviewEditorCapabilities2["Editable"] = 0] = "Editable";
  WebviewEditorCapabilities2[WebviewEditorCapabilities2["SupportsHotExit"] = 1] = "SupportsHotExit";
})(WebviewEditorCapabilities || (WebviewEditorCapabilities = {}));
var WebviewMessageArrayBufferViewType;
(function(WebviewMessageArrayBufferViewType2) {
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Int8Array"] = 1] = "Int8Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Uint8Array"] = 2] = "Uint8Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Uint8ClampedArray"] = 3] = "Uint8ClampedArray";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Int16Array"] = 4] = "Int16Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Uint16Array"] = 5] = "Uint16Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Int32Array"] = 6] = "Int32Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Uint32Array"] = 7] = "Uint32Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Float32Array"] = 8] = "Float32Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Float64Array"] = 9] = "Float64Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["BigInt64Array"] = 10] = "BigInt64Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["BigUint64Array"] = 11] = "BigUint64Array";
})(WebviewMessageArrayBufferViewType || (WebviewMessageArrayBufferViewType = {}));
var CellOutputKind;
(function(CellOutputKind2) {
  CellOutputKind2[CellOutputKind2["Text"] = 1] = "Text";
  CellOutputKind2[CellOutputKind2["Error"] = 2] = "Error";
  CellOutputKind2[CellOutputKind2["Rich"] = 3] = "Rich";
})(CellOutputKind || (CellOutputKind = {}));
var NotebookEditorRevealType;
(function(NotebookEditorRevealType3) {
  NotebookEditorRevealType3[NotebookEditorRevealType3["Default"] = 0] = "Default";
  NotebookEditorRevealType3[NotebookEditorRevealType3["InCenter"] = 1] = "InCenter";
  NotebookEditorRevealType3[NotebookEditorRevealType3["InCenterIfOutsideViewport"] = 2] = "InCenterIfOutsideViewport";
  NotebookEditorRevealType3[NotebookEditorRevealType3["AtTop"] = 3] = "AtTop";
})(NotebookEditorRevealType || (NotebookEditorRevealType = {}));
var CandidatePortSource;
(function(CandidatePortSource2) {
  CandidatePortSource2[CandidatePortSource2["None"] = 0] = "None";
  CandidatePortSource2[CandidatePortSource2["Process"] = 1] = "Process";
  CandidatePortSource2[CandidatePortSource2["Output"] = 2] = "Output";
  CandidatePortSource2[CandidatePortSource2["Hybrid"] = 3] = "Hybrid";
})(CandidatePortSource || (CandidatePortSource = {}));
var $wT = class _$wT {
  static {
    this.a = 0;
  }
  static mixin(object) {
    object._id = _$wT.a++;
    return object;
  }
};
var ISuggestDataDtoField;
(function(ISuggestDataDtoField2) {
  ISuggestDataDtoField2["label"] = "a";
  ISuggestDataDtoField2["kind"] = "b";
  ISuggestDataDtoField2["detail"] = "c";
  ISuggestDataDtoField2["documentation"] = "d";
  ISuggestDataDtoField2["sortText"] = "e";
  ISuggestDataDtoField2["filterText"] = "f";
  ISuggestDataDtoField2["preselect"] = "g";
  ISuggestDataDtoField2["insertText"] = "h";
  ISuggestDataDtoField2["insertTextRules"] = "i";
  ISuggestDataDtoField2["range"] = "j";
  ISuggestDataDtoField2["commitCharacters"] = "k";
  ISuggestDataDtoField2["additionalTextEdits"] = "l";
  ISuggestDataDtoField2["kindModifier"] = "m";
  ISuggestDataDtoField2["commandIdent"] = "n";
  ISuggestDataDtoField2["commandId"] = "o";
  ISuggestDataDtoField2["commandArguments"] = "p";
})(ISuggestDataDtoField || (ISuggestDataDtoField = {}));
var ISuggestResultDtoField;
(function(ISuggestResultDtoField2) {
  ISuggestResultDtoField2["defaultRanges"] = "a";
  ISuggestResultDtoField2["completions"] = "b";
  ISuggestResultDtoField2["isIncomplete"] = "c";
  ISuggestResultDtoField2["duration"] = "d";
})(ISuggestResultDtoField || (ISuggestResultDtoField = {}));
var ExtHostTestingResource;
(function(ExtHostTestingResource2) {
  ExtHostTestingResource2[ExtHostTestingResource2["Workspace"] = 0] = "Workspace";
  ExtHostTestingResource2[ExtHostTestingResource2["TextDocument"] = 1] = "TextDocument";
})(ExtHostTestingResource || (ExtHostTestingResource = {}));
var $xT = {
  MainThreadAuthentication: $CS("MainThreadAuthentication"),
  MainThreadBulkEdits: $CS("MainThreadBulkEdits"),
  MainThreadLanguageModels: $CS("MainThreadLanguageModels"),
  MainThreadEmbeddings: $CS("MainThreadEmbeddings"),
  MainThreadChatAgents2: $CS("MainThreadChatAgents2"),
  MainThreadCodeMapper: $CS("MainThreadCodeMapper"),
  MainThreadChatVariables: $CS("MainThreadChatVariables"),
  MainThreadLanguageModelTools: $CS("MainThreadChatSkills"),
  MainThreadClipboard: $CS("MainThreadClipboard"),
  MainThreadCommands: $CS("MainThreadCommands"),
  MainThreadComments: $CS("MainThreadComments"),
  MainThreadConfiguration: $CS("MainThreadConfiguration"),
  MainThreadConsole: $CS("MainThreadConsole"),
  MainThreadDebugService: $CS("MainThreadDebugService"),
  MainThreadDecorations: $CS("MainThreadDecorations"),
  MainThreadDiagnostics: $CS("MainThreadDiagnostics"),
  MainThreadDialogs: $CS("MainThreadDiaglogs"),
  MainThreadDocuments: $CS("MainThreadDocuments"),
  MainThreadDocumentContentProviders: $CS("MainThreadDocumentContentProviders"),
  MainThreadTextEditors: $CS("MainThreadTextEditors"),
  MainThreadEditorInsets: $CS("MainThreadEditorInsets"),
  MainThreadEditorTabs: $CS("MainThreadEditorTabs"),
  MainThreadErrors: $CS("MainThreadErrors"),
  MainThreadTreeViews: $CS("MainThreadTreeViews"),
  MainThreadDownloadService: $CS("MainThreadDownloadService"),
  MainThreadLanguageFeatures: $CS("MainThreadLanguageFeatures"),
  MainThreadLanguages: $CS("MainThreadLanguages"),
  MainThreadLogger: $CS("MainThreadLogger"),
  MainThreadMessageService: $CS("MainThreadMessageService"),
  MainThreadOutputService: $CS("MainThreadOutputService"),
  MainThreadProgress: $CS("MainThreadProgress"),
  MainThreadQuickDiff: $CS("MainThreadQuickDiff"),
  MainThreadQuickOpen: $CS("MainThreadQuickOpen"),
  MainThreadStatusBar: $CS("MainThreadStatusBar"),
  MainThreadSecretState: $CS("MainThreadSecretState"),
  MainThreadStorage: $CS("MainThreadStorage"),
  MainThreadSpeech: $CS("MainThreadSpeechProvider"),
  MainThreadTelemetry: $CS("MainThreadTelemetry"),
  MainThreadTerminalService: $CS("MainThreadTerminalService"),
  MainThreadTerminalShellIntegration: $CS("MainThreadTerminalShellIntegration"),
  MainThreadWebviews: $CS("MainThreadWebviews"),
  MainThreadWebviewPanels: $CS("MainThreadWebviewPanels"),
  MainThreadWebviewViews: $CS("MainThreadWebviewViews"),
  MainThreadCustomEditors: $CS("MainThreadCustomEditors"),
  MainThreadUrls: $CS("MainThreadUrls"),
  MainThreadUriOpeners: $CS("MainThreadUriOpeners"),
  MainThreadProfileContentHandlers: $CS("MainThreadProfileContentHandlers"),
  MainThreadWorkspace: $CS("MainThreadWorkspace"),
  MainThreadFileSystem: $CS("MainThreadFileSystem"),
  MainThreadFileSystemEventService: $CS("MainThreadFileSystemEventService"),
  MainThreadExtensionService: $CS("MainThreadExtensionService"),
  MainThreadSCM: $CS("MainThreadSCM"),
  MainThreadSearch: $CS("MainThreadSearch"),
  MainThreadShare: $CS("MainThreadShare"),
  MainThreadTask: $CS("MainThreadTask"),
  MainThreadWindow: $CS("MainThreadWindow"),
  MainThreadLabelService: $CS("MainThreadLabelService"),
  MainThreadNotebook: $CS("MainThreadNotebook"),
  MainThreadNotebookDocuments: $CS("MainThreadNotebookDocumentsShape"),
  MainThreadNotebookEditors: $CS("MainThreadNotebookEditorsShape"),
  MainThreadNotebookKernels: $CS("MainThreadNotebookKernels"),
  MainThreadNotebookRenderers: $CS("MainThreadNotebookRenderers"),
  MainThreadInteractive: $CS("MainThreadInteractive"),
  MainThreadTheming: $CS("MainThreadTheming"),
  MainThreadTunnelService: $CS("MainThreadTunnelService"),
  MainThreadManagedSockets: $CS("MainThreadManagedSockets"),
  MainThreadTimeline: $CS("MainThreadTimeline"),
  MainThreadTesting: $CS("MainThreadTesting"),
  MainThreadLocalization: $CS("MainThreadLocalizationShape"),
  MainThreadAiRelatedInformation: $CS("MainThreadAiRelatedInformation"),
  MainThreadAiEmbeddingVector: $CS("MainThreadAiEmbeddingVector")
};
var $yT = {
  ExtHostCodeMapper: $CS("ExtHostCodeMapper"),
  ExtHostCommands: $CS("ExtHostCommands"),
  ExtHostConfiguration: $CS("ExtHostConfiguration"),
  ExtHostDiagnostics: $CS("ExtHostDiagnostics"),
  ExtHostDebugService: $CS("ExtHostDebugService"),
  ExtHostDecorations: $CS("ExtHostDecorations"),
  ExtHostDocumentsAndEditors: $CS("ExtHostDocumentsAndEditors"),
  ExtHostDocuments: $CS("ExtHostDocuments"),
  ExtHostDocumentContentProviders: $CS("ExtHostDocumentContentProviders"),
  ExtHostDocumentSaveParticipant: $CS("ExtHostDocumentSaveParticipant"),
  ExtHostEditors: $CS("ExtHostEditors"),
  ExtHostTreeViews: $CS("ExtHostTreeViews"),
  ExtHostFileSystem: $CS("ExtHostFileSystem"),
  ExtHostFileSystemInfo: $CS("ExtHostFileSystemInfo"),
  ExtHostFileSystemEventService: $CS("ExtHostFileSystemEventService"),
  ExtHostLanguages: $CS("ExtHostLanguages"),
  ExtHostLanguageFeatures: $CS("ExtHostLanguageFeatures"),
  ExtHostQuickOpen: $CS("ExtHostQuickOpen"),
  ExtHostQuickDiff: $CS("ExtHostQuickDiff"),
  ExtHostStatusBar: $CS("ExtHostStatusBar"),
  ExtHostShare: $CS("ExtHostShare"),
  ExtHostExtensionService: $CS("ExtHostExtensionService"),
  ExtHostLogLevelServiceShape: $CS("ExtHostLogLevelServiceShape"),
  ExtHostTerminalService: $CS("ExtHostTerminalService"),
  ExtHostTerminalShellIntegration: $CS("ExtHostTerminalShellIntegration"),
  ExtHostSCM: $CS("ExtHostSCM"),
  ExtHostSearch: $CS("ExtHostSearch"),
  ExtHostTask: $CS("ExtHostTask"),
  ExtHostWorkspace: $CS("ExtHostWorkspace"),
  ExtHostWindow: $CS("ExtHostWindow"),
  ExtHostWebviews: $CS("ExtHostWebviews"),
  ExtHostWebviewPanels: $CS("ExtHostWebviewPanels"),
  ExtHostCustomEditors: $CS("ExtHostCustomEditors"),
  ExtHostWebviewViews: $CS("ExtHostWebviewViews"),
  ExtHostEditorInsets: $CS("ExtHostEditorInsets"),
  ExtHostEditorTabs: $CS("ExtHostEditorTabs"),
  ExtHostProgress: $CS("ExtHostProgress"),
  ExtHostComments: $CS("ExtHostComments"),
  ExtHostSecretState: $CS("ExtHostSecretState"),
  ExtHostStorage: $CS("ExtHostStorage"),
  ExtHostUrls: $CS("ExtHostUrls"),
  ExtHostUriOpeners: $CS("ExtHostUriOpeners"),
  ExtHostProfileContentHandlers: $CS("ExtHostProfileContentHandlers"),
  ExtHostOutputService: $CS("ExtHostOutputService"),
  ExtHostLabelService: $CS("ExtHostLabelService"),
  ExtHostNotebook: $CS("ExtHostNotebook"),
  ExtHostNotebookDocuments: $CS("ExtHostNotebookDocuments"),
  ExtHostNotebookEditors: $CS("ExtHostNotebookEditors"),
  ExtHostNotebookKernels: $CS("ExtHostNotebookKernels"),
  ExtHostNotebookRenderers: $CS("ExtHostNotebookRenderers"),
  ExtHostNotebookDocumentSaveParticipant: $CS("ExtHostNotebookDocumentSaveParticipant"),
  ExtHostInteractive: $CS("ExtHostInteractive"),
  ExtHostChatAgents2: $CS("ExtHostChatAgents"),
  ExtHostChatVariables: $CS("ExtHostChatVariables"),
  ExtHostLanguageModelTools: $CS("ExtHostChatSkills"),
  ExtHostChatProvider: $CS("ExtHostChatProvider"),
  ExtHostSpeech: $CS("ExtHostSpeech"),
  ExtHostEmbeddings: $CS("ExtHostEmbeddings"),
  ExtHostAiRelatedInformation: $CS("ExtHostAiRelatedInformation"),
  ExtHostAiEmbeddingVector: $CS("ExtHostAiEmbeddingVector"),
  ExtHostTheming: $CS("ExtHostTheming"),
  ExtHostTunnelService: $CS("ExtHostTunnelService"),
  ExtHostManagedSockets: $CS("ExtHostManagedSockets"),
  ExtHostAuthentication: $CS("ExtHostAuthentication"),
  ExtHostTimeline: $CS("ExtHostTimeline"),
  ExtHostTesting: $CS("ExtHostTesting"),
  ExtHostTelemetry: $CS("ExtHostTelemetry"),
  ExtHostLocalization: $CS("ExtHostLocalization")
};

// out-build/vs/base/common/uriIpc.js
function toJSON(uri) {
  return uri.toJSON();
}
var $ry = class {
  constructor(uriTransformer) {
    this.a = uriTransformer;
  }
  transformIncoming(uri) {
    const result = this.a.transformIncoming(uri);
    return result === uri ? uri : toJSON(URI.from(result));
  }
  transformOutgoing(uri) {
    const result = this.a.transformOutgoing(uri);
    return result === uri ? uri : toJSON(URI.from(result));
  }
  transformOutgoingURI(uri) {
    const result = this.a.transformOutgoing(uri);
    return result === uri ? uri : URI.from(result);
  }
  transformOutgoingScheme(scheme) {
    return this.a.transformOutgoingScheme(scheme);
  }
};
var $sy = new class {
  transformIncoming(uri) {
    return uri;
  }
  transformOutgoing(uri) {
    return uri;
  }
  transformOutgoingURI(uri) {
    return uri;
  }
  transformOutgoingScheme(scheme) {
    return scheme;
  }
}();
function _transformIncomingURIs(obj, transformer, revive, depth) {
  if (!obj || depth > 200) {
    return null;
  }
  if (typeof obj === "object") {
    if (obj.$mid === 1) {
      return revive ? URI.revive(transformer.transformIncoming(obj)) : transformer.transformIncoming(obj);
    }
    if (obj instanceof $Ci) {
      return null;
    }
    for (const key in obj) {
      if (Object.hasOwnProperty.call(obj, key)) {
        const r = _transformIncomingURIs(obj[key], transformer, revive, depth + 1);
        if (r !== null) {
          obj[key] = r;
        }
      }
    }
  }
  return null;
}
function $uy(obj, transformer) {
  const result = _transformIncomingURIs(obj, transformer, false, 0);
  if (result === null) {
    return obj;
  }
  return result;
}

// out-build/vs/workbench/services/extensions/common/lazyPromise.js
var $mnc = class {
  constructor() {
    this.a = null;
    this.b = null;
    this.d = null;
    this.f = false;
    this.g = null;
    this.h = false;
    this.i = null;
  }
  get [Symbol.toStringTag]() {
    return this.toString();
  }
  j() {
    if (!this.a) {
      this.a = new Promise((c, e) => {
        this.b = c;
        this.d = e;
        if (this.f) {
          this.b(this.g);
        }
        if (this.h) {
          this.d(this.i);
        }
      });
    }
    return this.a;
  }
  resolveOk(value) {
    if (this.f || this.h) {
      return;
    }
    this.f = true;
    this.g = value;
    if (this.a) {
      this.b(value);
    }
  }
  resolveErr(err) {
    if (this.f || this.h) {
      return;
    }
    this.h = true;
    this.i = err;
    if (this.a) {
      this.d(err);
    } else {
      $gb(err);
    }
  }
  then(success, error) {
    return this.j().then(success, error);
  }
  catch(error) {
    return this.j().then(void 0, error);
  }
  finally(callback) {
    return this.j().finally(callback);
  }
};
var $nnc = class extends $mnc {
  constructor() {
    super();
    this.h = true;
    this.i = new $lb();
  }
};

// out-build/vs/workbench/services/extensions/common/rpcProtocol.js
var _a3;
function safeStringify(obj, replacer2) {
  try {
    return JSON.stringify(obj, replacer2);
  } catch (err) {
    return "null";
  }
}
var refSymbolName = "$$ref$$";
var undefinedRef = { [refSymbolName]: -1 };
function $onc(obj, replacer2 = null, useSafeStringify = false) {
  const foundBuffers = [];
  const serialized = (useSafeStringify ? safeStringify : JSON.stringify)(obj, (key, value) => {
    if (typeof value === "undefined") {
      return undefinedRef;
    } else if (typeof value === "object") {
      if (value instanceof $Ci) {
        const bufferIndex = foundBuffers.push(value) - 1;
        return { [refSymbolName]: bufferIndex };
      }
      if (replacer2) {
        return replacer2(key, value);
      }
    }
    return value;
  });
  return {
    jsonString: serialized,
    referencedBuffers: foundBuffers
  };
}
function $pnc(jsonString, buffers, uriTransformer) {
  return JSON.parse(jsonString, (_key, value) => {
    if (value) {
      const ref = value[refSymbolName];
      if (typeof ref === "number") {
        return buffers[ref];
      }
      if (uriTransformer && value.$mid === 1) {
        return uriTransformer.transformIncoming(value);
      }
    }
    return value;
  });
}
function stringify(obj, replacer2) {
  return JSON.stringify(obj, replacer2);
}
function createURIReplacer(transformer) {
  if (!transformer) {
    return null;
  }
  return (key, value) => {
    if (value && value.$mid === 1) {
      return transformer.transformOutgoing(value);
    }
    return value;
  };
}
var RequestInitiator2;
(function(RequestInitiator3) {
  RequestInitiator3[RequestInitiator3["LocalSide"] = 0] = "LocalSide";
  RequestInitiator3[RequestInitiator3["OtherSide"] = 1] = "OtherSide";
})(RequestInitiator2 || (RequestInitiator2 = {}));
var ResponsiveState;
(function(ResponsiveState2) {
  ResponsiveState2[ResponsiveState2["Responsive"] = 0] = "Responsive";
  ResponsiveState2[ResponsiveState2["Unresponsive"] = 1] = "Unresponsive";
})(ResponsiveState || (ResponsiveState = {}));
var noop = () => {
};
var _RPCProtocolSymbol = Symbol.for("rpcProtocol");
var _RPCProxySymbol = Symbol.for("rpcProxy");
var $qnc = class _$qnc extends $3c {
  static {
    _a3 = _RPCProtocolSymbol;
  }
  static {
    this.a = 3 * 1e3;
  }
  // 3s
  constructor(protocol, logger = null, transformer = null) {
    super();
    this[_a3] = true;
    this.b = this.B(new $ze());
    this.onDidChangeResponsiveState = this.b.event;
    this.c = protocol;
    this.f = logger;
    this.g = transformer;
    this.h = createURIReplacer(this.g);
    this.j = false;
    this.m = [];
    this.s = [];
    for (let i = 0, len = $BS.count; i < len; i++) {
      this.m[i] = null;
      this.s[i] = null;
    }
    this.t = 0;
    this.u = /* @__PURE__ */ Object.create(null);
    this.w = {};
    this.y = 0;
    this.z = 0;
    this.C = 0;
    this.D = this.B(new $8h(() => this.H(), 1e3));
    this.B(this.c.onMessage((msg) => this.L(msg)));
  }
  dispose() {
    this.j = true;
    Object.keys(this.w).forEach((msgId) => {
      const pending = this.w[msgId];
      delete this.w[msgId];
      pending.resolveErr($mb());
    });
    super.dispose();
  }
  drain() {
    if (typeof this.c.drain === "function") {
      return this.c.drain();
    }
    return Promise.resolve();
  }
  F(req) {
    if (this.z === 0) {
      this.C = Date.now() + _$qnc.a;
    }
    this.z++;
    if (!this.D.isScheduled()) {
      this.D.schedule();
    }
  }
  G(req) {
    this.C = Date.now() + _$qnc.a;
    this.z--;
    if (this.z === 0) {
      this.D.cancel();
    }
    this.I(
      0
      /* ResponsiveState.Responsive */
    );
  }
  H() {
    if (this.z === 0) {
      return;
    }
    if (Date.now() > this.C) {
      this.I(
        1
        /* ResponsiveState.Unresponsive */
      );
    } else {
      this.D.schedule();
    }
  }
  I(newResponsiveState) {
    if (this.y === newResponsiveState) {
      return;
    }
    this.y = newResponsiveState;
    this.b.fire(this.y);
  }
  get responsiveState() {
    return this.y;
  }
  transformIncomingURIs(obj) {
    if (!this.g) {
      return obj;
    }
    return $uy(obj, this.g);
  }
  getProxy(identifier) {
    const { nid: rpcId, sid } = identifier;
    if (!this.s[rpcId]) {
      this.s[rpcId] = this.J(rpcId, sid);
    }
    return this.s[rpcId];
  }
  J(rpcId, debugName) {
    const handler = {
      get: (target, name) => {
        if (typeof name === "string" && !target[name] && name.charCodeAt(0) === 36) {
          target[name] = (...myArgs) => {
            return this.U(rpcId, name, myArgs);
          };
        }
        if (name === _RPCProxySymbol) {
          return debugName;
        }
        return target[name];
      }
    };
    return new Proxy(/* @__PURE__ */ Object.create(null), handler);
  }
  set(identifier, value) {
    this.m[identifier.nid] = value;
    return value;
  }
  assertRegistered(identifiers2) {
    for (let i = 0, len = identifiers2.length; i < len; i++) {
      const identifier = identifiers2[i];
      if (!this.m[identifier.nid]) {
        throw new Error(`Missing proxy instance ${identifier.sid}`);
      }
    }
  }
  L(rawmsg) {
    if (this.j) {
      return;
    }
    const msgLength = rawmsg.byteLength;
    const buff = MessageBuffer.read(rawmsg, 0);
    const messageType = buff.readUInt8();
    const req = buff.readUInt32();
    switch (messageType) {
      case 1:
      case 2: {
        let { rpcId, method, args: args2 } = MessageIO.deserializeRequestJSONArgs(buff);
        if (this.g) {
          args2 = $uy(args2, this.g);
        }
        this.M(msgLength, req, rpcId, method, args2, messageType === 2);
        break;
      }
      case 3:
      case 4: {
        let { rpcId, method, args: args2 } = MessageIO.deserializeRequestMixedArgs(buff);
        if (this.g) {
          args2 = $uy(args2, this.g);
        }
        this.M(msgLength, req, rpcId, method, args2, messageType === 4);
        break;
      }
      case 5: {
        this.f?.logIncoming(msgLength, req, 0, `ack`);
        this.G(req);
        break;
      }
      case 6: {
        this.N(msgLength, req);
        break;
      }
      case 7: {
        this.O(msgLength, req, void 0);
        break;
      }
      case 9: {
        let value = MessageIO.deserializeReplyOKJSON(buff);
        if (this.g) {
          value = $uy(value, this.g);
        }
        this.O(msgLength, req, value);
        break;
      }
      case 10: {
        const value = MessageIO.deserializeReplyOKJSONWithBuffers(buff, this.g);
        this.O(msgLength, req, value);
        break;
      }
      case 8: {
        const value = MessageIO.deserializeReplyOKVSBuffer(buff);
        this.O(msgLength, req, value);
        break;
      }
      case 11: {
        let err = MessageIO.deserializeReplyErrError(buff);
        if (this.g) {
          err = $uy(err, this.g);
        }
        this.P(msgLength, req, err);
        break;
      }
      case 12: {
        this.P(msgLength, req, void 0);
        break;
      }
      default:
        console.error(`received unexpected message`);
        console.error(rawmsg);
    }
  }
  M(msgLength, req, rpcId, method, args2, usesCancellationToken) {
    this.f?.logIncoming(msgLength, req, 1, `receiveRequest ${$DS(rpcId)}.${method}(`, args2);
    const callId = String(req);
    let promise;
    let cancel;
    if (usesCancellationToken) {
      const cancellationTokenSource = new $ad();
      args2.push(cancellationTokenSource.token);
      promise = this.Q(rpcId, method, args2);
      cancel = () => cancellationTokenSource.cancel();
    } else {
      promise = this.Q(rpcId, method, args2);
      cancel = noop;
    }
    this.u[callId] = cancel;
    const msg = MessageIO.serializeAcknowledged(req);
    this.f?.logOutgoing(msg.byteLength, req, 1, `ack`);
    this.c.send(msg);
    promise.then((r) => {
      delete this.u[callId];
      const msg2 = MessageIO.serializeReplyOK(req, r, this.h);
      this.f?.logOutgoing(msg2.byteLength, req, 1, `reply:`, r);
      this.c.send(msg2);
    }, (err) => {
      delete this.u[callId];
      const msg2 = MessageIO.serializeReplyErr(req, err);
      this.f?.logOutgoing(msg2.byteLength, req, 1, `replyErr:`, err);
      this.c.send(msg2);
    });
  }
  N(msgLength, req) {
    this.f?.logIncoming(msgLength, req, 1, `receiveCancel`);
    const callId = String(req);
    this.u[callId]?.();
  }
  O(msgLength, req, value) {
    this.f?.logIncoming(msgLength, req, 0, `receiveReply:`, value);
    const callId = String(req);
    if (!this.w.hasOwnProperty(callId)) {
      return;
    }
    const pendingReply = this.w[callId];
    delete this.w[callId];
    pendingReply.resolveOk(value);
  }
  P(msgLength, req, value) {
    this.f?.logIncoming(msgLength, req, 0, `receiveReplyErr:`, value);
    const callId = String(req);
    if (!this.w.hasOwnProperty(callId)) {
      return;
    }
    const pendingReply = this.w[callId];
    delete this.w[callId];
    let err = void 0;
    if (value) {
      if (value.$isError) {
        err = new Error();
        err.name = value.name;
        err.message = value.message;
        err.stack = value.stack;
      } else {
        err = value;
      }
    }
    pendingReply.resolveErr(err);
  }
  Q(rpcId, methodName, args2) {
    try {
      return Promise.resolve(this.S(rpcId, methodName, args2));
    } catch (err) {
      return Promise.reject(err);
    }
  }
  S(rpcId, methodName, args2) {
    const actor = this.m[rpcId];
    if (!actor) {
      throw new Error("Unknown actor " + $DS(rpcId));
    }
    const method = actor[methodName];
    if (typeof method !== "function") {
      throw new Error("Unknown method " + methodName + " on actor " + $DS(rpcId));
    }
    return method.apply(actor, args2);
  }
  U(rpcId, methodName, args2) {
    if (this.j) {
      return new $nnc();
    }
    let cancellationToken = null;
    if (args2.length > 0 && CancellationToken.isCancellationToken(args2[args2.length - 1])) {
      cancellationToken = args2.pop();
    }
    if (cancellationToken && cancellationToken.isCancellationRequested) {
      return Promise.reject($mb());
    }
    const serializedRequestArguments = MessageIO.serializeRequestArguments(args2, this.h);
    const req = ++this.t;
    const callId = String(req);
    const result = new $mnc();
    const disposable = new $2c();
    if (cancellationToken) {
      disposable.add(cancellationToken.onCancellationRequested(() => {
        const msg2 = MessageIO.serializeCancel(req);
        this.f?.logOutgoing(msg2.byteLength, req, 0, `cancel`);
        this.c.send(msg2);
      }));
    }
    this.w[callId] = new PendingRPCReply(result, disposable);
    this.F(req);
    const msg = MessageIO.serializeRequest(req, rpcId, methodName, serializedRequestArguments, !!cancellationToken);
    this.f?.logOutgoing(msg.byteLength, req, 0, `request: ${$DS(rpcId)}.${methodName}(`, args2);
    this.c.send(msg);
    return result;
  }
};
var PendingRPCReply = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  resolveOk(value) {
    this.a.resolveOk(value);
    this.b.dispose();
  }
  resolveErr(err) {
    this.a.resolveErr(err);
    this.b.dispose();
  }
};
var MessageBuffer = class _MessageBuffer {
  static alloc(type, req, messageSize) {
    const result = new _MessageBuffer($Ci.alloc(
      messageSize + 1 + 4
      /* req */
    ), 0);
    result.writeUInt8(type);
    result.writeUInt32(req);
    return result;
  }
  static read(buff, offset) {
    return new _MessageBuffer(buff, offset);
  }
  get buffer() {
    return this.a;
  }
  constructor(buff, offset) {
    this.a = buff;
    this.b = offset;
  }
  static sizeUInt8() {
    return 1;
  }
  static {
    this.sizeUInt32 = 4;
  }
  writeUInt8(n) {
    this.a.writeUInt8(n, this.b);
    this.b += 1;
  }
  readUInt8() {
    const n = this.a.readUInt8(this.b);
    this.b += 1;
    return n;
  }
  writeUInt32(n) {
    this.a.writeUInt32BE(n, this.b);
    this.b += 4;
  }
  readUInt32() {
    const n = this.a.readUInt32BE(this.b);
    this.b += 4;
    return n;
  }
  static sizeShortString(str) {
    return 1 + str.byteLength;
  }
  writeShortString(str) {
    this.a.writeUInt8(str.byteLength, this.b);
    this.b += 1;
    this.a.set(str, this.b);
    this.b += str.byteLength;
  }
  readShortString() {
    const strByteLength = this.a.readUInt8(this.b);
    this.b += 1;
    const strBuff = this.a.slice(this.b, this.b + strByteLength);
    const str = strBuff.toString();
    this.b += strByteLength;
    return str;
  }
  static sizeLongString(str) {
    return 4 + str.byteLength;
  }
  writeLongString(str) {
    this.a.writeUInt32BE(str.byteLength, this.b);
    this.b += 4;
    this.a.set(str, this.b);
    this.b += str.byteLength;
  }
  readLongString() {
    const strByteLength = this.a.readUInt32BE(this.b);
    this.b += 4;
    const strBuff = this.a.slice(this.b, this.b + strByteLength);
    const str = strBuff.toString();
    this.b += strByteLength;
    return str;
  }
  writeBuffer(buff) {
    this.a.writeUInt32BE(buff.byteLength, this.b);
    this.b += 4;
    this.a.set(buff, this.b);
    this.b += buff.byteLength;
  }
  static sizeVSBuffer(buff) {
    return 4 + buff.byteLength;
  }
  writeVSBuffer(buff) {
    this.a.writeUInt32BE(buff.byteLength, this.b);
    this.b += 4;
    this.a.set(buff, this.b);
    this.b += buff.byteLength;
  }
  readVSBuffer() {
    const buffLength = this.a.readUInt32BE(this.b);
    this.b += 4;
    const buff = this.a.slice(this.b, this.b + buffLength);
    this.b += buffLength;
    return buff;
  }
  static sizeMixedArray(arr) {
    let size = 0;
    size += 1;
    for (let i = 0, len = arr.length; i < len; i++) {
      const el = arr[i];
      size += 1;
      switch (el.type) {
        case 1:
          size += this.sizeLongString(el.value);
          break;
        case 2:
          size += this.sizeVSBuffer(el.value);
          break;
        case 3:
          size += this.sizeUInt32;
          size += this.sizeLongString(el.value);
          for (let i2 = 0; i2 < el.buffers.length; ++i2) {
            size += this.sizeVSBuffer(el.buffers[i2]);
          }
          break;
        case 4:
          break;
      }
    }
    return size;
  }
  writeMixedArray(arr) {
    this.a.writeUInt8(arr.length, this.b);
    this.b += 1;
    for (let i = 0, len = arr.length; i < len; i++) {
      const el = arr[i];
      switch (el.type) {
        case 1:
          this.writeUInt8(
            1
            /* ArgType.String */
          );
          this.writeLongString(el.value);
          break;
        case 2:
          this.writeUInt8(
            2
            /* ArgType.VSBuffer */
          );
          this.writeVSBuffer(el.value);
          break;
        case 3:
          this.writeUInt8(
            3
            /* ArgType.SerializedObjectWithBuffers */
          );
          this.writeUInt32(el.buffers.length);
          this.writeLongString(el.value);
          for (let i2 = 0; i2 < el.buffers.length; ++i2) {
            this.writeBuffer(el.buffers[i2]);
          }
          break;
        case 4:
          this.writeUInt8(
            4
            /* ArgType.Undefined */
          );
          break;
      }
    }
  }
  readMixedArray() {
    const arrLen = this.a.readUInt8(this.b);
    this.b += 1;
    const arr = new Array(arrLen);
    for (let i = 0; i < arrLen; i++) {
      const argType = this.readUInt8();
      switch (argType) {
        case 1:
          arr[i] = this.readLongString();
          break;
        case 2:
          arr[i] = this.readVSBuffer();
          break;
        case 3: {
          const bufferCount = this.readUInt32();
          const jsonString = this.readLongString();
          const buffers = [];
          for (let i2 = 0; i2 < bufferCount; ++i2) {
            buffers.push(this.readVSBuffer());
          }
          arr[i] = new $ES($pnc(jsonString, buffers, null));
          break;
        }
        case 4:
          arr[i] = void 0;
          break;
      }
    }
    return arr;
  }
};
var SerializedRequestArgumentType;
(function(SerializedRequestArgumentType2) {
  SerializedRequestArgumentType2[SerializedRequestArgumentType2["Simple"] = 0] = "Simple";
  SerializedRequestArgumentType2[SerializedRequestArgumentType2["Mixed"] = 1] = "Mixed";
})(SerializedRequestArgumentType || (SerializedRequestArgumentType = {}));
var MessageIO = class {
  static a(arr) {
    for (let i = 0, len = arr.length; i < len; i++) {
      if (arr[i] instanceof $Ci) {
        return true;
      }
      if (arr[i] instanceof $ES) {
        return true;
      }
      if (typeof arr[i] === "undefined") {
        return true;
      }
    }
    return false;
  }
  static serializeRequestArguments(args2, replacer2) {
    if (this.a(args2)) {
      const massagedArgs = [];
      for (let i = 0, len = args2.length; i < len; i++) {
        const arg = args2[i];
        if (arg instanceof $Ci) {
          massagedArgs[i] = { type: 2, value: arg };
        } else if (typeof arg === "undefined") {
          massagedArgs[i] = {
            type: 4
            /* ArgType.Undefined */
          };
        } else if (arg instanceof $ES) {
          const { jsonString, referencedBuffers } = $onc(arg.value, replacer2);
          massagedArgs[i] = { type: 3, value: $Ci.fromString(jsonString), buffers: referencedBuffers };
        } else {
          massagedArgs[i] = { type: 1, value: $Ci.fromString(stringify(arg, replacer2)) };
        }
      }
      return {
        type: 1,
        args: massagedArgs
      };
    }
    return {
      type: 0,
      args: stringify(args2, replacer2)
    };
  }
  static serializeRequest(req, rpcId, method, serializedArgs, usesCancellationToken) {
    switch (serializedArgs.type) {
      case 0:
        return this.b(req, rpcId, method, serializedArgs.args, usesCancellationToken);
      case 1:
        return this.c(req, rpcId, method, serializedArgs.args, usesCancellationToken);
    }
  }
  static b(req, rpcId, method, args2, usesCancellationToken) {
    const methodBuff = $Ci.fromString(method);
    const argsBuff = $Ci.fromString(args2);
    let len = 0;
    len += MessageBuffer.sizeUInt8();
    len += MessageBuffer.sizeShortString(methodBuff);
    len += MessageBuffer.sizeLongString(argsBuff);
    const result = MessageBuffer.alloc(usesCancellationToken ? 2 : 1, req, len);
    result.writeUInt8(rpcId);
    result.writeShortString(methodBuff);
    result.writeLongString(argsBuff);
    return result.buffer;
  }
  static deserializeRequestJSONArgs(buff) {
    const rpcId = buff.readUInt8();
    const method = buff.readShortString();
    const args2 = buff.readLongString();
    return {
      rpcId,
      method,
      args: JSON.parse(args2)
    };
  }
  static c(req, rpcId, method, args2, usesCancellationToken) {
    const methodBuff = $Ci.fromString(method);
    let len = 0;
    len += MessageBuffer.sizeUInt8();
    len += MessageBuffer.sizeShortString(methodBuff);
    len += MessageBuffer.sizeMixedArray(args2);
    const result = MessageBuffer.alloc(usesCancellationToken ? 4 : 3, req, len);
    result.writeUInt8(rpcId);
    result.writeShortString(methodBuff);
    result.writeMixedArray(args2);
    return result.buffer;
  }
  static deserializeRequestMixedArgs(buff) {
    const rpcId = buff.readUInt8();
    const method = buff.readShortString();
    const rawargs = buff.readMixedArray();
    const args2 = new Array(rawargs.length);
    for (let i = 0, len = rawargs.length; i < len; i++) {
      const rawarg = rawargs[i];
      if (typeof rawarg === "string") {
        args2[i] = JSON.parse(rawarg);
      } else {
        args2[i] = rawarg;
      }
    }
    return {
      rpcId,
      method,
      args: args2
    };
  }
  static serializeAcknowledged(req) {
    return MessageBuffer.alloc(5, req, 0).buffer;
  }
  static serializeCancel(req) {
    return MessageBuffer.alloc(6, req, 0).buffer;
  }
  static serializeReplyOK(req, res, replacer2) {
    if (typeof res === "undefined") {
      return this.d(req);
    } else if (res instanceof $Ci) {
      return this.e(req, res);
    } else if (res instanceof $ES) {
      const { jsonString, referencedBuffers } = $onc(res.value, replacer2, true);
      return this.g(req, jsonString, referencedBuffers);
    } else {
      return this.f(req, safeStringify(res, replacer2));
    }
  }
  static d(req) {
    return MessageBuffer.alloc(7, req, 0).buffer;
  }
  static e(req, res) {
    let len = 0;
    len += MessageBuffer.sizeVSBuffer(res);
    const result = MessageBuffer.alloc(8, req, len);
    result.writeVSBuffer(res);
    return result.buffer;
  }
  static deserializeReplyOKVSBuffer(buff) {
    return buff.readVSBuffer();
  }
  static f(req, res) {
    const resBuff = $Ci.fromString(res);
    let len = 0;
    len += MessageBuffer.sizeLongString(resBuff);
    const result = MessageBuffer.alloc(9, req, len);
    result.writeLongString(resBuff);
    return result.buffer;
  }
  static g(req, res, buffers) {
    const resBuff = $Ci.fromString(res);
    let len = 0;
    len += MessageBuffer.sizeUInt32;
    len += MessageBuffer.sizeLongString(resBuff);
    for (const buffer of buffers) {
      len += MessageBuffer.sizeVSBuffer(buffer);
    }
    const result = MessageBuffer.alloc(10, req, len);
    result.writeUInt32(buffers.length);
    result.writeLongString(resBuff);
    for (const buffer of buffers) {
      result.writeBuffer(buffer);
    }
    return result.buffer;
  }
  static deserializeReplyOKJSON(buff) {
    const res = buff.readLongString();
    return JSON.parse(res);
  }
  static deserializeReplyOKJSONWithBuffers(buff, uriTransformer) {
    const bufferCount = buff.readUInt32();
    const res = buff.readLongString();
    const buffers = [];
    for (let i = 0; i < bufferCount; ++i) {
      buffers.push(buff.readVSBuffer());
    }
    return new $ES($pnc(res, buffers, uriTransformer));
  }
  static serializeReplyErr(req, err) {
    const errStr = err ? safeStringify($ib(err), null) : void 0;
    if (typeof errStr !== "string") {
      return this.h(req);
    }
    const errBuff = $Ci.fromString(errStr);
    let len = 0;
    len += MessageBuffer.sizeLongString(errBuff);
    const result = MessageBuffer.alloc(11, req, len);
    result.writeLongString(errBuff);
    return result.buffer;
  }
  static deserializeReplyErrError(buff) {
    const err = buff.readLongString();
    return JSON.parse(err);
  }
  static h(req) {
    return MessageBuffer.alloc(12, req, 0).buffer;
  }
};
var MessageType;
(function(MessageType3) {
  MessageType3[MessageType3["RequestJSONArgs"] = 1] = "RequestJSONArgs";
  MessageType3[MessageType3["RequestJSONArgsWithCancellation"] = 2] = "RequestJSONArgsWithCancellation";
  MessageType3[MessageType3["RequestMixedArgs"] = 3] = "RequestMixedArgs";
  MessageType3[MessageType3["RequestMixedArgsWithCancellation"] = 4] = "RequestMixedArgsWithCancellation";
  MessageType3[MessageType3["Acknowledged"] = 5] = "Acknowledged";
  MessageType3[MessageType3["Cancel"] = 6] = "Cancel";
  MessageType3[MessageType3["ReplyOKEmpty"] = 7] = "ReplyOKEmpty";
  MessageType3[MessageType3["ReplyOKVSBuffer"] = 8] = "ReplyOKVSBuffer";
  MessageType3[MessageType3["ReplyOKJSON"] = 9] = "ReplyOKJSON";
  MessageType3[MessageType3["ReplyOKJSONWithBuffers"] = 10] = "ReplyOKJSONWithBuffers";
  MessageType3[MessageType3["ReplyErrError"] = 11] = "ReplyErrError";
  MessageType3[MessageType3["ReplyErrEmpty"] = 12] = "ReplyErrEmpty";
})(MessageType || (MessageType = {}));
var ArgType;
(function(ArgType2) {
  ArgType2[ArgType2["String"] = 1] = "String";
  ArgType2[ArgType2["VSBuffer"] = 2] = "VSBuffer";
  ArgType2[ArgType2["SerializedObjectWithBuffers"] = 3] = "SerializedObjectWithBuffers";
  ArgType2[ArgType2["Undefined"] = 4] = "Undefined";
})(ArgType || (ArgType = {}));

// out-build/vs/base/common/errorMessage.js
function exceptionToErrorMessage(exception, verbose) {
  if (verbose && (exception.stack || exception.stacktrace)) {
    return localize(110, null, 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(111, null, exception.message);
  }
  return exception.message || localize(112, null);
}
function $1m(error = null, verbose = false) {
  if (!error) {
    return localize(113, null);
  }
  if (Array.isArray(error)) {
    const errors = $Mb(error);
    const msg = $1m(errors[0], verbose);
    if (errors.length > 1) {
      return localize(114, null, msg, errors.length);
    }
    return msg;
  }
  if ($zg(error)) {
    return error;
  }
  if (error.detail) {
    const detail = error.detail;
    if (detail.error) {
      return exceptionToErrorMessage(detail.error, verbose);
    }
    if (detail.exception) {
      return exceptionToErrorMessage(detail.exception, verbose);
    }
  }
  if (error.stack) {
    return exceptionToErrorMessage(error, verbose);
  }
  if (error.message) {
    return error.message;
  }
  return localize(115, null);
}

// out-build/vs/base/common/hash.js
function $Xi(obj) {
  return $Yi(obj, 0);
}
function $Yi(obj, hashVal) {
  switch (typeof obj) {
    case "object":
      if (obj === null) {
        return $Zi(349, hashVal);
      } else if (Array.isArray(obj)) {
        return arrayHash(obj, hashVal);
      }
      return objectHash(obj, hashVal);
    case "string":
      return $1i(obj, hashVal);
    case "boolean":
      return booleanHash(obj, hashVal);
    case "number":
      return $Zi(obj, hashVal);
    case "undefined":
      return $Zi(937, hashVal);
    default:
      return $Zi(617, hashVal);
  }
}
function $Zi(val, initialHashVal) {
  return (initialHashVal << 5) - initialHashVal + val | 0;
}
function booleanHash(b, initialHashVal) {
  return $Zi(b ? 433 : 863, initialHashVal);
}
function $1i(s, hashVal) {
  hashVal = $Zi(149417, hashVal);
  for (let i = 0, length = s.length; i < length; i++) {
    hashVal = $Zi(s.charCodeAt(i), hashVal);
  }
  return hashVal;
}
function arrayHash(arr, initialHashVal) {
  initialHashVal = $Zi(104579, initialHashVal);
  return arr.reduce((hashVal, item) => $Yi(item, hashVal), initialHashVal);
}
function objectHash(obj, initialHashVal) {
  initialHashVal = $Zi(181387, initialHashVal);
  return Object.keys(obj).sort().reduce((hashVal, key) => {
    hashVal = $1i(key, hashVal);
    return $Yi(obj[key], hashVal);
  }, initialHashVal);
}
var SHA1Constant;
(function(SHA1Constant2) {
  SHA1Constant2[SHA1Constant2["BLOCK_SIZE"] = 64] = "BLOCK_SIZE";
  SHA1Constant2[SHA1Constant2["UNICODE_REPLACEMENT"] = 65533] = "UNICODE_REPLACEMENT";
})(SHA1Constant || (SHA1Constant = {}));
function leftRotate(value, bits, totalBits = 32) {
  const delta2 = totalBits - bits;
  const mask = ~((1 << delta2) - 1);
  return (value << bits | (mask & value) >>> delta2) >>> 0;
}
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 (bufferOrValue >>> 0).toString(16).padStart(bitsize / 4, "0");
}
var $3i = class _$3i {
  static {
    this.g = new DataView(new ArrayBuffer(320));
  }
  // 80 * 4 = 320
  constructor() {
    this.h = 1732584193;
    this.l = 4023233417;
    this.m = 2562383102;
    this.n = 271733878;
    this.o = 3285377520;
    this.p = new Uint8Array(
      64 + 3
      /* to fit any utf-8 */
    );
    this.q = new DataView(this.p.buffer);
    this.r = 0;
    this.t = 0;
    this.u = 0;
    this.v = false;
  }
  update(str) {
    const strLen = str.length;
    if (strLen === 0) {
      return;
    }
    const buff = this.p;
    let buffLen = this.r;
    let leftoverHighSurrogate = this.u;
    let charCode;
    let offset;
    if (leftoverHighSurrogate !== 0) {
      charCode = leftoverHighSurrogate;
      offset = -1;
      leftoverHighSurrogate = 0;
    } else {
      charCode = str.charCodeAt(0);
      offset = 0;
    }
    while (true) {
      let codePoint = charCode;
      if ($5f(charCode)) {
        if (offset + 1 < strLen) {
          const nextCharCode = str.charCodeAt(offset + 1);
          if ($6f(nextCharCode)) {
            offset++;
            codePoint = $7f(charCode, nextCharCode);
          } else {
            codePoint = 65533;
          }
        } else {
          leftoverHighSurrogate = charCode;
          break;
        }
      } else if ($6f(charCode)) {
        codePoint = 65533;
      }
      buffLen = this.w(buff, buffLen, codePoint);
      offset++;
      if (offset < strLen) {
        charCode = str.charCodeAt(offset);
      } else {
        break;
      }
    }
    this.r = buffLen;
    this.u = leftoverHighSurrogate;
  }
  w(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.y();
      buffLen -= 64;
      this.t += 64;
      buff[0] = buff[64 + 0];
      buff[1] = buff[64 + 1];
      buff[2] = buff[64 + 2];
    }
    return buffLen;
  }
  digest() {
    if (!this.v) {
      this.v = true;
      if (this.u) {
        this.u = 0;
        this.r = this.w(
          this.p,
          this.r,
          65533
          /* SHA1Constant.UNICODE_REPLACEMENT */
        );
      }
      this.t += this.r;
      this.x();
    }
    return toHexString(this.h) + toHexString(this.l) + toHexString(this.m) + toHexString(this.n) + toHexString(this.o);
  }
  x() {
    this.p[this.r++] = 128;
    this.p.subarray(this.r).fill(0);
    if (this.r > 56) {
      this.y();
      this.p.fill(0);
    }
    const ml = 8 * this.t;
    this.q.setUint32(56, Math.floor(ml / 4294967296), false);
    this.q.setUint32(60, ml % 4294967296, false);
    this.y();
  }
  y() {
    const bigBlock32 = _$3i.g;
    const data = this.q;
    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.h;
    let b = this.l;
    let c = this.m;
    let d = this.n;
    let e = this.o;
    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.h = this.h + a & 4294967295;
    this.l = this.l + b & 4294967295;
    this.m = this.m + c & 4294967295;
    this.n = this.n + d & 4294967295;
    this.o = this.o + e & 4294967295;
  }
};

// out-build/vs/platform/contextkey/common/scanner.js
var TokenType;
(function(TokenType3) {
  TokenType3[TokenType3["LParen"] = 0] = "LParen";
  TokenType3[TokenType3["RParen"] = 1] = "RParen";
  TokenType3[TokenType3["Neg"] = 2] = "Neg";
  TokenType3[TokenType3["Eq"] = 3] = "Eq";
  TokenType3[TokenType3["NotEq"] = 4] = "NotEq";
  TokenType3[TokenType3["Lt"] = 5] = "Lt";
  TokenType3[TokenType3["LtEq"] = 6] = "LtEq";
  TokenType3[TokenType3["Gt"] = 7] = "Gt";
  TokenType3[TokenType3["GtEq"] = 8] = "GtEq";
  TokenType3[TokenType3["RegexOp"] = 9] = "RegexOp";
  TokenType3[TokenType3["RegexStr"] = 10] = "RegexStr";
  TokenType3[TokenType3["True"] = 11] = "True";
  TokenType3[TokenType3["False"] = 12] = "False";
  TokenType3[TokenType3["In"] = 13] = "In";
  TokenType3[TokenType3["Not"] = 14] = "Not";
  TokenType3[TokenType3["And"] = 15] = "And";
  TokenType3[TokenType3["Or"] = 16] = "Or";
  TokenType3[TokenType3["Str"] = 17] = "Str";
  TokenType3[TokenType3["QuotedStr"] = 18] = "QuotedStr";
  TokenType3[TokenType3["Error"] = 19] = "Error";
  TokenType3[TokenType3["EOF"] = 20] = "EOF";
})(TokenType || (TokenType = {}));
function hintDidYouMean(...meant) {
  switch (meant.length) {
    case 1:
      return localize(1724, null, meant[0]);
    case 2:
      return localize(1725, null, meant[0], meant[1]);
    case 3:
      return localize(1726, null, meant[0], meant[1], meant[2]);
    default:
      return void 0;
  }
}
var hintDidYouForgetToOpenOrCloseQuote = localize(1727, null);
var hintDidYouForgetToEscapeSlash = localize(1728, null);
var $4m = class _$4m {
  constructor() {
    this.c = "";
    this.d = 0;
    this.e = 0;
    this.f = [];
    this.g = [];
    this.m = /[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 $ob(`unhandled token type: ${JSON.stringify(token)}; have you forgotten to add a case?`);
    }
  }
  static {
    this.a = new Set(["i", "g", "s", "m", "y", "u"].map((ch) => ch.charCodeAt(0)));
  }
  static {
    this.b = /* @__PURE__ */ new Map([
      [
        "not",
        14
        /* TokenType.Not */
      ],
      [
        "in",
        13
        /* TokenType.In */
      ],
      [
        "false",
        12
        /* TokenType.False */
      ],
      [
        "true",
        11
        /* TokenType.True */
      ]
    ]);
  }
  get errors() {
    return this.g;
  }
  reset(value) {
    this.c = value;
    this.d = 0;
    this.e = 0;
    this.f = [];
    this.g = [];
    return this;
  }
  scan() {
    while (!this.r()) {
      this.d = this.e;
      const ch = this.i();
      switch (ch) {
        case 40:
          this.k(
            0
            /* TokenType.LParen */
          );
          break;
        case 41:
          this.k(
            1
            /* TokenType.RParen */
          );
          break;
        case 33:
          if (this.h(
            61
            /* CharCode.Equals */
          )) {
            const isTripleEq = this.h(
              61
              /* CharCode.Equals */
            );
            this.f.push({ type: 4, offset: this.d, isTripleEq });
          } else {
            this.k(
              2
              /* TokenType.Neg */
            );
          }
          break;
        case 39:
          this.o();
          break;
        case 47:
          this.q();
          break;
        case 61:
          if (this.h(
            61
            /* CharCode.Equals */
          )) {
            const isTripleEq = this.h(
              61
              /* CharCode.Equals */
            );
            this.f.push({ type: 3, offset: this.d, isTripleEq });
          } else if (this.h(
            126
            /* CharCode.Tilde */
          )) {
            this.k(
              9
              /* TokenType.RegexOp */
            );
          } else {
            this.l(hintDidYouMean("==", "=~"));
          }
          break;
        case 60:
          this.k(
            this.h(
              61
              /* CharCode.Equals */
            ) ? 6 : 5
            /* TokenType.Lt */
          );
          break;
        case 62:
          this.k(
            this.h(
              61
              /* CharCode.Equals */
            ) ? 8 : 7
            /* TokenType.Gt */
          );
          break;
        case 38:
          if (this.h(
            38
            /* CharCode.Ampersand */
          )) {
            this.k(
              15
              /* TokenType.And */
            );
          } else {
            this.l(hintDidYouMean("&&"));
          }
          break;
        case 124:
          if (this.h(
            124
            /* CharCode.Pipe */
          )) {
            this.k(
              16
              /* TokenType.Or */
            );
          } else {
            this.l(hintDidYouMean("||"));
          }
          break;
        case 32:
        case 13:
        case 9:
        case 10:
        case 160:
          break;
        default:
          this.n();
      }
    }
    this.d = this.e;
    this.k(
      20
      /* TokenType.EOF */
    );
    return Array.from(this.f);
  }
  h(expected) {
    if (this.r()) {
      return false;
    }
    if (this.c.charCodeAt(this.e) !== expected) {
      return false;
    }
    this.e++;
    return true;
  }
  i() {
    return this.c.charCodeAt(this.e++);
  }
  j() {
    return this.r() ? 0 : this.c.charCodeAt(this.e);
  }
  k(type) {
    this.f.push({ type, offset: this.d });
  }
  l(additional) {
    const offset = this.d;
    const lexeme = this.c.substring(this.d, this.e);
    const errToken = { type: 19, offset: this.d, lexeme };
    this.g.push({ offset, lexeme, additionalInfo: additional });
    this.f.push(errToken);
  }
  n() {
    this.m.lastIndex = this.d;
    const match = this.m.exec(this.c);
    if (match) {
      this.e = this.d + match[0].length;
      const lexeme = this.c.substring(this.d, this.e);
      const keyword = _$4m.b.get(lexeme);
      if (keyword) {
        this.k(keyword);
      } else {
        this.f.push({ type: 17, lexeme, offset: this.d });
      }
    }
  }
  // captures the lexeme without the leading and trailing '
  o() {
    while (this.j() !== 39 && !this.r()) {
      this.i();
    }
    if (this.r()) {
      this.l(hintDidYouForgetToOpenOrCloseQuote);
      return;
    }
    this.i();
    this.f.push({ type: 18, lexeme: this.c.substring(this.d + 1, this.e - 1), offset: this.d + 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:///`
   */
  q() {
    let p = this.e;
    let inEscape = false;
    let inCharacterClass = false;
    while (true) {
      if (p >= this.c.length) {
        this.e = p;
        this.l(hintDidYouForgetToEscapeSlash);
        return;
      }
      const ch = this.c.charCodeAt(p);
      if (inEscape) {
        inEscape = false;
      } else if (ch === 47 && !inCharacterClass) {
        p++;
        break;
      } else if (ch === 91) {
        inCharacterClass = true;
      } else if (ch === 92) {
        inEscape = true;
      } else if (ch === 93) {
        inCharacterClass = false;
      }
      p++;
    }
    while (p < this.c.length && _$4m.a.has(this.c.charCodeAt(p))) {
      p++;
    }
    this.e = p;
    const lexeme = this.c.substring(this.d, this.e);
    this.f.push({ type: 10, lexeme, offset: this.d });
  }
  r() {
    return this.e >= this.c.length;
  }
};

// out-build/vs/platform/instantiation/common/instantiation.js
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 = {}));
var $Pk = $Qk("instantiationService");
function storeServiceDependency(id2, target, index) {
  if (target[_util.DI_TARGET] === target) {
    target[_util.DI_DEPENDENCIES].push({ id: id2, index });
  } else {
    target[_util.DI_DEPENDENCIES] = [{ id: id2, index }];
    target[_util.DI_TARGET] = target;
  }
}
function $Qk(serviceId) {
  if (_util.serviceIds.has(serviceId)) {
    return _util.serviceIds.get(serviceId);
  }
  const id2 = function(target, key, index) {
    if (arguments.length !== 3) {
      throw new Error("@IServiceName-decorator can only be used to decorate a parameter");
    }
    storeServiceDependency(id2, target, index);
  };
  id2.toString = () => serviceId;
  _util.serviceIds.set(serviceId, id2);
  return id2;
}
function $Rk(serviceIdentifier) {
  return serviceIdentifier;
}

// out-build/vs/platform/contextkey/common/contextkey.js
var CONSTANT_VALUES = /* @__PURE__ */ new Map();
CONSTANT_VALUES.set("false", false);
CONSTANT_VALUES.set("true", true);
CONSTANT_VALUES.set("isMac", $m);
CONSTANT_VALUES.set("isLinux", $n);
CONSTANT_VALUES.set("isWindows", $l);
CONSTANT_VALUES.set("isWeb", $r);
CONSTANT_VALUES.set("isMacNative", $m && !$r);
CONSTANT_VALUES.set("isEdge", $K);
CONSTANT_VALUES.set("isFirefox", $I);
CONSTANT_VALUES.set("isChrome", $H);
CONSTANT_VALUES.set("isSafari", $J);
var hasOwnProperty2 = Object.prototype.hasOwnProperty;
var ContextKeyExprType;
(function(ContextKeyExprType2) {
  ContextKeyExprType2[ContextKeyExprType2["False"] = 0] = "False";
  ContextKeyExprType2[ContextKeyExprType2["True"] = 1] = "True";
  ContextKeyExprType2[ContextKeyExprType2["Defined"] = 2] = "Defined";
  ContextKeyExprType2[ContextKeyExprType2["Not"] = 3] = "Not";
  ContextKeyExprType2[ContextKeyExprType2["Equals"] = 4] = "Equals";
  ContextKeyExprType2[ContextKeyExprType2["NotEquals"] = 5] = "NotEquals";
  ContextKeyExprType2[ContextKeyExprType2["And"] = 6] = "And";
  ContextKeyExprType2[ContextKeyExprType2["Regex"] = 7] = "Regex";
  ContextKeyExprType2[ContextKeyExprType2["NotRegex"] = 8] = "NotRegex";
  ContextKeyExprType2[ContextKeyExprType2["Or"] = 9] = "Or";
  ContextKeyExprType2[ContextKeyExprType2["In"] = 10] = "In";
  ContextKeyExprType2[ContextKeyExprType2["NotIn"] = 11] = "NotIn";
  ContextKeyExprType2[ContextKeyExprType2["Greater"] = 12] = "Greater";
  ContextKeyExprType2[ContextKeyExprType2["GreaterEquals"] = 13] = "GreaterEquals";
  ContextKeyExprType2[ContextKeyExprType2["Smaller"] = 14] = "Smaller";
  ContextKeyExprType2[ContextKeyExprType2["SmallerEquals"] = 15] = "SmallerEquals";
})(ContextKeyExprType || (ContextKeyExprType = {}));
var defaultConfig = {
  regexParsingWithErrorRecovery: true
};
var errorEmptyString = localize(1704, null);
var hintEmptyString = localize(1705, null);
var errorNoInAfterNot = localize(1706, null);
var errorClosingParenthesis = localize(1707, null);
var errorUnexpectedToken = localize(1708, null);
var hintUnexpectedToken = localize(1709, null);
var errorUnexpectedEOF = localize(1710, null);
var hintUnexpectedEOF = localize(1711, null);
var $6m = class _$6m {
  static {
    this.c = new Error();
  }
  get lexingErrors() {
    return this.d.errors;
  }
  get parsingErrors() {
    return this.h;
  }
  constructor(k = defaultConfig) {
    this.k = k;
    this.d = new $4m();
    this.f = [];
    this.g = 0;
    this.h = [];
    this.v = /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(input) {
    if (input === "") {
      this.h.push({ message: errorEmptyString, offset: 0, lexeme: "", additionalInfo: hintEmptyString });
      return void 0;
    }
    this.f = this.d.reset(input).scan();
    this.g = 0;
    this.h = [];
    try {
      const expr = this.l();
      if (!this.E()) {
        const peek = this.D();
        const additionalInfo = peek.type === 17 ? hintUnexpectedToken : void 0;
        this.h.push({ message: errorUnexpectedToken, offset: peek.offset, lexeme: $4m.getLexeme(peek), additionalInfo });
        throw _$6m.c;
      }
      return expr;
    } catch (e) {
      if (!(e === _$6m.c)) {
        throw e;
      }
      return void 0;
    }
  }
  l() {
    return this.m();
  }
  m() {
    const expr = [this.o()];
    while (this.y(
      16
      /* TokenType.Or */
    )) {
      const right = this.o();
      expr.push(right);
    }
    return expr.length === 1 ? expr[0] : $7m.or(...expr);
  }
  o() {
    const expr = [this.s()];
    while (this.y(
      15
      /* TokenType.And */
    )) {
      const right = this.s();
      expr.push(right);
    }
    return expr.length === 1 ? expr[0] : $7m.and(...expr);
  }
  s() {
    if (this.y(
      2
      /* TokenType.Neg */
    )) {
      const peek = this.D();
      switch (peek.type) {
        case 11:
          this.z();
          return $0m.INSTANCE;
        case 12:
          this.z();
          return $$m.INSTANCE;
        case 0: {
          this.z();
          const expr = this.l();
          this.A(1, errorClosingParenthesis);
          return expr?.negate();
        }
        case 17:
          this.z();
          return $en.create(peek.lexeme);
        default:
          throw this.B(`KEY | true | false | '(' expression ')'`, peek);
      }
    }
    return this.t();
  }
  t() {
    const peek = this.D();
    switch (peek.type) {
      case 11:
        this.z();
        return $7m.true();
      case 12:
        this.z();
        return $7m.false();
      case 0: {
        this.z();
        const expr = this.l();
        this.A(1, errorClosingParenthesis);
        return expr;
      }
      case 17: {
        const key = peek.lexeme;
        this.z();
        if (this.y(
          9
          /* TokenType.RegexOp */
        )) {
          const expr = this.D();
          if (!this.k.regexParsingWithErrorRecovery) {
            this.z();
            if (expr.type !== 10) {
              throw this.B(`REGEX`, expr);
            }
            const regexLexeme = expr.lexeme;
            const closingSlashIndex = regexLexeme.lastIndexOf("/");
            const flags = closingSlashIndex === regexLexeme.length - 1 ? void 0 : this.w(regexLexeme.substring(closingSlashIndex + 1));
            let regexp;
            try {
              regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
            } catch (e) {
              throw this.B(`REGEX`, expr);
            }
            return $jn.create(key, regexp);
          }
          switch (expr.type) {
            case 10:
            case 19: {
              const lexemeReconstruction = [expr.lexeme];
              this.z();
              let followingToken = this.D();
              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.E() && 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($4m.getLexeme(followingToken));
                this.z();
                followingToken = this.D();
              }
              const regexLexeme = lexemeReconstruction.join("");
              const closingSlashIndex = regexLexeme.lastIndexOf("/");
              const flags = closingSlashIndex === regexLexeme.length - 1 ? void 0 : this.w(regexLexeme.substring(closingSlashIndex + 1));
              let regexp;
              try {
                regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
              } catch (e) {
                throw this.B(`REGEX`, expr);
              }
              return $7m.regex(key, regexp);
            }
            case 18: {
              const serializedValue = expr.lexeme;
              this.z();
              let regex = null;
              if (!$vf(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 (_e) {
                    throw this.B(`REGEX`, expr);
                  }
                }
              }
              if (regex === null) {
                throw this.B("REGEX", expr);
              }
              return $jn.create(key, regex);
            }
            default:
              throw this.B("REGEX", this.D());
          }
        }
        if (this.y(
          14
          /* TokenType.Not */
        )) {
          this.A(13, errorNoInAfterNot);
          const right = this.u();
          return $7m.notIn(key, right);
        }
        const maybeOp = this.D().type;
        switch (maybeOp) {
          case 3: {
            this.z();
            const right = this.u();
            if (this.x().type === 18) {
              return $7m.equals(key, right);
            }
            switch (right) {
              case "true":
                return $7m.has(key);
              case "false":
                return $7m.not(key);
              default:
                return $7m.equals(key, right);
            }
          }
          case 4: {
            this.z();
            const right = this.u();
            if (this.x().type === 18) {
              return $7m.notEquals(key, right);
            }
            switch (right) {
              case "true":
                return $7m.not(key);
              case "false":
                return $7m.has(key);
              default:
                return $7m.notEquals(key, right);
            }
          }
          case 5:
            this.z();
            return $hn.create(key, this.u());
          case 6:
            this.z();
            return $in.create(key, this.u());
          case 7:
            this.z();
            return $fn.create(key, this.u());
          case 8:
            this.z();
            return $gn.create(key, this.u());
          case 13:
            this.z();
            return $7m.in(key, this.u());
          default:
            return $7m.has(key);
        }
      }
      case 20:
        this.h.push({ message: errorUnexpectedEOF, offset: peek.offset, lexeme: "", additionalInfo: hintUnexpectedEOF });
        throw _$6m.c;
      default:
        throw this.B(`true | false | KEY 
	| KEY '=~' REGEX 
	| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`, this.D());
    }
  }
  u() {
    const token = this.D();
    switch (token.type) {
      case 17:
      case 18:
        this.z();
        return token.lexeme;
      case 11:
        this.z();
        return "true";
      case 12:
        this.z();
        return "false";
      case 13:
        this.z();
        return "in";
      default:
        return "";
    }
  }
  w(flags) {
    return flags.replaceAll(this.v, "");
  }
  // careful: this can throw if current token is the initial one (ie index = 0)
  x() {
    return this.f[this.g - 1];
  }
  y(token) {
    if (this.C(token)) {
      this.z();
      return true;
    }
    return false;
  }
  z() {
    if (!this.E()) {
      this.g++;
    }
    return this.x();
  }
  A(type, message) {
    if (this.C(type)) {
      return this.z();
    }
    throw this.B(message, this.D());
  }
  B(expected, got, additionalInfo) {
    const message = localize(1712, null, expected, $4m.getLexeme(got));
    const offset = got.offset;
    const lexeme = $4m.getLexeme(got);
    this.h.push({ message, offset, lexeme, additionalInfo });
    return _$6m.c;
  }
  C(type) {
    return this.D().type === type;
  }
  D() {
    return this.f[this.g];
  }
  E() {
    return this.D().type === 20;
  }
};
var $7m = class {
  static false() {
    return $0m.INSTANCE;
  }
  static true() {
    return $$m.INSTANCE;
  }
  static has(key) {
    return $_m.create(key);
  }
  static equals(key, value) {
    return $an.create(key, value);
  }
  static notEquals(key, value) {
    return $dn.create(key, value);
  }
  static regex(key, value) {
    return $jn.create(key, value);
  }
  static in(key, value) {
    return $bn.create(key, value);
  }
  static notIn(key, value) {
    return $cn.create(key, value);
  }
  static not(key) {
    return $en.create(key);
  }
  static and(...expr) {
    return $ln.create(expr, null, true);
  }
  static or(...expr) {
    return $mn.create(expr, null, true);
  }
  static greater(key, value) {
    return $fn.create(key, value);
  }
  static greaterEquals(key, value) {
    return $gn.create(key, value);
  }
  static smaller(key, value) {
    return $hn.create(key, value);
  }
  static smallerEquals(key, value) {
    return $in.create(key, value);
  }
  static {
    this.c = new $6m({ regexParsingWithErrorRecovery: false });
  }
  static deserialize(serialized) {
    if (serialized === void 0 || serialized === null) {
      return void 0;
    }
    const expr = this.c.parse(serialized);
    return expr;
  }
};
function $8m(whenClauses) {
  const parser2 = new $6m({ regexParsingWithErrorRecovery: false });
  return whenClauses.map((whenClause) => {
    parser2.parse(whenClause);
    if (parser2.lexingErrors.length > 0) {
      return parser2.lexingErrors.map((se) => ({
        errorMessage: se.additionalInfo ? localize(1713, null, se.additionalInfo) : localize(1714, null),
        offset: se.offset,
        length: se.lexeme.length
      }));
    } else if (parser2.parsingErrors.length > 0) {
      return parser2.parsingErrors.map((pe) => ({
        errorMessage: pe.additionalInfo ? `${pe.message}. ${pe.additionalInfo}` : pe.message,
        offset: pe.offset,
        length: pe.lexeme.length
      }));
    } else {
      return [];
    }
  });
}
function cmp(a, b) {
  return a.cmp(b);
}
var $0m = class _$0m {
  static {
    this.INSTANCE = new _$0m();
  }
  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 [];
  }
  map(mapFnc) {
    return this;
  }
  negate() {
    return $$m.INSTANCE;
  }
};
var $$m = class _$$m {
  static {
    this.INSTANCE = new _$$m();
  }
  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 [];
  }
  map(mapFnc) {
    return this;
  }
  negate() {
    return $0m.INSTANCE;
  }
};
var $_m = class _$_m {
  static create(key, negated = null) {
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      return constantValue ? $$m.INSTANCE : $0m.INSTANCE;
    }
    return new _$_m(key, negated);
  }
  constructor(key, c) {
    this.key = key;
    this.c = c;
    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 ? $$m.INSTANCE : $0m.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return !!context.getValue(this.key);
  }
  serialize() {
    return this.key;
  }
  keys() {
    return [this.key];
  }
  map(mapFnc) {
    return mapFnc.mapDefined(this.key);
  }
  negate() {
    if (!this.c) {
      this.c = $en.create(this.key, this);
    }
    return this.c;
  }
};
var $an = class _$an {
  static create(key, value, negated = null) {
    if (typeof value === "boolean") {
      return value ? $_m.create(key, negated) : $en.create(key, negated);
    }
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      const trueValue = constantValue ? "true" : "false";
      return value === trueValue ? $$m.INSTANCE : $0m.INSTANCE;
    }
    return new _$an(key, value, negated);
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 4;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.c);
    if (typeof constantValue === "boolean") {
      const trueValue = constantValue ? "true" : "false";
      return this.d === trueValue ? $$m.INSTANCE : $0m.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return context.getValue(this.c) == this.d;
  }
  serialize() {
    return `${this.c} == '${this.d}'`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapEquals(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $dn.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $bn = class _$bn {
  static create(key, valueKey) {
    return new _$bn(key, valueKey);
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.type = 10;
    this.c = null;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.d, this.f, other.d, other.f);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.d === other.d && this.f === other.f;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    const source = context.getValue(this.f);
    const item = context.getValue(this.d);
    if (Array.isArray(source)) {
      return source.includes(item);
    }
    if (typeof item === "string" && typeof source === "object" && source !== null) {
      return hasOwnProperty2.call(source, item);
    }
    return false;
  }
  serialize() {
    return `${this.d} in '${this.f}'`;
  }
  keys() {
    return [this.d, this.f];
  }
  map(mapFnc) {
    return mapFnc.mapIn(this.d, this.f);
  }
  negate() {
    if (!this.c) {
      this.c = $cn.create(this.d, this.f);
    }
    return this.c;
  }
};
var $cn = class _$cn {
  static create(key, valueKey) {
    return new _$cn(key, valueKey);
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.type = 11;
    this.c = $bn.create(d, f);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return this.c.cmp(other.c);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c.equals(other.c);
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return !this.c.evaluate(context);
  }
  serialize() {
    return `${this.d} not in '${this.f}'`;
  }
  keys() {
    return this.c.keys();
  }
  map(mapFnc) {
    return mapFnc.mapNotIn(this.d, this.f);
  }
  negate() {
    return this.c;
  }
};
var $dn = class _$dn {
  static create(key, value, negated = null) {
    if (typeof value === "boolean") {
      if (value) {
        return $en.create(key, negated);
      }
      return $_m.create(key, negated);
    }
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      const falseValue = constantValue ? "true" : "false";
      return value === falseValue ? $0m.INSTANCE : $$m.INSTANCE;
    }
    return new _$dn(key, value, negated);
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 5;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.c);
    if (typeof constantValue === "boolean") {
      const falseValue = constantValue ? "true" : "false";
      return this.d === falseValue ? $0m.INSTANCE : $$m.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return context.getValue(this.c) != this.d;
  }
  serialize() {
    return `${this.c} != '${this.d}'`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapNotEquals(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $an.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $en = class _$en {
  static create(key, negated = null) {
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      return constantValue ? $0m.INSTANCE : $$m.INSTANCE;
    }
    return new _$en(key, negated);
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.type = 3;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp1(this.c, other.c);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.c);
    if (typeof constantValue === "boolean") {
      return constantValue ? $0m.INSTANCE : $$m.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return !context.getValue(this.c);
  }
  serialize() {
    return `!${this.c}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapNot(this.c);
  }
  negate() {
    if (!this.d) {
      this.d = $_m.create(this.c, this);
    }
    return this.d;
  }
};
function withFloatOrStr(value, callback) {
  if (typeof value === "string") {
    const n = parseFloat(value);
    if (!isNaN(n)) {
      value = n;
    }
  }
  if (typeof value === "string" || typeof value === "number") {
    return callback(value);
  }
  return $0m.INSTANCE;
}
var $fn = class _$fn {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$fn(key, value, negated));
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 12;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.d === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.c)) > this.d;
  }
  serialize() {
    return `${this.c} > ${this.d}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapGreater(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $in.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $gn = class _$gn {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$gn(key, value, negated));
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 13;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.d === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.c)) >= this.d;
  }
  serialize() {
    return `${this.c} >= ${this.d}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapGreaterEquals(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $hn.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $hn = class _$hn {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$hn(key, value, negated));
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 14;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.d === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.c)) < this.d;
  }
  serialize() {
    return `${this.c} < ${this.d}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapSmaller(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $gn.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $in = class _$in {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$in(key, value, negated));
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.type = 15;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.c, this.d, other.c, other.d);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c === other.c && this.d === other.d;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.d === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.c)) <= this.d;
  }
  serialize() {
    return `${this.c} <= ${this.d}`;
  }
  keys() {
    return [this.c];
  }
  map(mapFnc) {
    return mapFnc.mapSmallerEquals(this.c, this.d);
  }
  negate() {
    if (!this.f) {
      this.f = $fn.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $jn = class _$jn {
  static create(key, regexp) {
    return new _$jn(key, regexp);
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.type = 7;
    this.c = null;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.d < other.d) {
      return -1;
    }
    if (this.d > other.d) {
      return 1;
    }
    const thisSource = this.f ? this.f.source : "";
    const otherSource = other.f ? other.f.source : "";
    if (thisSource < otherSource) {
      return -1;
    }
    if (thisSource > otherSource) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      const thisSource = this.f ? this.f.source : "";
      const otherSource = other.f ? other.f.source : "";
      return this.d === other.d && thisSource === otherSource;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    const value = context.getValue(this.d);
    return this.f ? this.f.test(value) : false;
  }
  serialize() {
    const value = this.f ? `/${this.f.source}/${this.f.flags}` : "/invalid/";
    return `${this.d} =~ ${value}`;
  }
  keys() {
    return [this.d];
  }
  map(mapFnc) {
    return mapFnc.mapRegex(this.d, this.f);
  }
  negate() {
    if (!this.c) {
      this.c = $kn.create(this);
    }
    return this.c;
  }
};
var $kn = class _$kn {
  static create(actual) {
    return new _$kn(actual);
  }
  constructor(c) {
    this.c = c;
    this.type = 8;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return this.c.cmp(other.c);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.c.equals(other.c);
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return !this.c.evaluate(context);
  }
  serialize() {
    return `!(${this.c.serialize()})`;
  }
  keys() {
    return this.c.keys();
  }
  map(mapFnc) {
    return new _$kn(this.c.map(mapFnc));
  }
  negate() {
    return this.c;
  }
};
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;
}
var $ln = class _$ln {
  static create(_expr, negated, extraRedundantCheck) {
    return _$ln.d(_expr, negated, extraRedundantCheck);
  }
  constructor(expr, c) {
    this.expr = expr;
    this.c = c;
    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 _$ln.create(exprArr, this.c, 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 d(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 $0m.INSTANCE;
      }
      if (e.type === 6) {
        expr.push(...e.expr);
        continue;
      }
      expr.push(e);
    }
    if (expr.length === 0 && hasTrue) {
      return $$m.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 = $mn.create(lastElement.expr.map((el) => _$ln.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 $0m.INSTANCE;
          }
        }
      }
      if (expr.length === 1) {
        return expr[0];
      }
    }
    return new _$ln(expr, negated);
  }
  serialize() {
    return this.expr.map((e) => e.serialize()).join(" && ");
  }
  keys() {
    const result = [];
    for (const expr of this.expr) {
      result.push(...expr.keys());
    }
    return result;
  }
  map(mapFnc) {
    return new _$ln(this.expr.map((expr) => expr.map(mapFnc)), null);
  }
  negate() {
    if (!this.c) {
      const result = [];
      for (const expr of this.expr) {
        result.push(expr.negate());
      }
      this.c = $mn.create(result, this, true);
    }
    return this.c;
  }
};
var $mn = class _$mn {
  static create(_expr, negated, extraRedundantCheck) {
    return _$mn.d(_expr, negated, extraRedundantCheck);
  }
  constructor(expr, c) {
    this.expr = expr;
    this.c = c;
    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 _$mn.create(exprArr, this.c, 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 d(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 $$m.INSTANCE;
        }
        if (e.type === 9) {
          expr = expr.concat(e.expr);
          continue;
        }
        expr.push(e);
      }
      if (expr.length === 0 && hasFalse) {
        return $0m.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 $$m.INSTANCE;
          }
        }
      }
      if (expr.length === 1) {
        return expr[0];
      }
    }
    return new _$mn(expr, negated);
  }
  serialize() {
    return this.expr.map((e) => e.serialize()).join(" || ");
  }
  keys() {
    const result = [];
    for (const expr of this.expr) {
      result.push(...expr.keys());
    }
    return result;
  }
  map(mapFnc) {
    return new _$mn(this.expr.map((expr) => expr.map(mapFnc)), null);
  }
  negate() {
    if (!this.c) {
      const result = [];
      for (const expr of this.expr) {
        result.push(expr.negate());
      }
      while (result.length > 1) {
        const LEFT = result.shift();
        const RIGHT = result.shift();
        const all = [];
        for (const left of getTerminals(LEFT)) {
          for (const right of getTerminals(RIGHT)) {
            all.push($ln.create([left, right], null, false));
          }
        }
        result.unshift(_$mn.create(all, null, false));
      }
      this.c = _$mn.create(result, this, true);
    }
    return this.c;
  }
};
var $nn = class _$nn extends $_m {
  static {
    this.d = [];
  }
  static all() {
    return _$nn.d.values();
  }
  constructor(key, defaultValue, metaOrHide) {
    super(key, null);
    this.f = defaultValue;
    if (typeof metaOrHide === "object") {
      _$nn.d.push({ ...metaOrHide, key });
    } else if (metaOrHide !== true) {
      _$nn.d.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== void 0 ? typeof defaultValue : void 0 });
    }
  }
  bindTo(target) {
    return target.createKey(this.key, this.f);
  }
  getValue(target) {
    return target.getContextKeyValue(this.key);
  }
  toNegated() {
    return this.negate();
  }
  isEqualTo(value) {
    return $an.create(this.key, value);
  }
  notEqualsTo(value) {
    return $dn.create(this.key, value);
  }
};
var $on = $Qk("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 getTerminals(node) {
  if (node.type === 9) {
    return node.expr;
  }
  return [node];
}

// out-build/vs/platform/log/common/log.js
var $wn = $Qk("logService");
var $xn = $Qk("loggerService");
function $yn(thing) {
  return $Dg(thing);
}
var LogLevel;
(function(LogLevel3) {
  LogLevel3[LogLevel3["Off"] = 0] = "Off";
  LogLevel3[LogLevel3["Trace"] = 1] = "Trace";
  LogLevel3[LogLevel3["Debug"] = 2] = "Debug";
  LogLevel3[LogLevel3["Info"] = 3] = "Info";
  LogLevel3[LogLevel3["Warning"] = 4] = "Warning";
  LogLevel3[LogLevel3["Error"] = 5] = "Error";
})(LogLevel || (LogLevel = {}));
var $zn = LogLevel.Info;
function log(logger, level, message) {
  switch (level) {
    case LogLevel.Trace:
      logger.trace(message);
      break;
    case LogLevel.Debug:
      logger.debug(message);
      break;
    case LogLevel.Info:
      logger.info(message);
      break;
    case LogLevel.Warning:
      logger.warn(message);
      break;
    case LogLevel.Error:
      logger.error(message);
      break;
    case LogLevel.Off:
      break;
    default:
      throw new Error(`Invalid log level ${level}`);
  }
}
function format(args2, verbose = false) {
  let result = "";
  for (let i = 0; i < args2.length; i++) {
    let a = args2[i];
    if (a instanceof Error) {
      a = $1m(a, verbose);
    }
    if (typeof a === "object") {
      try {
        a = JSON.stringify(a);
      } catch (e) {
      }
    }
    result += (i > 0 ? " " : "") + a;
  }
  return result;
}
var $Bn = class extends $3c {
  constructor() {
    super(...arguments);
    this.b = $zn;
    this.c = this.B(new $ze());
    this.onDidChangeLogLevel = this.c.event;
  }
  setLevel(level) {
    if (this.b !== level) {
      this.b = level;
      this.c.fire(this.b);
    }
  }
  getLevel() {
    return this.b;
  }
  f(level) {
    return this.b !== LogLevel.Off && this.b <= level;
  }
  g(level) {
    if (this.q.isDisposed) {
      return false;
    }
    return this.f(level);
  }
};
var $Cn = class extends $Bn {
  constructor(h) {
    super();
    this.h = h;
  }
  f(level) {
    return this.h || super.f(level);
  }
  trace(message, ...args2) {
    if (this.g(LogLevel.Trace)) {
      this.m(LogLevel.Trace, format([message, ...args2], true));
    }
  }
  debug(message, ...args2) {
    if (this.g(LogLevel.Debug)) {
      this.m(LogLevel.Debug, format([message, ...args2]));
    }
  }
  info(message, ...args2) {
    if (this.g(LogLevel.Info)) {
      this.m(LogLevel.Info, format([message, ...args2]));
    }
  }
  warn(message, ...args2) {
    if (this.g(LogLevel.Warning)) {
      this.m(LogLevel.Warning, format([message, ...args2]));
    }
  }
  error(message, ...args2) {
    if (this.g(LogLevel.Error)) {
      if (message instanceof Error) {
        const array = Array.prototype.slice.call(arguments);
        array[0] = message.stack;
        this.m(LogLevel.Error, format(array));
      } else {
        this.m(LogLevel.Error, format([message, ...args2]));
      }
    }
  }
  flush() {
  }
};
var $Gn = class extends $Bn {
  constructor(h) {
    super();
    this.h = h;
    if (h.length) {
      this.setLevel(h[0].getLevel());
    }
  }
  setLevel(level) {
    for (const logger of this.h) {
      logger.setLevel(level);
    }
    super.setLevel(level);
  }
  trace(message, ...args2) {
    for (const logger of this.h) {
      logger.trace(message, ...args2);
    }
  }
  debug(message, ...args2) {
    for (const logger of this.h) {
      logger.debug(message, ...args2);
    }
  }
  info(message, ...args2) {
    for (const logger of this.h) {
      logger.info(message, ...args2);
    }
  }
  warn(message, ...args2) {
    for (const logger of this.h) {
      logger.warn(message, ...args2);
    }
  }
  error(message, ...args2) {
    for (const logger of this.h) {
      logger.error(message, ...args2);
    }
  }
  flush() {
    for (const logger of this.h) {
      logger.flush();
    }
  }
  dispose() {
    for (const logger of this.h) {
      logger.dispose();
    }
    super.dispose();
  }
};
var $Hn = class extends $3c {
  constructor(h, j, loggerResources) {
    super();
    this.h = h;
    this.j = j;
    this.b = new $Ec();
    this.c = this.B(new $ze());
    this.onDidChangeLoggers = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeLogLevel = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeVisibility = this.g.event;
    if (loggerResources) {
      for (const loggerResource of loggerResources) {
        this.b.set(loggerResource.resource, { logger: void 0, info: loggerResource });
      }
    }
  }
  m(resourceOrId) {
    if ($zg(resourceOrId)) {
      return [...this.b.values()].find((logger) => logger.info.id === resourceOrId);
    }
    return this.b.get(resourceOrId);
  }
  getLogger(resourceOrId) {
    return this.m(resourceOrId)?.logger;
  }
  createLogger(idOrResource, options2) {
    const resource = this.n(idOrResource);
    const id2 = $zg(idOrResource) ? idOrResource : options2?.id ?? $Xi(resource.toString()).toString(16);
    let logger = this.b.get(resource)?.logger;
    const logLevel = options2?.logLevel === "always" ? LogLevel.Trace : options2?.logLevel;
    if (!logger) {
      logger = this.s(resource, logLevel ?? this.getLogLevel(resource) ?? this.h, { ...options2, id: id2 });
    }
    const loggerEntry = {
      logger,
      info: { resource, id: id2, logLevel, name: options2?.name, hidden: options2?.hidden, extensionId: options2?.extensionId, when: options2?.when }
    };
    this.registerLogger(loggerEntry.info);
    this.b.set(resource, loggerEntry);
    return logger;
  }
  n(idOrResource) {
    return $zg(idOrResource) ? $vh(this.j, `${idOrResource}.log`) : idOrResource;
  }
  setLogLevel(arg1, arg2) {
    if (URI.isUri(arg1)) {
      const resource = arg1;
      const logLevel = arg2;
      const logger = this.b.get(resource);
      if (logger && logLevel !== logger.info.logLevel) {
        logger.info.logLevel = logLevel === this.h ? void 0 : logLevel;
        logger.logger?.setLevel(logLevel);
        this.b.set(logger.info.resource, logger);
        this.f.fire([resource, logLevel]);
      }
    } else {
      this.h = arg1;
      for (const [resource, logger] of this.b.entries()) {
        if (this.b.get(resource)?.info.logLevel === void 0) {
          logger.logger?.setLevel(this.h);
        }
      }
      this.f.fire(this.h);
    }
  }
  setVisibility(resourceOrId, visibility) {
    const logger = this.m(resourceOrId);
    if (logger && visibility !== !logger.info.hidden) {
      logger.info.hidden = !visibility;
      this.b.set(logger.info.resource, logger);
      this.g.fire([logger.info.resource, visibility]);
    }
  }
  getLogLevel(resource) {
    let logLevel;
    if (resource) {
      logLevel = this.b.get(resource)?.info.logLevel;
    }
    return logLevel ?? this.h;
  }
  registerLogger(resource) {
    const existing = this.b.get(resource.resource);
    if (existing) {
      if (existing.info.hidden !== resource.hidden) {
        this.setVisibility(resource.resource, !resource.hidden);
      }
    } else {
      this.b.set(resource.resource, { info: resource, logger: void 0 });
      this.c.fire({ added: [resource], removed: [] });
    }
  }
  deregisterLogger(resource) {
    const existing = this.b.get(resource);
    if (existing) {
      if (existing.logger) {
        existing.logger.dispose();
      }
      this.b.delete(resource);
      this.c.fire({ added: [], removed: [existing.info] });
    }
  }
  *getRegisteredLoggers() {
    for (const entry of this.b.values()) {
      yield entry.info;
    }
  }
  getRegisteredLogger(resource) {
    return this.b.get(resource)?.info;
  }
  dispose() {
    this.b.forEach((logger) => logger.logger?.dispose());
    this.b.clear();
    super.dispose();
  }
};
function $Ln(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";
  }
}
function $Nn(logLevel) {
  switch (logLevel) {
    case "trace":
      return LogLevel.Trace;
    case "debug":
      return LogLevel.Debug;
    case "info":
      return LogLevel.Info;
    case "warn":
      return LogLevel.Warning;
    case "error":
      return LogLevel.Error;
    case "critical":
      return LogLevel.Error;
    case "off":
      return LogLevel.Off;
  }
  return void 0;
}
var $On = new $nn("logLevel", $Ln(LogLevel.Info));

// out-build/vs/platform/instantiation/common/descriptors.js
var $Nk = class {
  constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) {
    this.ctor = ctor;
    this.staticArguments = staticArguments;
    this.supportsDelayedInstantiation = supportsDelayedInstantiation;
  }
};

// out-build/vs/platform/instantiation/common/extensions.js
var _registry = [];
var InstantiationType;
(function(InstantiationType2) {
  InstantiationType2[InstantiationType2["Eager"] = 0] = "Eager";
  InstantiationType2[InstantiationType2["Delayed"] = 1] = "Delayed";
})(InstantiationType || (InstantiationType = {}));
function $SC(id2, ctorOrDescriptor, supportsDelayedInstantiation) {
  if (!(ctorOrDescriptor instanceof $Nk)) {
    ctorOrDescriptor = new $Nk(ctorOrDescriptor, [], Boolean(supportsDelayedInstantiation));
  }
  _registry.push([id2, ctorOrDescriptor]);
}
function $TC() {
  return _registry;
}

// out-build/vs/platform/instantiation/common/serviceCollection.js
var $Ok = class {
  constructor(...entries) {
    this.a = /* @__PURE__ */ new Map();
    for (const [id2, service] of entries) {
      this.set(id2, service);
    }
  }
  set(id2, instanceOrDescriptor) {
    const result = this.a.get(id2);
    this.a.set(id2, instanceOrDescriptor);
    return result;
  }
  has(id2) {
    return this.a.has(id2);
  }
  get(id2) {
    return this.a.get(id2);
  }
};

// out-build/vs/workbench/api/common/extHostInitDataService.js
var $wW = $Qk("IExtHostInitDataService");

// out-build/vs/platform/instantiation/common/graph.js
var $8B = class {
  constructor(key, data) {
    this.key = key;
    this.data = data;
    this.incoming = /* @__PURE__ */ new Map();
    this.outgoing = /* @__PURE__ */ new Map();
  }
};
var $9B = class {
  constructor(b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
  }
  roots() {
    const ret = [];
    for (const node of this.a.values()) {
      if (node.outgoing.size === 0) {
        ret.push(node);
      }
    }
    return ret;
  }
  insertEdge(from, to) {
    const fromNode = this.lookupOrInsertNode(from);
    const toNode = this.lookupOrInsertNode(to);
    fromNode.outgoing.set(toNode.key, toNode);
    toNode.incoming.set(fromNode.key, fromNode);
  }
  removeNode(data) {
    const key = this.b(data);
    this.a.delete(key);
    for (const node of this.a.values()) {
      node.outgoing.delete(key);
      node.incoming.delete(key);
    }
  }
  lookupOrInsertNode(data) {
    const key = this.b(data);
    let node = this.a.get(key);
    if (!node) {
      node = new $8B(key, data);
      this.a.set(key, node);
    }
    return node;
  }
  lookup(data) {
    return this.a.get(this.b(data));
  }
  isEmpty() {
    return this.a.size === 0;
  }
  toString() {
    const data = [];
    for (const [key, value] of this.a) {
      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 [id2, node] of this.a) {
      const seen = /* @__PURE__ */ new Set([id2]);
      const res = this.c(node, seen);
      if (res) {
        return res;
      }
    }
    return void 0;
  }
  c(node, seen) {
    for (const [id2, outgoing] of node.outgoing) {
      if (seen.has(id2)) {
        return [...seen, id2].join(" -> ");
      }
      seen.add(id2);
      const value = this.c(outgoing, seen);
      if (value) {
        return value;
      }
      seen.delete(id2);
    }
    return void 0;
  }
};

// out-build/vs/platform/instantiation/common/instantiationService.js
var _enableAllTracing = false;
var CyclicDependencyError = class extends Error {
  constructor(graph) {
    super("cyclic dependency between services");
    this.message = graph.findCycleSlow() ?? `UNABLE to detect cycle, dumping graph: 
${graph.toString()}`;
  }
};
var $0B = class _$0B {
  constructor(i = new $Ok(), j = false, k, l = _enableAllTracing) {
    this.i = i;
    this.j = j;
    this.k = k;
    this.l = l;
    this.f = false;
    this.g = /* @__PURE__ */ new Set();
    this.h = /* @__PURE__ */ new Set();
    this.t = /* @__PURE__ */ new Set();
    this.i.set($Pk, this);
    this._globalGraph = l ? k?._globalGraph ?? new $9B((e) => e) : void 0;
  }
  dispose() {
    if (!this.f) {
      this.f = true;
      $Xc(this.h);
      this.h.clear();
      for (const candidate of this.g) {
        if ($Wc(candidate)) {
          candidate.dispose();
        }
      }
      this.g.clear();
    }
  }
  m() {
    if (this.f) {
      throw new Error("InstantiationService has been disposed");
    }
  }
  createChild(services, store) {
    this.m();
    const that = this;
    const result = new class extends _$0B {
      dispose() {
        that.h.delete(result);
        super.dispose();
      }
    }(services, this.j, this, this.l);
    this.h.add(result);
    store?.add(result);
    return result;
  }
  invokeFunction(fn, ...args2) {
    this.m();
    const _trace = $$B.traceInvocation(this.l, fn);
    let _done = false;
    try {
      const accessor = {
        get: (id2) => {
          if (_done) {
            throw $ob("service accessor is only valid during the invocation of its target method");
          }
          const result = this.s(id2, _trace);
          if (!result) {
            throw new Error(`[invokeFunction] unknown service '${id2}'`);
          }
          return result;
        }
      };
      return fn(accessor, ...args2);
    } finally {
      _done = true;
      _trace.stop();
    }
  }
  createInstance(ctorOrDescriptor, ...rest) {
    this.m();
    let _trace;
    let result;
    if (ctorOrDescriptor instanceof $Nk) {
      _trace = $$B.traceCreation(this.l, ctorOrDescriptor.ctor);
      result = this.o(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
    } else {
      _trace = $$B.traceCreation(this.l, ctorOrDescriptor);
      result = this.o(ctorOrDescriptor, rest, _trace);
    }
    _trace.stop();
    return result;
  }
  o(ctor, args2 = [], _trace) {
    const serviceDependencies = _util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
    const serviceArgs = [];
    for (const dependency of serviceDependencies) {
      const service = this.s(dependency.id, _trace);
      if (!service) {
        this.y(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`, false);
      }
      serviceArgs.push(service);
    }
    const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args2.length;
    if (args2.length !== firstServiceArgPos) {
      console.trace(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args2.length} static arguments`);
      const delta2 = firstServiceArgPos - args2.length;
      if (delta2 > 0) {
        args2 = args2.concat(new Array(delta2));
      } else {
        args2 = args2.slice(0, firstServiceArgPos);
      }
    }
    return Reflect.construct(ctor, args2.concat(serviceArgs));
  }
  q(id2, instance) {
    if (this.i.get(id2) instanceof $Nk) {
      this.i.set(id2, instance);
    } else if (this.k) {
      this.k.q(id2, instance);
    } else {
      throw new Error("illegalState - setting UNKNOWN service instance");
    }
  }
  r(id2) {
    const instanceOrDesc = this.i.get(id2);
    if (!instanceOrDesc && this.k) {
      return this.k.r(id2);
    } else {
      return instanceOrDesc;
    }
  }
  s(id2, _trace) {
    if (this._globalGraph && this.c) {
      this._globalGraph.insertEdge(this.c, String(id2));
    }
    const thing = this.r(id2);
    if (thing instanceof $Nk) {
      return this.u(id2, thing, _trace.branch(id2, true));
    } else {
      _trace.branch(id2, false);
      return thing;
    }
  }
  u(id2, desc, _trace) {
    if (this.t.has(id2)) {
      throw new Error(`illegal state - RECURSIVELY instantiating service '${id2}'`);
    }
    this.t.add(id2);
    try {
      return this.v(id2, desc, _trace);
    } finally {
      this.t.delete(id2);
    }
  }
  v(id2, desc, _trace) {
    const graph = new $9B((data) => data.id.toString());
    let cycleCount = 0;
    const stack = [{ id: id2, desc, _trace }];
    const seen = /* @__PURE__ */ new Set();
    while (stack.length) {
      const item = stack.pop();
      if (seen.has(String(item.id))) {
        continue;
      }
      seen.add(String(item.id));
      graph.lookupOrInsertNode(item);
      if (cycleCount++ > 1e3) {
        throw new CyclicDependencyError(graph);
      }
      for (const dependency of _util.getServiceDependencies(item.desc.ctor)) {
        const instanceOrDesc = this.r(dependency.id);
        if (!instanceOrDesc) {
          this.y(`[createInstance] ${id2} depends on ${dependency.id} which is NOT registered.`, true);
        }
        this._globalGraph?.insertEdge(String(item.id), String(dependency.id));
        if (instanceOrDesc instanceof $Nk) {
          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.r(data.id);
        if (instanceOrDesc instanceof $Nk) {
          const instance = this.w(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
          this.q(data.id, instance);
        }
        graph.removeNode(data);
      }
    }
    return this.r(id2);
  }
  w(id2, ctor, args2 = [], supportsDelayedInstantiation, _trace) {
    if (this.i.get(id2) instanceof $Nk) {
      return this.x(id2, ctor, args2, supportsDelayedInstantiation, _trace, this.g);
    } else if (this.k) {
      return this.k.w(id2, ctor, args2, supportsDelayedInstantiation, _trace);
    } else {
      throw new Error(`illegalState - creating UNKNOWN service instance ${ctor.name}`);
    }
  }
  x(id2, ctor, args2 = [], supportsDelayedInstantiation, _trace, disposeBucket) {
    if (!supportsDelayedInstantiation) {
      const result = this.o(ctor, args2, _trace);
      disposeBucket.add(result);
      return result;
    } else {
      const child = new _$0B(void 0, this.j, this, this.l);
      child.c = String(id2);
      const earlyListeners = /* @__PURE__ */ new Map();
      const idle = new $ci(() => {
        const result = child.o(ctor, args2, _trace);
        for (const [key, values] of earlyListeners) {
          const candidate = result[key];
          if (typeof candidate === "function") {
            for (const value of values) {
              value.disposable = candidate.apply(result, value.listener);
            }
          }
        }
        earlyListeners.clear();
        disposeBucket.add(result);
        return result;
      });
      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 $cd();
                earlyListeners.set(key, list2);
              }
              const event = (callback, thisArg, disposables) => {
                if (idle.isInitialized) {
                  return idle.value[key](callback, thisArg, disposables);
                } else {
                  const entry = { listener: [callback, thisArg, disposables], disposable: void 0 };
                  const rm = list2.push(entry);
                  const result = $1c(() => {
                    rm();
                    entry.disposable?.dispose();
                  });
                  return result;
                }
              };
              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, p, value) {
          idle.value[p] = value;
          return true;
        },
        getPrototypeOf(_target) {
          return ctor.prototype;
        }
      });
    }
  }
  y(msg, printWarning) {
    if (printWarning) {
      console.warn(msg);
    }
    if (this.j) {
      throw new Error(msg);
    }
  }
};
var TraceType;
(function(TraceType2) {
  TraceType2[TraceType2["None"] = 0] = "None";
  TraceType2[TraceType2["Creation"] = 1] = "Creation";
  TraceType2[TraceType2["Invocation"] = 2] = "Invocation";
  TraceType2[TraceType2["Branch"] = 3] = "Branch";
})(TraceType || (TraceType = {}));
var $$B = class _$$B {
  static {
    this.all = /* @__PURE__ */ new Set();
  }
  static {
    this.c = new class extends _$$B {
      constructor() {
        super(0, null);
      }
      stop() {
      }
      branch() {
        return this;
      }
    }();
  }
  static traceInvocation(_enableTracing, ctor) {
    return !_enableTracing ? _$$B.c : new _$$B(2, ctor.name || new Error().stack.split("\n").slice(3, 4).join("\n"));
  }
  static traceCreation(_enableTracing, ctor) {
    return !_enableTracing ? _$$B.c : new _$$B(1, ctor.name);
  }
  static {
    this.f = 0;
  }
  constructor(type, name) {
    this.type = type;
    this.name = name;
    this.g = Date.now();
    this.h = [];
  }
  branch(id2, first) {
    const child = new _$$B(3, id2.toString());
    this.h.push([id2, first, child]);
    return child;
  }
  stop() {
    const dur = Date.now() - this.g;
    _$$B.f += dur;
    let causedCreation = false;
    function printChild(n, trace) {
      const res = [];
      const prefix = new Array(n + 1).join("	");
      for (const [id2, first, child] of trace.h) {
        if (first && child) {
          causedCreation = true;
          res.push(`${prefix}CREATES -> ${id2}`);
          const nested = printChild(n + 1, child);
          if (nested) {
            res.push(nested);
          }
        } else {
          res.push(`${prefix}uses -> ${id2}`);
        }
      }
      return res.join("\n");
    }
    const lines = [
      `${this.type === 1 ? "CREATE" : "CALL"} ${this.name}`,
      `${printChild(1, this)}`,
      `DONE, took ${dur.toFixed(2)}ms (grand total ${_$$B.f.toFixed(2)}ms)`
    ];
    if (dur > 2 || causedCreation) {
      _$$B.all.add(lines.join("\n"));
    }
  }
};

// out-build/vs/workbench/api/common/extHostRpcService.js
var $gW = $Qk("IExtHostRpcService");
var $hW = class {
  constructor(rpcProtocol) {
    this.getProxy = rpcProtocol.getProxy.bind(rpcProtocol);
    this.set = rpcProtocol.set.bind(rpcProtocol);
    this.dispose = rpcProtocol.dispose.bind(rpcProtocol);
    this.assertRegistered = rpcProtocol.assertRegistered.bind(rpcProtocol);
    this.drain = rpcProtocol.drain.bind(rpcProtocol);
  }
};

// out-build/vs/workbench/api/common/extHostUriTransformerService.js
var $7wc = $Qk("IURITransformerService");
var $8wc = class {
  constructor(delegate) {
    if (!delegate) {
      this.transformIncoming = (arg) => arg;
      this.transformOutgoing = (arg) => arg;
      this.transformOutgoingURI = (arg) => arg;
      this.transformOutgoingScheme = (arg) => arg;
    } else {
      this.transformIncoming = delegate.transformIncoming.bind(delegate);
      this.transformOutgoing = delegate.transformOutgoing.bind(delegate);
      this.transformOutgoingURI = delegate.transformOutgoingURI.bind(delegate);
      this.transformOutgoingScheme = delegate.transformOutgoingScheme.bind(delegate);
    }
  }
};

// out-build/vs/base/common/ternarySearchTree.js
var $Sk = class {
  constructor() {
    this.b = "";
    this.c = 0;
  }
  reset(key) {
    this.b = key;
    this.c = 0;
    return this;
  }
  next() {
    this.c += 1;
    return this;
  }
  hasNext() {
    return this.c < this.b.length - 1;
  }
  cmp(a) {
    const aCode = a.charCodeAt(0);
    const thisCode = this.b.charCodeAt(this.c);
    return aCode - thisCode;
  }
  value() {
    return this.b[this.c];
  }
};
var $Tk = class {
  constructor(e = true) {
    this.e = e;
  }
  reset(key) {
    this.b = key;
    this.c = 0;
    this.d = 0;
    return this.next();
  }
  hasNext() {
    return this.d < this.b.length;
  }
  next() {
    this.c = this.d;
    let justSeps = true;
    for (; this.d < this.b.length; this.d++) {
      const ch = this.b.charCodeAt(this.d);
      if (ch === 46) {
        if (justSeps) {
          this.c++;
        } else {
          break;
        }
      } else {
        justSeps = false;
      }
    }
    return this;
  }
  cmp(a) {
    return this.e ? $Uf(a, this.b, 0, a.length, this.c, this.d) : $Wf(a, this.b, 0, a.length, this.c, this.d);
  }
  value() {
    return this.b.substring(this.c, this.d);
  }
};
var $Uk = class {
  constructor(f = true, g = true) {
    this.f = f;
    this.g = g;
  }
  reset(key) {
    this.d = 0;
    this.e = 0;
    this.b = key;
    this.c = key.length;
    for (let pos = key.length - 1; pos >= 0; pos--, this.c--) {
      const ch = this.b.charCodeAt(pos);
      if (!(ch === 47 || this.f && ch === 92)) {
        break;
      }
    }
    return this.next();
  }
  hasNext() {
    return this.e < this.c;
  }
  next() {
    this.d = this.e;
    let justSeps = true;
    for (; this.e < this.c; this.e++) {
      const ch = this.b.charCodeAt(this.e);
      if (ch === 47 || this.f && ch === 92) {
        if (justSeps) {
          this.d++;
        } else {
          break;
        }
      } else {
        justSeps = false;
      }
    }
    return this;
  }
  cmp(a) {
    return this.g ? $Uf(a, this.b, 0, a.length, this.d, this.e) : $Wf(a, this.b, 0, a.length, this.d, this.e);
  }
  value() {
    return this.b.substring(this.d, this.e);
  }
};
var UriIteratorState;
(function(UriIteratorState2) {
  UriIteratorState2[UriIteratorState2["Scheme"] = 1] = "Scheme";
  UriIteratorState2[UriIteratorState2["Authority"] = 2] = "Authority";
  UriIteratorState2[UriIteratorState2["Path"] = 3] = "Path";
  UriIteratorState2[UriIteratorState2["Query"] = 4] = "Query";
  UriIteratorState2[UriIteratorState2["Fragment"] = 5] = "Fragment";
})(UriIteratorState || (UriIteratorState = {}));
var $Vk = class {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.d = [];
    this.e = 0;
  }
  reset(key) {
    this.c = key;
    this.d = [];
    if (this.c.scheme) {
      this.d.push(
        1
        /* UriIteratorState.Scheme */
      );
    }
    if (this.c.authority) {
      this.d.push(
        2
        /* UriIteratorState.Authority */
      );
    }
    if (this.c.path) {
      this.b = new $Uk(false, !this.f(key));
      this.b.reset(key.path);
      if (this.b.value()) {
        this.d.push(
          3
          /* UriIteratorState.Path */
        );
      }
    }
    if (!this.g(key)) {
      if (this.c.query) {
        this.d.push(
          4
          /* UriIteratorState.Query */
        );
      }
      if (this.c.fragment) {
        this.d.push(
          5
          /* UriIteratorState.Fragment */
        );
      }
    }
    this.e = 0;
    return this;
  }
  next() {
    if (this.d[this.e] === 3 && this.b.hasNext()) {
      this.b.next();
    } else {
      this.e += 1;
    }
    return this;
  }
  hasNext() {
    return this.d[this.e] === 3 && this.b.hasNext() || this.e < this.d.length - 1;
  }
  cmp(a) {
    if (this.d[this.e] === 1) {
      return $Vf(a, this.c.scheme);
    } else if (this.d[this.e] === 2) {
      return $Vf(a, this.c.authority);
    } else if (this.d[this.e] === 3) {
      return this.b.cmp(a);
    } else if (this.d[this.e] === 4) {
      return $Tf(a, this.c.query);
    } else if (this.d[this.e] === 5) {
      return $Tf(a, this.c.fragment);
    }
    throw new Error();
  }
  value() {
    if (this.d[this.e] === 1) {
      return this.c.scheme;
    } else if (this.d[this.e] === 2) {
      return this.c.authority;
    } else if (this.d[this.e] === 3) {
      return this.b.value();
    } else if (this.d[this.e] === 4) {
      return this.c.query;
    } else if (this.d[this.e] === 5) {
      return this.c.fragment;
    }
    throw new Error();
  }
};
var TernarySearchTreeNode = class {
  constructor() {
    this.height = 1;
  }
  isEmpty() {
    return !this.left && !this.mid && !this.right && !this.value;
  }
  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() {
    return this.left?.height ?? 0;
  }
  get heightRight() {
    return this.right?.height ?? 0;
  }
};
var Dir;
(function(Dir2) {
  Dir2[Dir2["Left"] = -1] = "Left";
  Dir2[Dir2["Mid"] = 0] = "Mid";
  Dir2[Dir2["Right"] = 1] = "Right";
})(Dir || (Dir = {}));
var $Wk = class _$Wk {
  static forUris(ignorePathCasing2 = () => false, ignoreQueryAndFragment = () => false) {
    return new _$Wk(new $Vk(ignorePathCasing2, ignoreQueryAndFragment));
  }
  static forPaths(ignorePathCasing2 = false) {
    return new _$Wk(new $Uk(void 0, !ignorePathCasing2));
  }
  static forStrings() {
    return new _$Wk(new $Sk());
  }
  static forConfigKeys() {
    return new _$Wk(new $Tk());
  }
  constructor(segments) {
    this.b = segments;
  }
  clear() {
    this.c = void 0;
  }
  fill(values, keys) {
    if (keys) {
      const arr = keys.slice(0);
      $Zb(arr);
      for (const k of arr) {
        this.set(k, values);
      }
    } else {
      const arr = values.slice(0);
      $Zb(arr);
      for (const entry of arr) {
        this.set(entry[0], entry[1]);
      }
    }
  }
  set(key, element) {
    const iter = this.b.reset(key);
    let node;
    if (!this.c) {
      this.c = new TernarySearchTreeNode();
      this.c.segment = iter.value();
    }
    const stack = [];
    node = this.c;
    while (true) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        if (!node.left) {
          node.left = new TernarySearchTreeNode();
          node.left.segment = iter.value();
        }
        stack.push([-1, node]);
        node = node.left;
      } else if (val < 0) {
        if (!node.right) {
          node.right = new TernarySearchTreeNode();
          node.right.segment = iter.value();
        }
        stack.push([1, node]);
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        if (!node.mid) {
          node.mid = new TernarySearchTreeNode();
          node.mid.segment = iter.value();
        }
        stack.push([0, node]);
        node = node.mid;
      } else {
        break;
      }
    }
    const oldElement = node.value;
    node.value = element;
    node.key = key;
    for (let i = stack.length - 1; i >= 0; i--) {
      const node2 = stack[i][1];
      node2.updateHeight();
      const bf = node2.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] = node2.rotateLeft();
        } else if (d1 === -1 && d2 === -1) {
          stack[i][1] = node2.rotateRight();
        } else if (d1 === 1 && d2 === -1) {
          node2.right = stack[i + 1][1] = stack[i + 1][1].rotateRight();
          stack[i][1] = node2.rotateLeft();
        } else if (d1 === -1 && d2 === 1) {
          node2.left = stack[i + 1][1] = stack[i + 1][1].rotateLeft();
          stack[i][1] = node2.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.c = stack[0][1];
        }
      }
    }
    return oldElement;
  }
  get(key) {
    return this.d(key)?.value;
  }
  d(key) {
    const iter = this.b.reset(key);
    let node = this.c;
    while (node) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        node = node.left;
      } else if (val < 0) {
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        node = node.mid;
      } else {
        break;
      }
    }
    return node;
  }
  has(key) {
    const node = this.d(key);
    return !(node?.value === void 0 && node?.mid === void 0);
  }
  delete(key) {
    return this.e(key, false);
  }
  deleteSuperstr(key) {
    return this.e(key, true);
  }
  e(key, superStr) {
    const iter = this.b.reset(key);
    const stack = [];
    let node = this.c;
    while (node) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        stack.push([-1, node]);
        node = node.left;
      } else if (val < 0) {
        stack.push([1, node]);
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        stack.push([0, node]);
        node = node.mid;
      } else {
        break;
      }
    }
    if (!node) {
      return;
    }
    if (superStr) {
      node.left = void 0;
      node.mid = void 0;
      node.right = void 0;
      node.height = 1;
    } else {
      node.key = void 0;
      node.value = void 0;
    }
    if (!node.mid && !node.value) {
      if (node.left && node.right) {
        const min = this.f(node.right);
        if (min.key) {
          const { key: key2, value, segment } = min;
          this.e(min.key, false);
          node.key = key2;
          node.value = value;
          node.segment = segment;
        }
      } else {
        const newChild = node.left ?? node.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.c = newChild;
        }
      }
    }
    for (let i = stack.length - 1; i >= 0; i--) {
      const node2 = stack[i][1];
      node2.updateHeight();
      const bf = node2.balanceFactor();
      if (bf > 1) {
        if (node2.right.balanceFactor() >= 0) {
          stack[i][1] = node2.rotateLeft();
        } else {
          node2.right = node2.right.rotateRight();
          stack[i][1] = node2.rotateLeft();
        }
      } else if (bf < -1) {
        if (node2.left.balanceFactor() <= 0) {
          stack[i][1] = node2.rotateRight();
        } else {
          node2.left = node2.left.rotateLeft();
          stack[i][1] = node2.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.c = stack[0][1];
      }
    }
  }
  f(node) {
    while (node.left) {
      node = node.left;
    }
    return node;
  }
  findSubstr(key) {
    const iter = this.b.reset(key);
    let node = this.c;
    let candidate = void 0;
    while (node) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        node = node.left;
      } else if (val < 0) {
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        candidate = node.value || candidate;
        node = node.mid;
      } else {
        break;
      }
    }
    return node && node.value || candidate;
  }
  findSuperstr(key) {
    return this.g(key, false);
  }
  g(key, allowValue) {
    const iter = this.b.reset(key);
    let node = this.c;
    while (node) {
      const val = iter.cmp(node.segment);
      if (val > 0) {
        node = node.left;
      } else if (val < 0) {
        node = node.right;
      } else if (iter.hasNext()) {
        iter.next();
        node = node.mid;
      } else {
        if (!node.mid) {
          if (allowValue) {
            return node.value;
          } else {
            return void 0;
          }
        } else {
          return this.h(node.mid);
        }
      }
    }
    return void 0;
  }
  hasElementOrSubtree(key) {
    return this.g(key, true) !== void 0;
  }
  forEach(callback) {
    for (const [key, value] of this) {
      callback(value, key);
    }
  }
  *[Symbol.iterator]() {
    yield* this.h(this.c);
  }
  h(node) {
    const result = [];
    this.j(node, result);
    return result[Symbol.iterator]();
  }
  j(node, bucket) {
    if (!node) {
      return;
    }
    if (node.left) {
      this.j(node.left, bucket);
    }
    if (node.value) {
      bucket.push([node.key, node.value]);
    }
    if (node.mid) {
      this.j(node.mid, bucket);
    }
    if (node.right) {
      this.j(node.right, bucket);
    }
  }
  // for debug/testing
  _isBalanced() {
    const nodeIsBalanced = (node) => {
      if (!node) {
        return true;
      }
      const bf = node.balanceFactor();
      if (bf < -1 || bf > 1) {
        return false;
      }
      return nodeIsBalanced(node.left) && nodeIsBalanced(node.right);
    };
    return nodeIsBalanced(this.c);
  }
};

// out-build/vs/base/common/numbers.js
function $4i(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
var $6i = class {
  constructor() {
    this.a = 0;
  }
  getNext() {
    return this.a++;
  }
};
var $7i = class {
  constructor() {
    this.a = 1;
    this.b = 0;
  }
  update(value) {
    this.b = this.b + (value - this.b) / this.a;
    this.a += 1;
    return this.b;
  }
  get value() {
    return this.b;
  }
};

// out-build/vs/base/common/severity.js
var Severity;
(function(Severity3) {
  Severity3[Severity3["Ignore"] = 0] = "Ignore";
  Severity3[Severity3["Info"] = 1] = "Info";
  Severity3[Severity3["Warning"] = 2] = "Warning";
  Severity3[Severity3["Error"] = 3] = "Error";
})(Severity || (Severity = {}));
(function(Severity3) {
  const _error = "error";
  const _warning = "warning";
  const _warn = "warn";
  const _info = "info";
  const _ignore = "ignore";
  function fromValue(value) {
    if (!value) {
      return Severity3.Ignore;
    }
    if ($1f(_error, value)) {
      return Severity3.Error;
    }
    if ($1f(_warning, value) || $1f(_warn, value)) {
      return Severity3.Warning;
    }
    if ($1f(_info, value)) {
      return Severity3.Info;
    }
    return Severity3.Ignore;
  }
  Severity3.fromValue = fromValue;
  function toString(severity) {
    switch (severity) {
      case Severity3.Error:
        return _error;
      case Severity3.Warning:
        return _warning;
      case Severity3.Info:
        return _info;
      default:
        return _ignore;
    }
  }
  Severity3.toString = toString;
})(Severity || (Severity = {}));
var severity_default = Severity;

// out-build/vs/platform/notification/common/notification.js
var Severity2 = severity_default;
var $PJ = $Qk("notificationService");
var NotificationPriority;
(function(NotificationPriority2) {
  NotificationPriority2[NotificationPriority2["DEFAULT"] = 0] = "DEFAULT";
  NotificationPriority2[NotificationPriority2["SILENT"] = 1] = "SILENT";
  NotificationPriority2[NotificationPriority2["URGENT"] = 2] = "URGENT";
})(NotificationPriority || (NotificationPriority = {}));
var NeverShowAgainScope;
(function(NeverShowAgainScope2) {
  NeverShowAgainScope2[NeverShowAgainScope2["WORKSPACE"] = 0] = "WORKSPACE";
  NeverShowAgainScope2[NeverShowAgainScope2["PROFILE"] = 1] = "PROFILE";
  NeverShowAgainScope2[NeverShowAgainScope2["APPLICATION"] = 2] = "APPLICATION";
})(NeverShowAgainScope || (NeverShowAgainScope = {}));
var NotificationsFilter;
(function(NotificationsFilter2) {
  NotificationsFilter2[NotificationsFilter2["OFF"] = 0] = "OFF";
  NotificationsFilter2[NotificationsFilter2["ERROR"] = 1] = "ERROR";
})(NotificationsFilter || (NotificationsFilter = {}));

// out-build/vs/platform/workspace/common/workspace.js
var $Zk = $Qk("contextService");
function $1k(obj) {
  const singleFolderIdentifier = obj;
  return typeof singleFolderIdentifier?.id === "string" && URI.isUri(singleFolderIdentifier.uri);
}
function $6k(obj) {
  const workspaceIdentifier = obj;
  return typeof workspaceIdentifier?.id === "string" && URI.isUri(workspaceIdentifier.configPath);
}
var WorkbenchState;
(function(WorkbenchState2) {
  WorkbenchState2[WorkbenchState2["EMPTY"] = 1] = "EMPTY";
  WorkbenchState2[WorkbenchState2["FOLDER"] = 2] = "FOLDER";
  WorkbenchState2[WorkbenchState2["WORKSPACE"] = 3] = "WORKSPACE";
})(WorkbenchState || (WorkbenchState = {}));
var $0k = class {
  constructor(h, folders, j, k, l) {
    this.h = h;
    this.j = j;
    this.k = k;
    this.l = l;
    this.c = $Wk.forUris(this.l, () => true);
    this.folders = folders;
  }
  update(workspace) {
    this.h = workspace.id;
    this.k = workspace.configuration;
    this.j = workspace.transient;
    this.l = workspace.l;
    this.folders = workspace.folders;
  }
  get folders() {
    return this.g;
  }
  set folders(folders) {
    this.g = folders;
    this.n();
  }
  get id() {
    return this.h;
  }
  get transient() {
    return this.j;
  }
  get configuration() {
    return this.k;
  }
  set configuration(configuration) {
    this.k = configuration;
  }
  getFolder(resource) {
    if (!resource) {
      return null;
    }
    return this.c.findSubstr(resource) || null;
  }
  n() {
    this.c = $Wk.forUris(this.l, () => true);
    for (const folder of this.folders) {
      this.c.set(folder.uri, folder);
    }
  }
  toJSON() {
    return { id: this.id, folders: this.folders, transient: this.transient, configuration: this.configuration };
  }
};
var $$k = class {
  constructor(data, raw) {
    this.raw = raw;
    this.uri = data.uri;
    this.index = data.index;
    this.name = data.name;
  }
  toResource(relativePath) {
    return $vh(this.uri, relativePath);
  }
  toJSON() {
    return { uri: this.uri, name: this.name, index: this.index };
  }
};
function $_k(resource) {
  return new $$k({ uri: resource, index: 0, name: $rh(resource) }, { uri: resource.toString() });
}
var $al = "code-workspace";
var $bl = `.${$al}`;
var $cl = [{ name: localize(2536, null), extensions: [$al] }];
function $jl(path) {
  const ext = typeof path === "string" ? $sc(path) : $th(path);
  return ext === $bl;
}

// out-build/vs/workbench/api/common/extHostFileSystemInfo.js
var $Owc = class {
  constructor() {
    this.a = new Set(Object.keys(Schemas));
    this.b = /* @__PURE__ */ new Map();
    this.extUri = new $kh((uri) => {
      const capabilities = this.b.get(uri.scheme);
      if (capabilities === void 0) {
        return false;
      }
      if (capabilities & 1024) {
        return false;
      }
      return true;
    });
  }
  $acceptProviderInfos(uri, capabilities) {
    if (capabilities === null) {
      this.b.delete(uri.scheme);
    } else {
      this.b.set(uri.scheme, capabilities);
    }
  }
  isFreeScheme(scheme) {
    return !this.b.has(scheme) && !this.a.has(scheme);
  }
  getCapabilities(scheme) {
    return this.b.get(scheme);
  }
};
var $Pwc = $Qk("IExtHostFileSystemInfo");

// out-build/vs/base/common/dataTransfer.js
var $nE = Object.freeze({
  // http://amundsen.com/hypermedia/urilist/
  create: (entries) => {
    return $Rb(entries.map((x) => x.toString())).join("\r\n");
  },
  split: (str) => {
    return str.split("\r\n");
  },
  parse: (str) => {
    return $nE.split(str).filter((value) => !value.startsWith("#"));
  }
});

// out-build/vs/base/common/naturalLanguage/korean.js
var codeBuffer = new Uint32Array(10);
var HangulRangeStartCode;
(function(HangulRangeStartCode2) {
  HangulRangeStartCode2[HangulRangeStartCode2["InitialConsonant"] = 4352] = "InitialConsonant";
  HangulRangeStartCode2[HangulRangeStartCode2["Vowel"] = 4449] = "Vowel";
  HangulRangeStartCode2[HangulRangeStartCode2["FinalConsonant"] = 4520] = "FinalConsonant";
  HangulRangeStartCode2[HangulRangeStartCode2["CompatibilityJamo"] = 12593] = "CompatibilityJamo";
})(HangulRangeStartCode || (HangulRangeStartCode = {}));
var AsciiCode;
(function(AsciiCode2) {
  AsciiCode2[AsciiCode2["NUL"] = 0] = "NUL";
  AsciiCode2[AsciiCode2["A"] = 65] = "A";
  AsciiCode2[AsciiCode2["B"] = 66] = "B";
  AsciiCode2[AsciiCode2["C"] = 67] = "C";
  AsciiCode2[AsciiCode2["D"] = 68] = "D";
  AsciiCode2[AsciiCode2["E"] = 69] = "E";
  AsciiCode2[AsciiCode2["F"] = 70] = "F";
  AsciiCode2[AsciiCode2["G"] = 71] = "G";
  AsciiCode2[AsciiCode2["H"] = 72] = "H";
  AsciiCode2[AsciiCode2["I"] = 73] = "I";
  AsciiCode2[AsciiCode2["J"] = 74] = "J";
  AsciiCode2[AsciiCode2["K"] = 75] = "K";
  AsciiCode2[AsciiCode2["L"] = 76] = "L";
  AsciiCode2[AsciiCode2["M"] = 77] = "M";
  AsciiCode2[AsciiCode2["N"] = 78] = "N";
  AsciiCode2[AsciiCode2["O"] = 79] = "O";
  AsciiCode2[AsciiCode2["P"] = 80] = "P";
  AsciiCode2[AsciiCode2["Q"] = 81] = "Q";
  AsciiCode2[AsciiCode2["R"] = 82] = "R";
  AsciiCode2[AsciiCode2["S"] = 83] = "S";
  AsciiCode2[AsciiCode2["T"] = 84] = "T";
  AsciiCode2[AsciiCode2["U"] = 85] = "U";
  AsciiCode2[AsciiCode2["V"] = 86] = "V";
  AsciiCode2[AsciiCode2["W"] = 87] = "W";
  AsciiCode2[AsciiCode2["X"] = 88] = "X";
  AsciiCode2[AsciiCode2["Y"] = 89] = "Y";
  AsciiCode2[AsciiCode2["Z"] = 90] = "Z";
  AsciiCode2[AsciiCode2["a"] = 97] = "a";
  AsciiCode2[AsciiCode2["b"] = 98] = "b";
  AsciiCode2[AsciiCode2["c"] = 99] = "c";
  AsciiCode2[AsciiCode2["d"] = 100] = "d";
  AsciiCode2[AsciiCode2["e"] = 101] = "e";
  AsciiCode2[AsciiCode2["f"] = 102] = "f";
  AsciiCode2[AsciiCode2["g"] = 103] = "g";
  AsciiCode2[AsciiCode2["h"] = 104] = "h";
  AsciiCode2[AsciiCode2["i"] = 105] = "i";
  AsciiCode2[AsciiCode2["j"] = 106] = "j";
  AsciiCode2[AsciiCode2["k"] = 107] = "k";
  AsciiCode2[AsciiCode2["l"] = 108] = "l";
  AsciiCode2[AsciiCode2["m"] = 109] = "m";
  AsciiCode2[AsciiCode2["n"] = 110] = "n";
  AsciiCode2[AsciiCode2["o"] = 111] = "o";
  AsciiCode2[AsciiCode2["p"] = 112] = "p";
  AsciiCode2[AsciiCode2["q"] = 113] = "q";
  AsciiCode2[AsciiCode2["r"] = 114] = "r";
  AsciiCode2[AsciiCode2["s"] = 115] = "s";
  AsciiCode2[AsciiCode2["t"] = 116] = "t";
  AsciiCode2[AsciiCode2["u"] = 117] = "u";
  AsciiCode2[AsciiCode2["v"] = 118] = "v";
  AsciiCode2[AsciiCode2["w"] = 119] = "w";
  AsciiCode2[AsciiCode2["x"] = 120] = "x";
  AsciiCode2[AsciiCode2["y"] = 121] = "y";
  AsciiCode2[AsciiCode2["z"] = 122] = "z";
})(AsciiCode || (AsciiCode = {}));
var AsciiCodeCombo;
(function(AsciiCodeCombo2) {
  AsciiCodeCombo2[AsciiCodeCombo2["fa"] = 24934] = "fa";
  AsciiCodeCombo2[AsciiCodeCombo2["fg"] = 26470] = "fg";
  AsciiCodeCombo2[AsciiCodeCombo2["fq"] = 29030] = "fq";
  AsciiCodeCombo2[AsciiCodeCombo2["fr"] = 29286] = "fr";
  AsciiCodeCombo2[AsciiCodeCombo2["ft"] = 29798] = "ft";
  AsciiCodeCombo2[AsciiCodeCombo2["fv"] = 30310] = "fv";
  AsciiCodeCombo2[AsciiCodeCombo2["fx"] = 30822] = "fx";
  AsciiCodeCombo2[AsciiCodeCombo2["hk"] = 27496] = "hk";
  AsciiCodeCombo2[AsciiCodeCombo2["hl"] = 27752] = "hl";
  AsciiCodeCombo2[AsciiCodeCombo2["ho"] = 28520] = "ho";
  AsciiCodeCombo2[AsciiCodeCombo2["ml"] = 27757] = "ml";
  AsciiCodeCombo2[AsciiCodeCombo2["nj"] = 27246] = "nj";
  AsciiCodeCombo2[AsciiCodeCombo2["nl"] = 27758] = "nl";
  AsciiCodeCombo2[AsciiCodeCombo2["np"] = 28782] = "np";
  AsciiCodeCombo2[AsciiCodeCombo2["qt"] = 29809] = "qt";
  AsciiCodeCombo2[AsciiCodeCombo2["rt"] = 29810] = "rt";
  AsciiCodeCombo2[AsciiCodeCombo2["sg"] = 26483] = "sg";
  AsciiCodeCombo2[AsciiCodeCombo2["sw"] = 30579] = "sw";
})(AsciiCodeCombo || (AsciiCodeCombo = {}));
var modernConsonants = new Uint8Array([
  114,
  // ㄱ
  82,
  // ㄲ
  115,
  // ㄴ
  101,
  // ㄷ
  69,
  // ㄸ
  102,
  // ㄹ
  97,
  // ㅁ
  113,
  // ㅂ
  81,
  // ㅃ
  116,
  // ㅅ
  84,
  // ㅆ
  100,
  // ㅇ
  119,
  // ㅈ
  87,
  // ㅉ
  99,
  // ㅊ
  122,
  // ㅋ
  120,
  // ㅌ
  118,
  // ㅍ
  103
  // ㅎ
]);
var modernVowels = new Uint16Array([
  107,
  //  -> ㅏ
  111,
  //  -> ㅐ
  105,
  //  -> ㅑ
  79,
  //  -> ㅒ
  106,
  //  -> ㅓ
  112,
  //  -> ㅔ
  117,
  //  -> ㅕ
  80,
  //  -> ㅖ
  104,
  //  -> ㅗ
  27496,
  //  -> ㅘ
  28520,
  //  -> ㅙ
  27752,
  //  -> ㅚ
  121,
  //  -> ㅛ
  110,
  //  -> ㅜ
  27246,
  //  -> ㅝ
  28782,
  //  -> ㅞ
  27758,
  //  -> ㅟ
  98,
  //  -> ㅠ
  109,
  //  -> ㅡ
  27757,
  //  -> ㅢ
  108
  //  -> ㅣ
]);
var modernFinalConsonants = new Uint16Array([
  114,
  // ㄱ
  82,
  // ㄲ
  29810,
  // ㄳ
  115,
  // ㄴ
  30579,
  // ㄵ
  26483,
  // ㄶ
  101,
  // ㄷ
  102,
  // ㄹ
  29286,
  // ㄺ
  24934,
  // ㄻ
  29030,
  // ㄼ
  29798,
  // ㄽ
  30822,
  // ㄾ
  30310,
  // ㄿ
  26470,
  // ㅀ
  97,
  // ㅁ
  113,
  // ㅂ
  29809,
  // ㅄ
  116,
  // ㅅ
  84,
  // ㅆ
  100,
  // ㅇ
  119,
  // ㅈ
  99,
  // ㅊ
  122,
  // ㅋ
  120,
  // ㅌ
  118,
  // ㅍ
  103
  // ㅎ
]);
var compatibilityJamo = new Uint16Array([
  114,
  // ㄱ
  82,
  // ㄲ
  29810,
  // ㄳ
  115,
  // ㄴ
  30579,
  // ㄵ
  26483,
  // ㄶ
  101,
  // ㄷ
  69,
  // ㄸ
  102,
  // ㄹ
  29286,
  // ㄺ
  24934,
  // ㄻ
  29030,
  // ㄼ
  29798,
  // ㄽ
  30822,
  // ㄾ
  30310,
  // ㄿ
  26470,
  // ㅀ
  97,
  // ㅁ
  113,
  // ㅂ
  81,
  // ㅃ
  29809,
  // ㅄ
  116,
  // ㅅ
  84,
  // ㅆ
  100,
  // ㅇ
  119,
  // ㅈ
  87,
  // ㅉ
  99,
  // ㅊ
  122,
  // ㅋ
  120,
  // ㅌ
  118,
  // ㅍ
  103,
  // ㅎ
  107,
  // ㅏ
  111,
  // ㅐ
  105,
  // ㅑ
  79,
  // ㅒ
  106,
  // ㅓ
  112,
  // ㅔ
  117,
  // ㅕ
  80,
  // ㅖ
  104,
  // ㅗ
  27496,
  // ㅘ
  28520,
  // ㅙ
  27752,
  // ㅚ
  121,
  // ㅛ
  110,
  // ㅜ
  27246,
  // ㅝ
  28782,
  // ㅞ
  27758,
  // ㅟ
  98,
  // ㅠ
  109,
  // ㅡ
  27757,
  // ㅢ
  108
  // ㅣ
  // HF: Hangul Filler (everything after this is archaic)
  // ㅥ
  // ㅦ
  // ㅧ
  // ㅨ
  // ㅩ
  // ㅪ
  // ㅫ
  // ㅬ
  // ㅮ
  // ㅯ
  // ㅰ
  // ㅱ
  // ㅲ
  // ㅳ
  // ㅴ
  // ㅵ
  // ㅶ
  // ㅷ
  // ㅸ
  // ㅹ
  // ㅺ
  // ㅻ
  // ㅼ
  // ㅽ
  // ㅾ
  // ㅿ
  // ㆀ
  // ㆁ
  // ㆂ
  // ㆃ
  // ㆄ
  // ㆅ
  // ㆆ
  // ㆇ
  // ㆈ
  // ㆉ
  // ㆊ
  // ㆋ
  // ㆌ
  // ㆍ
  // ㆎ
]);

// out-build/vs/base/common/filters.js
function or(...filter) {
  return function(word, wordToMatchAgainst) {
    for (let i = 0, len = filter.length; i < len; i++) {
      const match = filter[i](word, wordToMatchAgainst);
      if (match) {
        return match;
      }
    }
    return null;
  };
}
var $Kl = _matchesPrefix.bind(void 0, false);
var $Ll = _matchesPrefix.bind(void 0, true);
function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) {
  if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) {
    return null;
  }
  let matches;
  if (ignoreCase) {
    matches = $2f(wordToMatchAgainst, word);
  } else {
    matches = wordToMatchAgainst.indexOf(word) === 0;
  }
  if (!matches) {
    return null;
  }
  return word.length > 0 ? [{ start: 0, end: word.length }] : [];
}
function $Ml(word, wordToMatchAgainst) {
  const index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
  if (index === -1) {
    return null;
  }
  return [{ start: index, end: index + word.length }];
}
function $Nl(word, wordToMatchAgainst) {
  return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
}
function _matchesSubString(word, wordToMatchAgainst, i, j) {
  if (i === word.length) {
    return [];
  } else if (j === wordToMatchAgainst.length) {
    return null;
  } else {
    if (word[i] === wordToMatchAgainst[j]) {
      let result = null;
      if (result = _matchesSubString(word, wordToMatchAgainst, i + 1, j + 1)) {
        return join({ start: j, end: j + 1 }, result);
      }
      return null;
    }
    return _matchesSubString(word, wordToMatchAgainst, i, j + 1);
  }
}
function isLower(code) {
  return 97 <= code && code <= 122;
}
function $Ol(code) {
  return 65 <= code && code <= 90;
}
function isNumber(code) {
  return 48 <= code && code <= 57;
}
function isWhitespace(code) {
  return code === 32 || code === 9 || code === 10 || code === 13;
}
var wordSeparators = /* @__PURE__ */ new Set();
"()[]{}<>`'\"-/;:,.?!".split("").forEach((s) => wordSeparators.add(s.charCodeAt(0)));
function isAlphanumeric(code) {
  return isLower(code) || $Ol(code) || isNumber(code);
}
function join(head, tail) {
  if (tail.length === 0) {
    tail = [head];
  } else if (head.end === tail[0].start) {
    tail[0].start = head.start;
  } else {
    tail.unshift(head);
  }
  return tail;
}
function nextAnchor(camelCaseWord, start) {
  for (let i = start; i < camelCaseWord.length; i++) {
    const c = camelCaseWord.charCodeAt(i);
    if ($Ol(c) || isNumber(c) || i > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i - 1))) {
      return i;
    }
  }
  return camelCaseWord.length;
}
function _matchesCamelCase(word, camelCaseWord, i, j) {
  if (i === word.length) {
    return [];
  } else if (j === camelCaseWord.length) {
    return null;
  } else if (word[i] !== camelCaseWord[j].toLowerCase()) {
    return null;
  } else {
    let result = null;
    let nextUpperIndex = j + 1;
    result = _matchesCamelCase(word, camelCaseWord, i + 1, j + 1);
    while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
      result = _matchesCamelCase(word, camelCaseWord, i + 1, nextUpperIndex);
      nextUpperIndex++;
    }
    return result === null ? null : join({ start: j, end: j + 1 }, result);
  }
}
function analyzeCamelCaseWord(word) {
  let upper = 0, lower = 0, alpha = 0, numeric = 0, code = 0;
  for (let i = 0; i < word.length; i++) {
    code = word.charCodeAt(i);
    if ($Ol(code)) {
      upper++;
    }
    if (isLower(code)) {
      lower++;
    }
    if (isAlphanumeric(code)) {
      alpha++;
    }
    if (isNumber(code)) {
      numeric++;
    }
  }
  const upperPercent = upper / word.length;
  const lowerPercent = lower / word.length;
  const alphaPercent = alpha / word.length;
  const numericPercent = numeric / word.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(word) {
  let upper = 0, lower = 0, code = 0, whitespace = 0;
  for (let i = 0; i < word.length; i++) {
    code = word.charCodeAt(i);
    if ($Ol(code)) {
      upper++;
    }
    if (isLower(code)) {
      lower++;
    }
    if (isWhitespace(code)) {
      whitespace++;
    }
  }
  if ((upper === 0 || lower === 0) && whitespace === 0) {
    return word.length <= 30;
  } else {
    return upper <= 5;
  }
}
function $Pl(word, camelCaseWord) {
  if (!camelCaseWord) {
    return null;
  }
  camelCaseWord = camelCaseWord.trim();
  if (camelCaseWord.length === 0) {
    return null;
  }
  if (!isCamelCasePattern(word)) {
    return null;
  }
  if (camelCaseWord.length > 60) {
    camelCaseWord = camelCaseWord.substring(0, 60);
  }
  const analysis = analyzeCamelCaseWord(camelCaseWord);
  if (!isCamelCaseWord(analysis)) {
    if (!isUpperCaseWord(analysis)) {
      return null;
    }
    camelCaseWord = camelCaseWord.toLowerCase();
  }
  let result = null;
  let i = 0;
  word = word.toLowerCase();
  while (i < camelCaseWord.length && (result = _matchesCamelCase(word, camelCaseWord, 0, i)) === null) {
    i = nextAnchor(camelCaseWord, i + 1);
  }
  return result;
}
var fuzzyContiguousFilter = or($Ll, $Pl, $Ml);
var fuzzySeparateFilter = or($Ll, $Pl, $Nl);
var fuzzyRegExpCache = new $Hc(1e4);
var _maxLen = 128;
function initTable() {
  const table = [];
  const row = [];
  for (let i = 0; i <= _maxLen; i++) {
    row[i] = 0;
  }
  for (let i = 0; i <= _maxLen; i++) {
    table.push(row.slice(0));
  }
  return table;
}
function initArr(maxLen) {
  const row = [];
  for (let i = 0; i <= maxLen; i++) {
    row[i] = 0;
  }
  return row;
}
var _minWordMatchPos = initArr(2 * _maxLen);
var _maxWordMatchPos = initArr(2 * _maxLen);
var _diag = initTable();
var _table = initTable();
var _arrows = initTable();
var Arrow;
(function(Arrow2) {
  Arrow2[Arrow2["Diag"] = 1] = "Diag";
  Arrow2[Arrow2["Left"] = 2] = "Left";
  Arrow2[Arrow2["LeftLeft"] = 3] = "LeftLeft";
})(Arrow || (Arrow = {}));
var FuzzyScore;
(function(FuzzyScore2) {
  FuzzyScore2.Default = [-100, 0];
  function isDefault(score) {
    return !score || score.length === 2 && score[0] === -100 && score[1] === 0;
  }
  FuzzyScore2.isDefault = isDefault;
})(FuzzyScore || (FuzzyScore = {}));
var $Wl = class {
  static {
    this.default = { boostFullMatch: true, firstMatchCanBeWeak: false };
  }
  constructor(firstMatchCanBeWeak, boostFullMatch) {
    this.firstMatchCanBeWeak = firstMatchCanBeWeak;
    this.boostFullMatch = boostFullMatch;
  }
};

// out-build/vs/base/common/codiconsUtil.js
var _codiconFontCharacters = /* @__PURE__ */ Object.create(null);
function $1l(id2, fontCharacter) {
  if ($zg(fontCharacter)) {
    const val = _codiconFontCharacters[fontCharacter];
    if (val === void 0) {
      throw new Error(`${id2} references an unknown codicon: ${fontCharacter}`);
    }
    fontCharacter = val;
  }
  _codiconFontCharacters[id2] = fontCharacter;
  return { id: id2 };
}
function $2l() {
  return _codiconFontCharacters;
}

// out-build/vs/base/common/codiconsLibrary.js
var $3l = {
  add: $1l("add", 6e4),
  plus: $1l("plus", 6e4),
  gistNew: $1l("gist-new", 6e4),
  repoCreate: $1l("repo-create", 6e4),
  lightbulb: $1l("lightbulb", 60001),
  lightBulb: $1l("light-bulb", 60001),
  repo: $1l("repo", 60002),
  repoDelete: $1l("repo-delete", 60002),
  gistFork: $1l("gist-fork", 60003),
  repoForked: $1l("repo-forked", 60003),
  gitPullRequest: $1l("git-pull-request", 60004),
  gitPullRequestAbandoned: $1l("git-pull-request-abandoned", 60004),
  recordKeys: $1l("record-keys", 60005),
  keyboard: $1l("keyboard", 60005),
  tag: $1l("tag", 60006),
  gitPullRequestLabel: $1l("git-pull-request-label", 60006),
  tagAdd: $1l("tag-add", 60006),
  tagRemove: $1l("tag-remove", 60006),
  person: $1l("person", 60007),
  personFollow: $1l("person-follow", 60007),
  personOutline: $1l("person-outline", 60007),
  personFilled: $1l("person-filled", 60007),
  gitBranch: $1l("git-branch", 60008),
  gitBranchCreate: $1l("git-branch-create", 60008),
  gitBranchDelete: $1l("git-branch-delete", 60008),
  sourceControl: $1l("source-control", 60008),
  mirror: $1l("mirror", 60009),
  mirrorPublic: $1l("mirror-public", 60009),
  star: $1l("star", 60010),
  starAdd: $1l("star-add", 60010),
  starDelete: $1l("star-delete", 60010),
  starEmpty: $1l("star-empty", 60010),
  comment: $1l("comment", 60011),
  commentAdd: $1l("comment-add", 60011),
  alert: $1l("alert", 60012),
  warning: $1l("warning", 60012),
  search: $1l("search", 60013),
  searchSave: $1l("search-save", 60013),
  logOut: $1l("log-out", 60014),
  signOut: $1l("sign-out", 60014),
  logIn: $1l("log-in", 60015),
  signIn: $1l("sign-in", 60015),
  eye: $1l("eye", 60016),
  eyeUnwatch: $1l("eye-unwatch", 60016),
  eyeWatch: $1l("eye-watch", 60016),
  circleFilled: $1l("circle-filled", 60017),
  primitiveDot: $1l("primitive-dot", 60017),
  closeDirty: $1l("close-dirty", 60017),
  debugBreakpoint: $1l("debug-breakpoint", 60017),
  debugBreakpointDisabled: $1l("debug-breakpoint-disabled", 60017),
  debugHint: $1l("debug-hint", 60017),
  terminalDecorationSuccess: $1l("terminal-decoration-success", 60017),
  primitiveSquare: $1l("primitive-square", 60018),
  edit: $1l("edit", 60019),
  pencil: $1l("pencil", 60019),
  info: $1l("info", 60020),
  issueOpened: $1l("issue-opened", 60020),
  gistPrivate: $1l("gist-private", 60021),
  gitForkPrivate: $1l("git-fork-private", 60021),
  lock: $1l("lock", 60021),
  mirrorPrivate: $1l("mirror-private", 60021),
  close: $1l("close", 60022),
  removeClose: $1l("remove-close", 60022),
  x: $1l("x", 60022),
  repoSync: $1l("repo-sync", 60023),
  sync: $1l("sync", 60023),
  clone: $1l("clone", 60024),
  desktopDownload: $1l("desktop-download", 60024),
  beaker: $1l("beaker", 60025),
  microscope: $1l("microscope", 60025),
  vm: $1l("vm", 60026),
  deviceDesktop: $1l("device-desktop", 60026),
  file: $1l("file", 60027),
  fileText: $1l("file-text", 60027),
  more: $1l("more", 60028),
  ellipsis: $1l("ellipsis", 60028),
  kebabHorizontal: $1l("kebab-horizontal", 60028),
  mailReply: $1l("mail-reply", 60029),
  reply: $1l("reply", 60029),
  organization: $1l("organization", 60030),
  organizationFilled: $1l("organization-filled", 60030),
  organizationOutline: $1l("organization-outline", 60030),
  newFile: $1l("new-file", 60031),
  fileAdd: $1l("file-add", 60031),
  newFolder: $1l("new-folder", 60032),
  fileDirectoryCreate: $1l("file-directory-create", 60032),
  trash: $1l("trash", 60033),
  trashcan: $1l("trashcan", 60033),
  history: $1l("history", 60034),
  clock: $1l("clock", 60034),
  folder: $1l("folder", 60035),
  fileDirectory: $1l("file-directory", 60035),
  symbolFolder: $1l("symbol-folder", 60035),
  logoGithub: $1l("logo-github", 60036),
  markGithub: $1l("mark-github", 60036),
  github: $1l("github", 60036),
  terminal: $1l("terminal", 60037),
  console: $1l("console", 60037),
  repl: $1l("repl", 60037),
  zap: $1l("zap", 60038),
  symbolEvent: $1l("symbol-event", 60038),
  error: $1l("error", 60039),
  stop: $1l("stop", 60039),
  variable: $1l("variable", 60040),
  symbolVariable: $1l("symbol-variable", 60040),
  array: $1l("array", 60042),
  symbolArray: $1l("symbol-array", 60042),
  symbolModule: $1l("symbol-module", 60043),
  symbolPackage: $1l("symbol-package", 60043),
  symbolNamespace: $1l("symbol-namespace", 60043),
  symbolObject: $1l("symbol-object", 60043),
  symbolMethod: $1l("symbol-method", 60044),
  symbolFunction: $1l("symbol-function", 60044),
  symbolConstructor: $1l("symbol-constructor", 60044),
  symbolBoolean: $1l("symbol-boolean", 60047),
  symbolNull: $1l("symbol-null", 60047),
  symbolNumeric: $1l("symbol-numeric", 60048),
  symbolNumber: $1l("symbol-number", 60048),
  symbolStructure: $1l("symbol-structure", 60049),
  symbolStruct: $1l("symbol-struct", 60049),
  symbolParameter: $1l("symbol-parameter", 60050),
  symbolTypeParameter: $1l("symbol-type-parameter", 60050),
  symbolKey: $1l("symbol-key", 60051),
  symbolText: $1l("symbol-text", 60051),
  symbolReference: $1l("symbol-reference", 60052),
  goToFile: $1l("go-to-file", 60052),
  symbolEnum: $1l("symbol-enum", 60053),
  symbolValue: $1l("symbol-value", 60053),
  symbolRuler: $1l("symbol-ruler", 60054),
  symbolUnit: $1l("symbol-unit", 60054),
  activateBreakpoints: $1l("activate-breakpoints", 60055),
  archive: $1l("archive", 60056),
  arrowBoth: $1l("arrow-both", 60057),
  arrowDown: $1l("arrow-down", 60058),
  arrowLeft: $1l("arrow-left", 60059),
  arrowRight: $1l("arrow-right", 60060),
  arrowSmallDown: $1l("arrow-small-down", 60061),
  arrowSmallLeft: $1l("arrow-small-left", 60062),
  arrowSmallRight: $1l("arrow-small-right", 60063),
  arrowSmallUp: $1l("arrow-small-up", 60064),
  arrowUp: $1l("arrow-up", 60065),
  bell: $1l("bell", 60066),
  bold: $1l("bold", 60067),
  book: $1l("book", 60068),
  bookmark: $1l("bookmark", 60069),
  debugBreakpointConditionalUnverified: $1l("debug-breakpoint-conditional-unverified", 60070),
  debugBreakpointConditional: $1l("debug-breakpoint-conditional", 60071),
  debugBreakpointConditionalDisabled: $1l("debug-breakpoint-conditional-disabled", 60071),
  debugBreakpointDataUnverified: $1l("debug-breakpoint-data-unverified", 60072),
  debugBreakpointData: $1l("debug-breakpoint-data", 60073),
  debugBreakpointDataDisabled: $1l("debug-breakpoint-data-disabled", 60073),
  debugBreakpointLogUnverified: $1l("debug-breakpoint-log-unverified", 60074),
  debugBreakpointLog: $1l("debug-breakpoint-log", 60075),
  debugBreakpointLogDisabled: $1l("debug-breakpoint-log-disabled", 60075),
  briefcase: $1l("briefcase", 60076),
  broadcast: $1l("broadcast", 60077),
  browser: $1l("browser", 60078),
  bug: $1l("bug", 60079),
  calendar: $1l("calendar", 60080),
  caseSensitive: $1l("case-sensitive", 60081),
  check: $1l("check", 60082),
  checklist: $1l("checklist", 60083),
  chevronDown: $1l("chevron-down", 60084),
  chevronLeft: $1l("chevron-left", 60085),
  chevronRight: $1l("chevron-right", 60086),
  chevronUp: $1l("chevron-up", 60087),
  chromeClose: $1l("chrome-close", 60088),
  chromeMaximize: $1l("chrome-maximize", 60089),
  chromeMinimize: $1l("chrome-minimize", 60090),
  chromeRestore: $1l("chrome-restore", 60091),
  circleOutline: $1l("circle-outline", 60092),
  circle: $1l("circle", 60092),
  debugBreakpointUnverified: $1l("debug-breakpoint-unverified", 60092),
  terminalDecorationIncomplete: $1l("terminal-decoration-incomplete", 60092),
  circleSlash: $1l("circle-slash", 60093),
  circuitBoard: $1l("circuit-board", 60094),
  clearAll: $1l("clear-all", 60095),
  clippy: $1l("clippy", 60096),
  closeAll: $1l("close-all", 60097),
  cloudDownload: $1l("cloud-download", 60098),
  cloudUpload: $1l("cloud-upload", 60099),
  code: $1l("code", 60100),
  collapseAll: $1l("collapse-all", 60101),
  colorMode: $1l("color-mode", 60102),
  commentDiscussion: $1l("comment-discussion", 60103),
  creditCard: $1l("credit-card", 60105),
  dash: $1l("dash", 60108),
  dashboard: $1l("dashboard", 60109),
  database: $1l("database", 60110),
  debugContinue: $1l("debug-continue", 60111),
  debugDisconnect: $1l("debug-disconnect", 60112),
  debugPause: $1l("debug-pause", 60113),
  debugRestart: $1l("debug-restart", 60114),
  debugStart: $1l("debug-start", 60115),
  debugStepInto: $1l("debug-step-into", 60116),
  debugStepOut: $1l("debug-step-out", 60117),
  debugStepOver: $1l("debug-step-over", 60118),
  debugStop: $1l("debug-stop", 60119),
  debug: $1l("debug", 60120),
  deviceCameraVideo: $1l("device-camera-video", 60121),
  deviceCamera: $1l("device-camera", 60122),
  deviceMobile: $1l("device-mobile", 60123),
  diffAdded: $1l("diff-added", 60124),
  diffIgnored: $1l("diff-ignored", 60125),
  diffModified: $1l("diff-modified", 60126),
  diffRemoved: $1l("diff-removed", 60127),
  diffRenamed: $1l("diff-renamed", 60128),
  diff: $1l("diff", 60129),
  diffSidebyside: $1l("diff-sidebyside", 60129),
  discard: $1l("discard", 60130),
  editorLayout: $1l("editor-layout", 60131),
  emptyWindow: $1l("empty-window", 60132),
  exclude: $1l("exclude", 60133),
  extensions: $1l("extensions", 60134),
  eyeClosed: $1l("eye-closed", 60135),
  fileBinary: $1l("file-binary", 60136),
  fileCode: $1l("file-code", 60137),
  fileMedia: $1l("file-media", 60138),
  filePdf: $1l("file-pdf", 60139),
  fileSubmodule: $1l("file-submodule", 60140),
  fileSymlinkDirectory: $1l("file-symlink-directory", 60141),
  fileSymlinkFile: $1l("file-symlink-file", 60142),
  fileZip: $1l("file-zip", 60143),
  files: $1l("files", 60144),
  filter: $1l("filter", 60145),
  flame: $1l("flame", 60146),
  foldDown: $1l("fold-down", 60147),
  foldUp: $1l("fold-up", 60148),
  fold: $1l("fold", 60149),
  folderActive: $1l("folder-active", 60150),
  folderOpened: $1l("folder-opened", 60151),
  gear: $1l("gear", 60152),
  gift: $1l("gift", 60153),
  gistSecret: $1l("gist-secret", 60154),
  gist: $1l("gist", 60155),
  gitCommit: $1l("git-commit", 60156),
  gitCompare: $1l("git-compare", 60157),
  compareChanges: $1l("compare-changes", 60157),
  gitMerge: $1l("git-merge", 60158),
  githubAction: $1l("github-action", 60159),
  githubAlt: $1l("github-alt", 60160),
  globe: $1l("globe", 60161),
  grabber: $1l("grabber", 60162),
  graph: $1l("graph", 60163),
  gripper: $1l("gripper", 60164),
  heart: $1l("heart", 60165),
  home: $1l("home", 60166),
  horizontalRule: $1l("horizontal-rule", 60167),
  hubot: $1l("hubot", 60168),
  inbox: $1l("inbox", 60169),
  issueReopened: $1l("issue-reopened", 60171),
  issues: $1l("issues", 60172),
  italic: $1l("italic", 60173),
  jersey: $1l("jersey", 60174),
  json: $1l("json", 60175),
  kebabVertical: $1l("kebab-vertical", 60176),
  key: $1l("key", 60177),
  law: $1l("law", 60178),
  lightbulbAutofix: $1l("lightbulb-autofix", 60179),
  linkExternal: $1l("link-external", 60180),
  link: $1l("link", 60181),
  listOrdered: $1l("list-ordered", 60182),
  listUnordered: $1l("list-unordered", 60183),
  liveShare: $1l("live-share", 60184),
  loading: $1l("loading", 60185),
  location: $1l("location", 60186),
  mailRead: $1l("mail-read", 60187),
  mail: $1l("mail", 60188),
  markdown: $1l("markdown", 60189),
  megaphone: $1l("megaphone", 60190),
  mention: $1l("mention", 60191),
  milestone: $1l("milestone", 60192),
  gitPullRequestMilestone: $1l("git-pull-request-milestone", 60192),
  mortarBoard: $1l("mortar-board", 60193),
  move: $1l("move", 60194),
  multipleWindows: $1l("multiple-windows", 60195),
  mute: $1l("mute", 60196),
  noNewline: $1l("no-newline", 60197),
  note: $1l("note", 60198),
  octoface: $1l("octoface", 60199),
  openPreview: $1l("open-preview", 60200),
  package: $1l("package", 60201),
  paintcan: $1l("paintcan", 60202),
  pin: $1l("pin", 60203),
  play: $1l("play", 60204),
  run: $1l("run", 60204),
  plug: $1l("plug", 60205),
  preserveCase: $1l("preserve-case", 60206),
  preview: $1l("preview", 60207),
  project: $1l("project", 60208),
  pulse: $1l("pulse", 60209),
  question: $1l("question", 60210),
  quote: $1l("quote", 60211),
  radioTower: $1l("radio-tower", 60212),
  reactions: $1l("reactions", 60213),
  references: $1l("references", 60214),
  refresh: $1l("refresh", 60215),
  regex: $1l("regex", 60216),
  remoteExplorer: $1l("remote-explorer", 60217),
  remote: $1l("remote", 60218),
  remove: $1l("remove", 60219),
  replaceAll: $1l("replace-all", 60220),
  replace: $1l("replace", 60221),
  repoClone: $1l("repo-clone", 60222),
  repoForcePush: $1l("repo-force-push", 60223),
  repoPull: $1l("repo-pull", 60224),
  repoPush: $1l("repo-push", 60225),
  report: $1l("report", 60226),
  requestChanges: $1l("request-changes", 60227),
  rocket: $1l("rocket", 60228),
  rootFolderOpened: $1l("root-folder-opened", 60229),
  rootFolder: $1l("root-folder", 60230),
  rss: $1l("rss", 60231),
  ruby: $1l("ruby", 60232),
  saveAll: $1l("save-all", 60233),
  saveAs: $1l("save-as", 60234),
  save: $1l("save", 60235),
  screenFull: $1l("screen-full", 60236),
  screenNormal: $1l("screen-normal", 60237),
  searchStop: $1l("search-stop", 60238),
  server: $1l("server", 60240),
  settingsGear: $1l("settings-gear", 60241),
  settings: $1l("settings", 60242),
  shield: $1l("shield", 60243),
  smiley: $1l("smiley", 60244),
  sortPrecedence: $1l("sort-precedence", 60245),
  splitHorizontal: $1l("split-horizontal", 60246),
  splitVertical: $1l("split-vertical", 60247),
  squirrel: $1l("squirrel", 60248),
  starFull: $1l("star-full", 60249),
  starHalf: $1l("star-half", 60250),
  symbolClass: $1l("symbol-class", 60251),
  symbolColor: $1l("symbol-color", 60252),
  symbolConstant: $1l("symbol-constant", 60253),
  symbolEnumMember: $1l("symbol-enum-member", 60254),
  symbolField: $1l("symbol-field", 60255),
  symbolFile: $1l("symbol-file", 60256),
  symbolInterface: $1l("symbol-interface", 60257),
  symbolKeyword: $1l("symbol-keyword", 60258),
  symbolMisc: $1l("symbol-misc", 60259),
  symbolOperator: $1l("symbol-operator", 60260),
  symbolProperty: $1l("symbol-property", 60261),
  wrench: $1l("wrench", 60261),
  wrenchSubaction: $1l("wrench-subaction", 60261),
  symbolSnippet: $1l("symbol-snippet", 60262),
  tasklist: $1l("tasklist", 60263),
  telescope: $1l("telescope", 60264),
  textSize: $1l("text-size", 60265),
  threeBars: $1l("three-bars", 60266),
  thumbsdown: $1l("thumbsdown", 60267),
  thumbsup: $1l("thumbsup", 60268),
  tools: $1l("tools", 60269),
  triangleDown: $1l("triangle-down", 60270),
  triangleLeft: $1l("triangle-left", 60271),
  triangleRight: $1l("triangle-right", 60272),
  triangleUp: $1l("triangle-up", 60273),
  twitter: $1l("twitter", 60274),
  unfold: $1l("unfold", 60275),
  unlock: $1l("unlock", 60276),
  unmute: $1l("unmute", 60277),
  unverified: $1l("unverified", 60278),
  verified: $1l("verified", 60279),
  versions: $1l("versions", 60280),
  vmActive: $1l("vm-active", 60281),
  vmOutline: $1l("vm-outline", 60282),
  vmRunning: $1l("vm-running", 60283),
  watch: $1l("watch", 60284),
  whitespace: $1l("whitespace", 60285),
  wholeWord: $1l("whole-word", 60286),
  window: $1l("window", 60287),
  wordWrap: $1l("word-wrap", 60288),
  zoomIn: $1l("zoom-in", 60289),
  zoomOut: $1l("zoom-out", 60290),
  listFilter: $1l("list-filter", 60291),
  listFlat: $1l("list-flat", 60292),
  listSelection: $1l("list-selection", 60293),
  selection: $1l("selection", 60293),
  listTree: $1l("list-tree", 60294),
  debugBreakpointFunctionUnverified: $1l("debug-breakpoint-function-unverified", 60295),
  debugBreakpointFunction: $1l("debug-breakpoint-function", 60296),
  debugBreakpointFunctionDisabled: $1l("debug-breakpoint-function-disabled", 60296),
  debugStackframeActive: $1l("debug-stackframe-active", 60297),
  circleSmallFilled: $1l("circle-small-filled", 60298),
  debugStackframeDot: $1l("debug-stackframe-dot", 60298),
  terminalDecorationMark: $1l("terminal-decoration-mark", 60298),
  debugStackframe: $1l("debug-stackframe", 60299),
  debugStackframeFocused: $1l("debug-stackframe-focused", 60299),
  debugBreakpointUnsupported: $1l("debug-breakpoint-unsupported", 60300),
  symbolString: $1l("symbol-string", 60301),
  debugReverseContinue: $1l("debug-reverse-continue", 60302),
  debugStepBack: $1l("debug-step-back", 60303),
  debugRestartFrame: $1l("debug-restart-frame", 60304),
  debugAlt: $1l("debug-alt", 60305),
  callIncoming: $1l("call-incoming", 60306),
  callOutgoing: $1l("call-outgoing", 60307),
  menu: $1l("menu", 60308),
  expandAll: $1l("expand-all", 60309),
  feedback: $1l("feedback", 60310),
  gitPullRequestReviewer: $1l("git-pull-request-reviewer", 60310),
  groupByRefType: $1l("group-by-ref-type", 60311),
  ungroupByRefType: $1l("ungroup-by-ref-type", 60312),
  account: $1l("account", 60313),
  gitPullRequestAssignee: $1l("git-pull-request-assignee", 60313),
  bellDot: $1l("bell-dot", 60314),
  debugConsole: $1l("debug-console", 60315),
  library: $1l("library", 60316),
  output: $1l("output", 60317),
  runAll: $1l("run-all", 60318),
  syncIgnored: $1l("sync-ignored", 60319),
  pinned: $1l("pinned", 60320),
  githubInverted: $1l("github-inverted", 60321),
  serverProcess: $1l("server-process", 60322),
  serverEnvironment: $1l("server-environment", 60323),
  pass: $1l("pass", 60324),
  issueClosed: $1l("issue-closed", 60324),
  stopCircle: $1l("stop-circle", 60325),
  playCircle: $1l("play-circle", 60326),
  record: $1l("record", 60327),
  debugAltSmall: $1l("debug-alt-small", 60328),
  vmConnect: $1l("vm-connect", 60329),
  cloud: $1l("cloud", 60330),
  merge: $1l("merge", 60331),
  export: $1l("export", 60332),
  graphLeft: $1l("graph-left", 60333),
  magnet: $1l("magnet", 60334),
  notebook: $1l("notebook", 60335),
  redo: $1l("redo", 60336),
  checkAll: $1l("check-all", 60337),
  pinnedDirty: $1l("pinned-dirty", 60338),
  passFilled: $1l("pass-filled", 60339),
  circleLargeFilled: $1l("circle-large-filled", 60340),
  circleLarge: $1l("circle-large", 60341),
  circleLargeOutline: $1l("circle-large-outline", 60341),
  combine: $1l("combine", 60342),
  gather: $1l("gather", 60342),
  table: $1l("table", 60343),
  variableGroup: $1l("variable-group", 60344),
  typeHierarchy: $1l("type-hierarchy", 60345),
  typeHierarchySub: $1l("type-hierarchy-sub", 60346),
  typeHierarchySuper: $1l("type-hierarchy-super", 60347),
  gitPullRequestCreate: $1l("git-pull-request-create", 60348),
  runAbove: $1l("run-above", 60349),
  runBelow: $1l("run-below", 60350),
  notebookTemplate: $1l("notebook-template", 60351),
  debugRerun: $1l("debug-rerun", 60352),
  workspaceTrusted: $1l("workspace-trusted", 60353),
  workspaceUntrusted: $1l("workspace-untrusted", 60354),
  workspaceUnknown: $1l("workspace-unknown", 60355),
  terminalCmd: $1l("terminal-cmd", 60356),
  terminalDebian: $1l("terminal-debian", 60357),
  terminalLinux: $1l("terminal-linux", 60358),
  terminalPowershell: $1l("terminal-powershell", 60359),
  terminalTmux: $1l("terminal-tmux", 60360),
  terminalUbuntu: $1l("terminal-ubuntu", 60361),
  terminalBash: $1l("terminal-bash", 60362),
  arrowSwap: $1l("arrow-swap", 60363),
  copy: $1l("copy", 60364),
  personAdd: $1l("person-add", 60365),
  filterFilled: $1l("filter-filled", 60366),
  wand: $1l("wand", 60367),
  debugLineByLine: $1l("debug-line-by-line", 60368),
  inspect: $1l("inspect", 60369),
  layers: $1l("layers", 60370),
  layersDot: $1l("layers-dot", 60371),
  layersActive: $1l("layers-active", 60372),
  compass: $1l("compass", 60373),
  compassDot: $1l("compass-dot", 60374),
  compassActive: $1l("compass-active", 60375),
  azure: $1l("azure", 60376),
  issueDraft: $1l("issue-draft", 60377),
  gitPullRequestClosed: $1l("git-pull-request-closed", 60378),
  gitPullRequestDraft: $1l("git-pull-request-draft", 60379),
  debugAll: $1l("debug-all", 60380),
  debugCoverage: $1l("debug-coverage", 60381),
  runErrors: $1l("run-errors", 60382),
  folderLibrary: $1l("folder-library", 60383),
  debugContinueSmall: $1l("debug-continue-small", 60384),
  beakerStop: $1l("beaker-stop", 60385),
  graphLine: $1l("graph-line", 60386),
  graphScatter: $1l("graph-scatter", 60387),
  pieChart: $1l("pie-chart", 60388),
  bracket: $1l("bracket", 60175),
  bracketDot: $1l("bracket-dot", 60389),
  bracketError: $1l("bracket-error", 60390),
  lockSmall: $1l("lock-small", 60391),
  azureDevops: $1l("azure-devops", 60392),
  verifiedFilled: $1l("verified-filled", 60393),
  newline: $1l("newline", 60394),
  layout: $1l("layout", 60395),
  layoutActivitybarLeft: $1l("layout-activitybar-left", 60396),
  layoutActivitybarRight: $1l("layout-activitybar-right", 60397),
  layoutPanelLeft: $1l("layout-panel-left", 60398),
  layoutPanelCenter: $1l("layout-panel-center", 60399),
  layoutPanelJustify: $1l("layout-panel-justify", 60400),
  layoutPanelRight: $1l("layout-panel-right", 60401),
  layoutPanel: $1l("layout-panel", 60402),
  layoutSidebarLeft: $1l("layout-sidebar-left", 60403),
  layoutSidebarRight: $1l("layout-sidebar-right", 60404),
  layoutStatusbar: $1l("layout-statusbar", 60405),
  layoutMenubar: $1l("layout-menubar", 60406),
  layoutCentered: $1l("layout-centered", 60407),
  target: $1l("target", 60408),
  indent: $1l("indent", 60409),
  recordSmall: $1l("record-small", 60410),
  errorSmall: $1l("error-small", 60411),
  terminalDecorationError: $1l("terminal-decoration-error", 60411),
  arrowCircleDown: $1l("arrow-circle-down", 60412),
  arrowCircleLeft: $1l("arrow-circle-left", 60413),
  arrowCircleRight: $1l("arrow-circle-right", 60414),
  arrowCircleUp: $1l("arrow-circle-up", 60415),
  layoutSidebarRightOff: $1l("layout-sidebar-right-off", 60416),
  layoutPanelOff: $1l("layout-panel-off", 60417),
  layoutSidebarLeftOff: $1l("layout-sidebar-left-off", 60418),
  blank: $1l("blank", 60419),
  heartFilled: $1l("heart-filled", 60420),
  map: $1l("map", 60421),
  mapHorizontal: $1l("map-horizontal", 60421),
  foldHorizontal: $1l("fold-horizontal", 60421),
  mapFilled: $1l("map-filled", 60422),
  mapHorizontalFilled: $1l("map-horizontal-filled", 60422),
  foldHorizontalFilled: $1l("fold-horizontal-filled", 60422),
  circleSmall: $1l("circle-small", 60423),
  bellSlash: $1l("bell-slash", 60424),
  bellSlashDot: $1l("bell-slash-dot", 60425),
  commentUnresolved: $1l("comment-unresolved", 60426),
  gitPullRequestGoToChanges: $1l("git-pull-request-go-to-changes", 60427),
  gitPullRequestNewChanges: $1l("git-pull-request-new-changes", 60428),
  searchFuzzy: $1l("search-fuzzy", 60429),
  commentDraft: $1l("comment-draft", 60430),
  send: $1l("send", 60431),
  sparkle: $1l("sparkle", 60432),
  insert: $1l("insert", 60433),
  mic: $1l("mic", 60434),
  thumbsdownFilled: $1l("thumbsdown-filled", 60435),
  thumbsupFilled: $1l("thumbsup-filled", 60436),
  coffee: $1l("coffee", 60437),
  snake: $1l("snake", 60438),
  game: $1l("game", 60439),
  vr: $1l("vr", 60440),
  chip: $1l("chip", 60441),
  piano: $1l("piano", 60442),
  music: $1l("music", 60443),
  micFilled: $1l("mic-filled", 60444),
  repoFetch: $1l("repo-fetch", 60445),
  copilot: $1l("copilot", 60446),
  lightbulbSparkle: $1l("lightbulb-sparkle", 60447),
  robot: $1l("robot", 60448),
  sparkleFilled: $1l("sparkle-filled", 60449),
  diffSingle: $1l("diff-single", 60450),
  diffMultiple: $1l("diff-multiple", 60451),
  surroundWith: $1l("surround-with", 60452),
  share: $1l("share", 60453),
  gitStash: $1l("git-stash", 60454),
  gitStashApply: $1l("git-stash-apply", 60455),
  gitStashPop: $1l("git-stash-pop", 60456),
  vscode: $1l("vscode", 60457),
  vscodeInsiders: $1l("vscode-insiders", 60458),
  codeOss: $1l("code-oss", 60459),
  runCoverage: $1l("run-coverage", 60460),
  runAllCoverage: $1l("run-all-coverage", 60461),
  coverage: $1l("coverage", 60462),
  githubProject: $1l("github-project", 60463),
  mapVertical: $1l("map-vertical", 60464),
  foldVertical: $1l("fold-vertical", 60464),
  mapVerticalFilled: $1l("map-vertical-filled", 60465),
  foldVerticalFilled: $1l("fold-vertical-filled", 60465),
  goToSearch: $1l("go-to-search", 60466),
  percentage: $1l("percentage", 60467),
  sortPercentage: $1l("sort-percentage", 60467),
  attach: $1l("attach", 60468),
  goToEditingSession: $1l("go-to-editing-session", 60469),
  editSession: $1l("edit-session", 60470),
  codeReview: $1l("code-review", 60471),
  copilotWarning: $1l("copilot-warning", 60472),
  python: $1l("python", 60473),
  copilotLarge: $1l("copilot-large", 60474),
  copilotWarningLarge: $1l("copilot-warning-large", 60475)
};

// out-build/vs/base/common/codicons.js
var $5l = {
  dialogError: $1l("dialog-error", "error"),
  dialogWarning: $1l("dialog-warning", "warning"),
  dialogInfo: $1l("dialog-info", "info"),
  dialogClose: $1l("dialog-close", "close"),
  treeItemExpanded: $1l("tree-item-expanded", "chevron-down"),
  // collapsed is done with rotation
  treeFilterOnTypeOn: $1l("tree-filter-on-type-on", "list-filter"),
  treeFilterOnTypeOff: $1l("tree-filter-on-type-off", "list-selection"),
  treeFilterClear: $1l("tree-filter-clear", "close"),
  treeItemLoading: $1l("tree-item-loading", "loading"),
  menuSelection: $1l("menu-selection", "check"),
  menuSubmenu: $1l("menu-submenu", "chevron-right"),
  menuBarMore: $1l("menubar-more", "more"),
  scrollbarButtonLeft: $1l("scrollbar-button-left", "triangle-left"),
  scrollbarButtonRight: $1l("scrollbar-button-right", "triangle-right"),
  scrollbarButtonUp: $1l("scrollbar-button-up", "triangle-up"),
  scrollbarButtonDown: $1l("scrollbar-button-down", "triangle-down"),
  toolBarMore: $1l("toolbar-more", "more"),
  quickInputBack: $1l("quick-input-back", "arrow-left"),
  dropDownButton: $1l("drop-down-button", 60084),
  symbolCustomColor: $1l("symbol-customcolor", 60252),
  exportIcon: $1l("export", 60332),
  workspaceUnspecified: $1l("workspace-unspecified", 60355),
  newLine: $1l("newline", 60394),
  thumbsDownFilled: $1l("thumbsdown-filled", 60435),
  thumbsUpFilled: $1l("thumbsup-filled", 60436),
  gitFetch: $1l("git-fetch", 60445),
  lightbulbSparkleAutofix: $1l("lightbulb-sparkle-autofix", 60447),
  debugBreakpointPending: $1l("debug-breakpoint-pending", 60377)
};
var $6l = {
  ...$3l,
  ...$5l
};

// out-build/vs/base/common/themables.js
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 match = ThemeIconIdRegex.exec(icon.id);
    if (!match) {
      return asClassNameArray($6l.error);
    }
    const [, id2, modifier] = match;
    const classNames = ["codicon", "codicon-" + id2];
    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 fromString(str) {
    const match = _regexFromString.exec(str);
    if (!match) {
      return void 0;
    }
    const [, name] = match;
    return { id: name };
  }
  ThemeIcon2.fromString = fromString;
  function fromId(id2) {
    return { id: id2 };
  }
  ThemeIcon2.fromId = fromId;
  function modify(icon, modifier) {
    let id2 = icon.id;
    const tildeIndex = id2.lastIndexOf("~");
    if (tildeIndex !== -1) {
      id2 = id2.substring(0, tildeIndex);
    }
    if (modifier) {
      id2 = `${id2}~${modifier}`;
    }
    return { id: id2 };
  }
  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 isEqual(ti1, ti2) {
    return ti1.id === ti2.id && ti1.color?.id === ti2.color?.id;
  }
  ThemeIcon2.isEqual = isEqual;
})(ThemeIcon || (ThemeIcon = {}));

// out-build/vs/base/common/iconLabels.js
var iconsRegex = new RegExp(`\\$\\(${ThemeIcon.iconNameExpression}(?:${ThemeIcon.iconModifierExpression})?\\)`, "g");
var escapeIconsRegex = new RegExp(`(\\\\)?${iconsRegex.source}`, "g");
function $8l(text) {
  return text.replace(escapeIconsRegex, (match, escaped) => escaped ? match : `\\${match}`);
}
var markdownEscapedIconsRegex = new RegExp(`\\\\${iconsRegex.source}`, "g");
var stripIconsRegex = new RegExp(`(\\s)?(\\\\)?${iconsRegex.source}(\\s)?`, "g");
var _parseIconsRegex = new RegExp(`\\$\\(${ThemeIcon.iconNameCharacter}+\\)`, "g");

// out-build/vs/base/common/htmlContent.js
var MarkdownStringTextNewlineStyle;
(function(MarkdownStringTextNewlineStyle2) {
  MarkdownStringTextNewlineStyle2[MarkdownStringTextNewlineStyle2["Paragraph"] = 0] = "Paragraph";
  MarkdownStringTextNewlineStyle2[MarkdownStringTextNewlineStyle2["Break"] = 1] = "Break";
})(MarkdownStringTextNewlineStyle || (MarkdownStringTextNewlineStyle = {}));
var $bm = class {
  constructor(value = "", isTrustedOrOptions = false) {
    this.value = value;
    if (typeof this.value !== "string") {
      throw $nb("value");
    }
    if (typeof isTrustedOrOptions === "boolean") {
      this.isTrusted = isTrustedOrOptions;
      this.supportThemeIcons = false;
      this.supportHtml = false;
    } else {
      this.isTrusted = isTrustedOrOptions.isTrusted ?? void 0;
      this.supportThemeIcons = isTrustedOrOptions.supportThemeIcons ?? false;
      this.supportHtml = isTrustedOrOptions.supportHtml ?? false;
    }
  }
  appendText(value, newlineStyle = 0) {
    this.value += $fm(this.supportThemeIcons ? $8l(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 += `
${$gm(code, langId)}
`;
    return this;
  }
  appendLink(target, label, title) {
    this.value += "[";
    this.value += this.c(label, "]");
    this.value += "](";
    this.value += this.c(String(target), ")");
    if (title) {
      this.value += ` "${this.c(this.c(title, '"'), ")")}"`;
    }
    this.value += ")";
    return this;
  }
  c(value, ch) {
    const r = new RegExp($Af(ch), "g");
    return value.replace(r, (match, offset) => {
      if (value.charAt(offset - 1) !== "\\") {
        return `\\${match}`;
      } else {
        return match;
      }
    });
  }
};
function $dm(thing) {
  if (thing instanceof $bm) {
    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 $fm(text) {
  return text.replace(/[\\`*_{}[\]()#+\-!~]/g, "\\$&");
}
function $gm(code, langId) {
  const longestFenceLength = code.match(/^`+/gm)?.reduce((a, b) => a.length > b.length ? a : b).length ?? 0;
  const desiredFenceLength = longestFenceLength >= 3 ? longestFenceLength + 1 : 3;
  return [
    `${"`".repeat(desiredFenceLength)}${langId}`,
    code,
    `${"`".repeat(desiredFenceLength)}`
  ].join("\n");
}
function $jm(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 };
}

// out-build/vs/base/common/marked/marked.js
function _getDefaults() {
  return {
    async: false,
    breaks: false,
    extensions: null,
    gfm: true,
    hooks: null,
    pedantic: false,
    renderer: null,
    silent: false,
    tokenizer: null,
    walkTokens: null
  };
}
var _defaults = _getDefaults();
function changeDefaults(newDefaults) {
  _defaults = newDefaults;
}
var escapeTest = /[&<>"']/;
var escapeReplace = new RegExp(escapeTest.source, "g");
var escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
var escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, "g");
var escapeReplacements = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
var getEscapeReplacement = (ch) => escapeReplacements[ch];
function escape$1(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 caret = /(^|[^\[])\^/g;
function edit(regex, opt) {
  let source = typeof regex === "string" ? regex : regex.source;
  opt = opt || "";
  const obj = {
    replace: (name, val) => {
      let valSource = typeof val === "string" ? val : val.source;
      valSource = valSource.replace(caret, "$1");
      source = source.replace(name, valSource);
      return obj;
    },
    getRegex: () => {
      return new RegExp(source, opt);
    }
  };
  return obj;
}
function cleanUrl(href) {
  try {
    href = encodeURI(href).replace(/%25/g, "%");
  } catch {
    return null;
  }
  return href;
}
var noopTest = { exec: () => null };
function splitCells(tableRow, count) {
  const row = tableRow.replace(/\|/g, (match, offset, str) => {
    let escaped = false;
    let curr = offset;
    while (--curr >= 0 && str[curr] === "\\")
      escaped = !escaped;
    if (escaped) {
      return "|";
    } else {
      return " |";
    }
  }), cells = row.split(/ \|/);
  let i = 0;
  if (!cells[0].trim()) {
    cells.shift();
  }
  if (cells.length > 0 && !cells[cells.length - 1].trim()) {
    cells.pop();
  }
  if (count) {
    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 rtrim(str, c, invert) {
  const l = str.length;
  if (l === 0) {
    return "";
  }
  let suffLen = 0;
  while (suffLen < l) {
    const currChar = str.charAt(l - suffLen - 1);
    if (currChar === c && !invert) {
      suffLen++;
    } else if (currChar !== c && invert) {
      suffLen++;
    } else {
      break;
    }
  }
  return str.slice(0, l - suffLen);
}
function findClosingBracket(str, b) {
  if (str.indexOf(b[1]) === -1) {
    return -1;
  }
  let level = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "\\") {
      i++;
    } else if (str[i] === b[0]) {
      level++;
    } else if (str[i] === b[1]) {
      level--;
      if (level < 0) {
        return i;
      }
    }
  }
  return -1;
}
function outputLink(cap, link2, raw, lexer2) {
  const href = link2.href;
  const title = link2.title ? escape$1(link2.title) : null;
  const text = cap[1].replace(/\\([\[\]])/g, "$1");
  if (cap[0].charAt(0) !== "!") {
    lexer2.state.inLink = true;
    const token = {
      type: "link",
      raw,
      href,
      title,
      text,
      tokens: lexer2.inlineTokens(text)
    };
    lexer2.state.inLink = false;
    return token;
  }
  return {
    type: "image",
    raw,
    href,
    title,
    text: escape$1(text)
  };
}
function indentCodeCompensation(raw, text) {
  const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
  if (matchIndentToCode === null) {
    return text;
  }
  const indentToCode = matchIndentToCode[1];
  return text.split("\n").map((node) => {
    const matchIndentInNode = node.match(/^\s+/);
    if (matchIndentInNode === null) {
      return node;
    }
    const [indentInNode] = matchIndentInNode;
    if (indentInNode.length >= indentToCode.length) {
      return node.slice(indentToCode.length);
    }
    return node;
  }).join("\n");
}
var _Tokenizer = class {
  options;
  rules;
  // set by the lexer
  lexer;
  // set by the lexer
  constructor(options2) {
    this.options = options2 || _defaults;
  }
  space(src) {
    const cap = this.rules.block.newline.exec(src);
    if (cap && cap[0].length > 0) {
      return {
        type: "space",
        raw: cap[0]
      };
    }
  }
  code(src) {
    const cap = this.rules.block.code.exec(src);
    if (cap) {
      const text = cap[0].replace(/^ {1,4}/gm, "");
      return {
        type: "code",
        raw: cap[0],
        codeBlockStyle: "indented",
        text: !this.options.pedantic ? rtrim(text, "\n") : text
      };
    }
  }
  fences(src) {
    const cap = this.rules.block.fences.exec(src);
    if (cap) {
      const raw = cap[0];
      const text = indentCodeCompensation(raw, cap[3] || "");
      return {
        type: "code",
        raw,
        lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2],
        text
      };
    }
  }
  heading(src) {
    const cap = this.rules.block.heading.exec(src);
    if (cap) {
      let text = cap[2].trim();
      if (/#$/.test(text)) {
        const trimmed = rtrim(text, "#");
        if (this.options.pedantic) {
          text = trimmed.trim();
        } else if (!trimmed || / $/.test(trimmed)) {
          text = trimmed.trim();
        }
      }
      return {
        type: "heading",
        raw: cap[0],
        depth: cap[1].length,
        text,
        tokens: this.lexer.inline(text)
      };
    }
  }
  hr(src) {
    const cap = this.rules.block.hr.exec(src);
    if (cap) {
      return {
        type: "hr",
        raw: rtrim(cap[0], "\n")
      };
    }
  }
  blockquote(src) {
    const cap = this.rules.block.blockquote.exec(src);
    if (cap) {
      let lines = rtrim(cap[0], "\n").split("\n");
      let raw = "";
      let text = "";
      const tokens = [];
      while (lines.length > 0) {
        let inBlockquote = false;
        const currentLines = [];
        let i;
        for (i = 0; i < lines.length; i++) {
          if (/^ {0,3}>/.test(lines[i])) {
            currentLines.push(lines[i]);
            inBlockquote = true;
          } else if (!inBlockquote) {
            currentLines.push(lines[i]);
          } else {
            break;
          }
        }
        lines = lines.slice(i);
        const currentRaw = currentLines.join("\n");
        const currentText = currentRaw.replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, "\n    $1").replace(/^ {0,3}>[ \t]?/gm, "");
        raw = raw ? `${raw}
${currentRaw}` : currentRaw;
        text = text ? `${text}
${currentText}` : currentText;
        const top = this.lexer.state.top;
        this.lexer.state.top = true;
        this.lexer.blockTokens(currentText, tokens, true);
        this.lexer.state.top = top;
        if (lines.length === 0) {
          break;
        }
        const lastToken = tokens[tokens.length - 1];
        if (lastToken?.type === "code") {
          break;
        } else if (lastToken?.type === "blockquote") {
          const oldToken = lastToken;
          const newText = oldToken.raw + "\n" + lines.join("\n");
          const newToken = this.blockquote(newText);
          tokens[tokens.length - 1] = newToken;
          raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
          text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
          break;
        } else if (lastToken?.type === "list") {
          const oldToken = lastToken;
          const newText = oldToken.raw + "\n" + lines.join("\n");
          const newToken = this.list(newText);
          tokens[tokens.length - 1] = newToken;
          raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
          text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
          lines = newText.substring(tokens[tokens.length - 1].raw.length).split("\n");
          continue;
        }
      }
      return {
        type: "blockquote",
        raw,
        tokens,
        text
      };
    }
  }
  list(src) {
    let cap = this.rules.block.list.exec(src);
    if (cap) {
      let bull = cap[1].trim();
      const isordered = bull.length > 1;
      const list2 = {
        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 : "[*+-]";
      }
      const itemRegex = new RegExp(`^( {0,3}${bull})((?:[	 ][^\\n]*)?(?:\\n|$))`);
      let endsWithBlankLine = false;
      while (src) {
        let endEarly = false;
        let raw = "";
        let itemContents = "";
        if (!(cap = itemRegex.exec(src))) {
          break;
        }
        if (this.rules.block.hr.test(src)) {
          break;
        }
        raw = cap[0];
        src = src.substring(raw.length);
        let line = cap[2].split("\n", 1)[0].replace(/^\t+/, (t) => " ".repeat(3 * t.length));
        let nextLine = src.split("\n", 1)[0];
        let blankLine = !line.trim();
        let indent = 0;
        if (this.options.pedantic) {
          indent = 2;
          itemContents = line.trimStart();
        } else if (blankLine) {
          indent = cap[1].length + 1;
        } else {
          indent = cap[2].search(/[^ ]/);
          indent = indent > 4 ? 1 : indent;
          itemContents = line.slice(indent);
          indent += cap[1].length;
        }
        if (blankLine && /^ *$/.test(nextLine)) {
          raw += nextLine + "\n";
          src = src.substring(nextLine.length + 1);
          endEarly = true;
        }
        if (!endEarly) {
          const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`);
          const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
          const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
          const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
          while (src) {
            const rawLine = src.split("\n", 1)[0];
            nextLine = rawLine;
            if (this.options.pedantic) {
              nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, "  ");
            }
            if (fencesBeginRegex.test(nextLine)) {
              break;
            }
            if (headingBeginRegex.test(nextLine)) {
              break;
            }
            if (nextBulletRegex.test(nextLine)) {
              break;
            }
            if (hrRegex.test(src)) {
              break;
            }
            if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) {
              itemContents += "\n" + nextLine.slice(indent);
            } else {
              if (blankLine) {
                break;
              }
              if (line.search(/[^ ]/) >= 4) {
                break;
              }
              if (fencesBeginRegex.test(line)) {
                break;
              }
              if (headingBeginRegex.test(line)) {
                break;
              }
              if (hrRegex.test(line)) {
                break;
              }
              itemContents += "\n" + nextLine;
            }
            if (!blankLine && !nextLine.trim()) {
              blankLine = true;
            }
            raw += rawLine + "\n";
            src = src.substring(rawLine.length + 1);
            line = nextLine.slice(indent);
          }
        }
        if (!list2.loose) {
          if (endsWithBlankLine) {
            list2.loose = true;
          } else if (/\n *\n *$/.test(raw)) {
            endsWithBlankLine = true;
          }
        }
        let istask = null;
        let ischecked;
        if (this.options.gfm) {
          istask = /^\[[ xX]\] /.exec(itemContents);
          if (istask) {
            ischecked = istask[0] !== "[ ] ";
            itemContents = itemContents.replace(/^\[[ xX]\] +/, "");
          }
        }
        list2.items.push({
          type: "list_item",
          raw,
          task: !!istask,
          checked: ischecked,
          loose: false,
          text: itemContents,
          tokens: []
        });
        list2.raw += raw;
      }
      list2.items[list2.items.length - 1].raw = list2.items[list2.items.length - 1].raw.trimEnd();
      list2.items[list2.items.length - 1].text = list2.items[list2.items.length - 1].text.trimEnd();
      list2.raw = list2.raw.trimEnd();
      for (let i = 0; i < list2.items.length; i++) {
        this.lexer.state.top = false;
        list2.items[i].tokens = this.lexer.blockTokens(list2.items[i].text, []);
        if (!list2.loose) {
          const spacers = list2.items[i].tokens.filter((t) => t.type === "space");
          const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t) => /\n.*\n/.test(t.raw));
          list2.loose = hasMultipleLineBreaks;
        }
      }
      if (list2.loose) {
        for (let i = 0; i < list2.items.length; i++) {
          list2.items[i].loose = true;
        }
      }
      return list2;
    }
  }
  html(src) {
    const cap = this.rules.block.html.exec(src);
    if (cap) {
      const token = {
        type: "html",
        block: true,
        raw: cap[0],
        pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
        text: cap[0]
      };
      return token;
    }
  }
  def(src) {
    const cap = this.rules.block.def.exec(src);
    if (cap) {
      const tag2 = cap[1].toLowerCase().replace(/\s+/g, " ");
      const href = cap[2] ? cap[2].replace(/^<(.*)>$/, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "";
      const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3];
      return {
        type: "def",
        tag: tag2,
        raw: cap[0],
        href,
        title
      };
    }
  }
  table(src) {
    const cap = this.rules.block.table.exec(src);
    if (!cap) {
      return;
    }
    if (!/[:|]/.test(cap[2])) {
      return;
    }
    const headers = splitCells(cap[1]);
    const aligns = cap[2].replace(/^\||\| *$/g, "").split("|");
    const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, "").split("\n") : [];
    const item = {
      type: "table",
      raw: cap[0],
      header: [],
      align: [],
      rows: []
    };
    if (headers.length !== aligns.length) {
      return;
    }
    for (const align of aligns) {
      if (/^ *-+: *$/.test(align)) {
        item.align.push("right");
      } else if (/^ *:-+: *$/.test(align)) {
        item.align.push("center");
      } else if (/^ *:-+ *$/.test(align)) {
        item.align.push("left");
      } else {
        item.align.push(null);
      }
    }
    for (let i = 0; i < headers.length; i++) {
      item.header.push({
        text: headers[i],
        tokens: this.lexer.inline(headers[i]),
        header: true,
        align: item.align[i]
      });
    }
    for (const row of rows) {
      item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
        return {
          text: cell,
          tokens: this.lexer.inline(cell),
          header: false,
          align: item.align[i]
        };
      }));
    }
    return item;
  }
  lheading(src) {
    const 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])
      };
    }
  }
  paragraph(src) {
    const cap = this.rules.block.paragraph.exec(src);
    if (cap) {
      const text = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1];
      return {
        type: "paragraph",
        raw: cap[0],
        text,
        tokens: this.lexer.inline(text)
      };
    }
  }
  text(src) {
    const cap = this.rules.block.text.exec(src);
    if (cap) {
      return {
        type: "text",
        raw: cap[0],
        text: cap[0],
        tokens: this.lexer.inline(cap[0])
      };
    }
  }
  escape(src) {
    const cap = this.rules.inline.escape.exec(src);
    if (cap) {
      return {
        type: "escape",
        raw: cap[0],
        text: escape$1(cap[1])
      };
    }
  }
  tag(src) {
    const 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: "html",
        raw: cap[0],
        inLink: this.lexer.state.inLink,
        inRawBlock: this.lexer.state.inRawBlock,
        block: false,
        text: cap[0]
      };
    }
  }
  link(src) {
    const cap = this.rules.inline.link.exec(src);
    if (cap) {
      const trimmedUrl = cap[2].trim();
      if (!this.options.pedantic && /^</.test(trimmedUrl)) {
        if (!/>$/.test(trimmedUrl)) {
          return;
        }
        const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
        if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
          return;
        }
      } else {
        const lastParenIndex = findClosingBracket(cap[2], "()");
        if (lastParenIndex > -1) {
          const start = cap[0].indexOf("!") === 0 ? 5 : 4;
          const linkLen = start + cap[1].length + lastParenIndex;
          cap[2] = cap[2].substring(0, lastParenIndex);
          cap[0] = cap[0].substring(0, linkLen).trim();
          cap[3] = "";
        }
      }
      let href = cap[2];
      let title = "";
      if (this.options.pedantic) {
        const link2 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
        if (link2) {
          href = link2[1];
          title = link2[3];
        }
      } else {
        title = 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.anyPunctuation, "$1") : href,
        title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title
      }, cap[0], this.lexer);
    }
  }
  reflink(src, links) {
    let cap;
    if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
      const linkString = (cap[2] || cap[1]).replace(/\s+/g, " ");
      const link2 = links[linkString.toLowerCase()];
      if (!link2) {
        const text = cap[0].charAt(0);
        return {
          type: "text",
          raw: text,
          text
        };
      }
      return outputLink(cap, link2, cap[0], this.lexer);
    }
  }
  emStrong(src, maskedSrc, prevChar = "") {
    let match = this.rules.inline.emStrongLDelim.exec(src);
    if (!match)
      return;
    if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
      return;
    const nextChar = match[1] || match[2] || "";
    if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
      const lLength = [...match[0]].length - 1;
      let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
      const endReg = match[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      endReg.lastIndex = 0;
      maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
      while ((match = endReg.exec(maskedSrc)) != null) {
        rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
        if (!rDelim)
          continue;
        rLength = [...rDelim].length;
        if (match[3] || match[4]) {
          delimTotal += rLength;
          continue;
        } else if (match[5] || match[6]) {
          if (lLength % 3 && !((lLength + rLength) % 3)) {
            midDelimTotal += rLength;
            continue;
          }
        }
        delimTotal -= rLength;
        if (delimTotal > 0)
          continue;
        rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
        const lastCharLength = [...match[0]][0].length;
        const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
        if (Math.min(lLength, rLength) % 2) {
          const text2 = raw.slice(1, -1);
          return {
            type: "em",
            raw,
            text: text2,
            tokens: this.lexer.inlineTokens(text2)
          };
        }
        const text = raw.slice(2, -2);
        return {
          type: "strong",
          raw,
          text,
          tokens: this.lexer.inlineTokens(text)
        };
      }
    }
  }
  codespan(src) {
    const cap = this.rules.inline.code.exec(src);
    if (cap) {
      let text = cap[2].replace(/\n/g, " ");
      const hasNonSpaceChars = /[^ ]/.test(text);
      const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
      if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
        text = text.substring(1, text.length - 1);
      }
      text = escape$1(text, true);
      return {
        type: "codespan",
        raw: cap[0],
        text
      };
    }
  }
  br(src) {
    const cap = this.rules.inline.br.exec(src);
    if (cap) {
      return {
        type: "br",
        raw: cap[0]
      };
    }
  }
  del(src) {
    const cap = this.rules.inline.del.exec(src);
    if (cap) {
      return {
        type: "del",
        raw: cap[0],
        text: cap[2],
        tokens: this.lexer.inlineTokens(cap[2])
      };
    }
  }
  autolink(src) {
    const cap = this.rules.inline.autolink.exec(src);
    if (cap) {
      let text, href;
      if (cap[2] === "@") {
        text = escape$1(cap[1]);
        href = "mailto:" + text;
      } else {
        text = escape$1(cap[1]);
        href = text;
      }
      return {
        type: "link",
        raw: cap[0],
        text,
        href,
        tokens: [
          {
            type: "text",
            raw: text,
            text
          }
        ]
      };
    }
  }
  url(src) {
    let cap;
    if (cap = this.rules.inline.url.exec(src)) {
      let text, href;
      if (cap[2] === "@") {
        text = escape$1(cap[0]);
        href = "mailto:" + text;
      } else {
        let prevCapZero;
        do {
          prevCapZero = cap[0];
          cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
        } while (prevCapZero !== cap[0]);
        text = escape$1(cap[0]);
        if (cap[1] === "www.") {
          href = "http://" + cap[0];
        } else {
          href = cap[0];
        }
      }
      return {
        type: "link",
        raw: cap[0],
        text,
        href,
        tokens: [
          {
            type: "text",
            raw: text,
            text
          }
        ]
      };
    }
  }
  inlineText(src) {
    const cap = this.rules.inline.text.exec(src);
    if (cap) {
      let text;
      if (this.lexer.state.inRawBlock) {
        text = cap[0];
      } else {
        text = escape$1(cap[0]);
      }
      return {
        type: "text",
        raw: cap[0],
        text
      };
    }
  }
};
var newline = /^(?: *(?:\n|$))+/;
var blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/;
var fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
var hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
var heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
var bullet = /(?:[*+-]|\d{1,9}[.)])/;
var lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g, bullet).replace(/blockCode/g, / {4}/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).getRegex();
var _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
var blockText = /^[^\n]+/;
var _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
var def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
var list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
var _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|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
var _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
var html = edit("^ {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|$))", "i").replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
var paragraph = edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").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", _tag).getRegex();
var blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex();
var blockNormal = {
  blockquote,
  code: blockCode,
  def,
  fences,
  heading,
  hr,
  html,
  lheading,
  list,
  newline,
  paragraph,
  table: noopTest,
  text: blockText
};
var gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").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", _tag).getRegex();
var blockGfm = {
  ...blockNormal,
  table: gfmTable,
  paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).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", _tag).getRegex()
};
var blockPedantic = {
  ...blockNormal,
  html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", _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
  lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
};
var escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
var inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
var br = /^( {2,}|\\)\n(?!\s*$)/;
var inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
var _punctuation = "\\p{P}\\p{S}";
var punctuation = edit(/^((?![*_])[\spunctuation])/, "u").replace(/punctuation/g, _punctuation).getRegex();
var blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
var emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, "u").replace(/punct/g, _punctuation).getRegex();
var emStrongRDelimAst = edit("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])", "gu").replace(/punct/g, _punctuation).getRegex();
var emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])", "gu").replace(/punct/g, _punctuation).getRegex();
var anyPunctuation = edit(/\\([punct])/, "gu").replace(/punct/g, _punctuation).getRegex();
var autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("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])?)+(?![-_])/).getRegex();
var _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex();
var tag = edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
var _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
var link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
var reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex();
var nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex();
var reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex();
var inlineNormal = {
  _backpedal: noopTest,
  // only used for GFM url
  anyPunctuation,
  autolink,
  blockSkip,
  br,
  code: inlineCode,
  del: noopTest,
  emStrongLDelim,
  emStrongRDelimAst,
  emStrongRDelimUnd,
  escape,
  link,
  nolink,
  punctuation,
  reflink,
  reflinkSearch,
  tag,
  text: inlineText,
  url: noopTest
};
var inlinePedantic = {
  ...inlineNormal,
  link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(),
  reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex()
};
var inlineGfm = {
  ...inlineNormal,
  escape: edit(escape).replace("])", "~|])").getRegex(),
  url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
  _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.!#$%&'*+\/=?_`{\|}~-]+@)))/
};
var inlineBreaks = {
  ...inlineGfm,
  br: edit(br).replace("{2,}", "*").getRegex(),
  text: edit(inlineGfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
};
var block = {
  normal: blockNormal,
  gfm: blockGfm,
  pedantic: blockPedantic
};
var inline = {
  normal: inlineNormal,
  gfm: inlineGfm,
  breaks: inlineBreaks,
  pedantic: inlinePedantic
};
var _Lexer = class __Lexer {
  tokens;
  options;
  state;
  tokenizer;
  inlineQueue;
  constructor(options2) {
    this.tokens = [];
    this.tokens.links = /* @__PURE__ */ Object.create(null);
    this.options = options2 || _defaults;
    this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
    this.tokenizer = this.options.tokenizer;
    this.tokenizer.options = this.options;
    this.tokenizer.lexer = this;
    this.inlineQueue = [];
    this.state = {
      inLink: false,
      inRawBlock: false,
      top: true
    };
    const 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;
  }
  /**
   * Expose Rules
   */
  static get rules() {
    return {
      block,
      inline
    };
  }
  /**
   * Static Lex Method
   */
  static lex(src, options2) {
    const lexer2 = new __Lexer(options2);
    return lexer2.lex(src);
  }
  /**
   * Static Lex Inline Method
   */
  static lexInline(src, options2) {
    const lexer2 = new __Lexer(options2);
    return lexer2.inlineTokens(src);
  }
  /**
   * Preprocessing
   */
  lex(src) {
    src = src.replace(/\r\n|\r/g, "\n");
    this.blockTokens(src, this.tokens);
    for (let i = 0; i < this.inlineQueue.length; i++) {
      const next = this.inlineQueue[i];
      this.inlineTokens(next.src, next.tokens);
    }
    this.inlineQueue = [];
    return this.tokens;
  }
  blockTokens(src, tokens = [], lastParagraphClipped = false) {
    if (this.options.pedantic) {
      src = src.replace(/\t/g, "    ").replace(/^ +$/gm, "");
    } else {
      src = src.replace(/^( *)(\t+)/gm, (_, leading, tabs) => {
        return leading + "    ".repeat(tabs.length);
      });
    }
    let token;
    let lastToken;
    let cutSrc;
    while (src) {
      if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some((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) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startBlock.forEach((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) {
        const 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;
  }
  inline(src, tokens = []) {
    this.inlineQueue.push({ src, tokens });
    return tokens;
  }
  /**
   * Lexing/Compiling
   */
  inlineTokens(src, tokens = []) {
    let token, lastToken, cutSrc;
    let maskedSrc = src;
    let match;
    let keepPrevChar, prevChar;
    if (this.tokens.links) {
      const links = Object.keys(this.tokens.links);
      if (links.length > 0) {
        while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
          if (links.includes(match[0].slice(match[0].lastIndexOf("[") + 1, -1))) {
            maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
          }
        }
      }
    }
    while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    }
    while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    }
    while (src) {
      if (!keepPrevChar) {
        prevChar = "";
      }
      keepPrevChar = false;
      if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some((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.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)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (!this.state.inLink && (token = this.tokenizer.url(src))) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startInline) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startInline.forEach((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)) {
        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) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    return tokens;
  }
};
var _Renderer = class {
  options;
  parser;
  // set by the parser
  constructor(options2) {
    this.options = options2 || _defaults;
  }
  space(token) {
    return "";
  }
  code({ text, lang, escaped }) {
    const langString = (lang || "").match(/^\S*/)?.[0];
    const code = text.replace(/\n$/, "") + "\n";
    if (!langString) {
      return "<pre><code>" + (escaped ? code : escape$1(code, true)) + "</code></pre>\n";
    }
    return '<pre><code class="language-' + escape$1(langString) + '">' + (escaped ? code : escape$1(code, true)) + "</code></pre>\n";
  }
  blockquote({ tokens }) {
    const body = this.parser.parse(tokens);
    return `<blockquote>
${body}</blockquote>
`;
  }
  html({ text }) {
    return text;
  }
  heading({ tokens, depth }) {
    return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>
`;
  }
  hr(token) {
    return "<hr>\n";
  }
  list(token) {
    const ordered = token.ordered;
    const start = token.start;
    let body = "";
    for (let j = 0; j < token.items.length; j++) {
      const item = token.items[j];
      body += this.listitem(item);
    }
    const type = ordered ? "ol" : "ul";
    const startAttr = ordered && start !== 1 ? ' start="' + start + '"' : "";
    return "<" + type + startAttr + ">\n" + body + "</" + type + ">\n";
  }
  listitem(item) {
    let itemBody = "";
    if (item.task) {
      const checkbox = this.checkbox({ checked: !!item.checked });
      if (item.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",
            raw: checkbox + " ",
            text: checkbox + " "
          });
        }
      } else {
        itemBody += checkbox + " ";
      }
    }
    itemBody += this.parser.parse(item.tokens, !!item.loose);
    return `<li>${itemBody}</li>
`;
  }
  checkbox({ checked }) {
    return "<input " + (checked ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
  }
  paragraph({ tokens }) {
    return `<p>${this.parser.parseInline(tokens)}</p>
`;
  }
  table(token) {
    let header = "";
    let cell = "";
    for (let j = 0; j < token.header.length; j++) {
      cell += this.tablecell(token.header[j]);
    }
    header += this.tablerow({ text: cell });
    let body = "";
    for (let j = 0; j < token.rows.length; j++) {
      const row = token.rows[j];
      cell = "";
      for (let k = 0; k < row.length; k++) {
        cell += this.tablecell(row[k]);
      }
      body += this.tablerow({ text: cell });
    }
    if (body)
      body = `<tbody>${body}</tbody>`;
    return "<table>\n<thead>\n" + header + "</thead>\n" + body + "</table>\n";
  }
  tablerow({ text }) {
    return `<tr>
${text}</tr>
`;
  }
  tablecell(token) {
    const content = this.parser.parseInline(token.tokens);
    const type = token.header ? "th" : "td";
    const tag2 = token.align ? `<${type} align="${token.align}">` : `<${type}>`;
    return tag2 + content + `</${type}>
`;
  }
  /**
   * span level renderer
   */
  strong({ tokens }) {
    return `<strong>${this.parser.parseInline(tokens)}</strong>`;
  }
  em({ tokens }) {
    return `<em>${this.parser.parseInline(tokens)}</em>`;
  }
  codespan({ text }) {
    return `<code>${text}</code>`;
  }
  br(token) {
    return "<br>";
  }
  del({ tokens }) {
    return `<del>${this.parser.parseInline(tokens)}</del>`;
  }
  link({ href, title, tokens }) {
    const text = this.parser.parseInline(tokens);
    const cleanHref = cleanUrl(href);
    if (cleanHref === null) {
      return text;
    }
    href = cleanHref;
    let out = '<a href="' + href + '"';
    if (title) {
      out += ' title="' + title + '"';
    }
    out += ">" + text + "</a>";
    return out;
  }
  image({ href, title, text }) {
    const cleanHref = cleanUrl(href);
    if (cleanHref === null) {
      return text;
    }
    href = cleanHref;
    let out = `<img src="${href}" alt="${text}"`;
    if (title) {
      out += ` title="${title}"`;
    }
    out += ">";
    return out;
  }
  text(token) {
    return "tokens" in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;
  }
};
var _TextRenderer = class {
  // no need for block level renderers
  strong({ text }) {
    return text;
  }
  em({ text }) {
    return text;
  }
  codespan({ text }) {
    return text;
  }
  del({ text }) {
    return text;
  }
  html({ text }) {
    return text;
  }
  text({ text }) {
    return text;
  }
  link({ text }) {
    return "" + text;
  }
  image({ text }) {
    return "" + text;
  }
  br() {
    return "";
  }
};
var _Parser = class __Parser {
  options;
  renderer;
  textRenderer;
  constructor(options2) {
    this.options = options2 || _defaults;
    this.options.renderer = this.options.renderer || new _Renderer();
    this.renderer = this.options.renderer;
    this.renderer.options = this.options;
    this.renderer.parser = this;
    this.textRenderer = new _TextRenderer();
  }
  /**
   * Static Parse Method
   */
  static parse(tokens, options2) {
    const parser2 = new __Parser(options2);
    return parser2.parse(tokens);
  }
  /**
   * Static Parse Inline Method
   */
  static parseInline(tokens, options2) {
    const parser2 = new __Parser(options2);
    return parser2.parseInline(tokens);
  }
  /**
   * Parse Loop
   */
  parse(tokens, top = true) {
    let out = "";
    for (let i = 0; i < tokens.length; i++) {
      const anyToken = tokens[i];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
        const genericToken = anyToken;
        const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
        if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) {
          out += ret || "";
          continue;
        }
      }
      const token = anyToken;
      switch (token.type) {
        case "space": {
          out += this.renderer.space(token);
          continue;
        }
        case "hr": {
          out += this.renderer.hr(token);
          continue;
        }
        case "heading": {
          out += this.renderer.heading(token);
          continue;
        }
        case "code": {
          out += this.renderer.code(token);
          continue;
        }
        case "table": {
          out += this.renderer.table(token);
          continue;
        }
        case "blockquote": {
          out += this.renderer.blockquote(token);
          continue;
        }
        case "list": {
          out += this.renderer.list(token);
          continue;
        }
        case "html": {
          out += this.renderer.html(token);
          continue;
        }
        case "paragraph": {
          out += this.renderer.paragraph(token);
          continue;
        }
        case "text": {
          let textToken = token;
          let body = this.renderer.text(textToken);
          while (i + 1 < tokens.length && tokens[i + 1].type === "text") {
            textToken = tokens[++i];
            body += "\n" + this.renderer.text(textToken);
          }
          if (top) {
            out += this.renderer.paragraph({
              type: "paragraph",
              raw: body,
              text: body,
              tokens: [{ type: "text", raw: body, text: body }]
            });
          } else {
            out += body;
          }
          continue;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return "";
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
  /**
   * Parse Inline Tokens
   */
  parseInline(tokens, renderer) {
    renderer = renderer || this.renderer;
    let out = "";
    for (let i = 0; i < tokens.length; i++) {
      const anyToken = tokens[i];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
        const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
        if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(anyToken.type)) {
          out += ret || "";
          continue;
        }
      }
      const token = anyToken;
      switch (token.type) {
        case "escape": {
          out += renderer.text(token);
          break;
        }
        case "html": {
          out += renderer.html(token);
          break;
        }
        case "link": {
          out += renderer.link(token);
          break;
        }
        case "image": {
          out += renderer.image(token);
          break;
        }
        case "strong": {
          out += renderer.strong(token);
          break;
        }
        case "em": {
          out += renderer.em(token);
          break;
        }
        case "codespan": {
          out += renderer.codespan(token);
          break;
        }
        case "br": {
          out += renderer.br(token);
          break;
        }
        case "del": {
          out += renderer.del(token);
          break;
        }
        case "text": {
          out += renderer.text(token);
          break;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return "";
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
};
var _Hooks = class {
  options;
  constructor(options2) {
    this.options = options2 || _defaults;
  }
  static passThroughHooks = /* @__PURE__ */ new Set([
    "preprocess",
    "postprocess",
    "processAllTokens"
  ]);
  /**
   * Process markdown before marked
   */
  preprocess(markdown) {
    return markdown;
  }
  /**
   * Process HTML after marked is finished
   */
  postprocess(html2) {
    return html2;
  }
  /**
   * Process all tokens before walk tokens
   */
  processAllTokens(tokens) {
    return tokens;
  }
};
var Marked = class {
  defaults = _getDefaults();
  options = this.setOptions;
  parse = this.parseMarkdown(_Lexer.lex, _Parser.parse);
  parseInline = this.parseMarkdown(_Lexer.lexInline, _Parser.parseInline);
  Parser = _Parser;
  Renderer = _Renderer;
  TextRenderer = _TextRenderer;
  Lexer = _Lexer;
  Tokenizer = _Tokenizer;
  Hooks = _Hooks;
  constructor(...args2) {
    this.use(...args2);
  }
  /**
   * Run callback for every token
   */
  walkTokens(tokens, callback) {
    let values = [];
    for (const token of tokens) {
      values = values.concat(callback.call(this, token));
      switch (token.type) {
        case "table": {
          const tableToken = token;
          for (const cell of tableToken.header) {
            values = values.concat(this.walkTokens(cell.tokens, callback));
          }
          for (const row of tableToken.rows) {
            for (const cell of row) {
              values = values.concat(this.walkTokens(cell.tokens, callback));
            }
          }
          break;
        }
        case "list": {
          const listToken = token;
          values = values.concat(this.walkTokens(listToken.items, callback));
          break;
        }
        default: {
          const genericToken = token;
          if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
            this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
              const tokens2 = genericToken[childTokens].flat(Infinity);
              values = values.concat(this.walkTokens(tokens2, callback));
            });
          } else if (genericToken.tokens) {
            values = values.concat(this.walkTokens(genericToken.tokens, callback));
          }
        }
      }
    }
    return values;
  }
  use(...args2) {
    const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
    args2.forEach((pack) => {
      const opts = { ...pack };
      opts.async = this.defaults.async || opts.async || false;
      if (pack.extensions) {
        pack.extensions.forEach((ext) => {
          if (!ext.name) {
            throw new Error("extension name required");
          }
          if ("renderer" in ext) {
            const prevRenderer = extensions.renderers[ext.name];
            if (prevRenderer) {
              extensions.renderers[ext.name] = function(...args3) {
                let ret = ext.renderer.apply(this, args3);
                if (ret === false) {
                  ret = prevRenderer.apply(this, args3);
                }
                return ret;
              };
            } else {
              extensions.renderers[ext.name] = ext.renderer;
            }
          }
          if ("tokenizer" in ext) {
            if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
              throw new Error("extension level must be 'block' or 'inline'");
            }
            const extLevel = extensions[ext.level];
            if (extLevel) {
              extLevel.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 ("childTokens" in ext && ext.childTokens) {
            extensions.childTokens[ext.name] = ext.childTokens;
          }
        });
        opts.extensions = extensions;
      }
      if (pack.renderer) {
        const renderer = this.defaults.renderer || new _Renderer(this.defaults);
        for (const prop in pack.renderer) {
          if (!(prop in renderer)) {
            throw new Error(`renderer '${prop}' does not exist`);
          }
          if (["options", "parser"].includes(prop)) {
            continue;
          }
          const rendererProp = prop;
          const rendererFunc = pack.renderer[rendererProp];
          const prevRenderer = renderer[rendererProp];
          renderer[rendererProp] = (...args3) => {
            let ret = rendererFunc.apply(renderer, args3);
            if (ret === false) {
              ret = prevRenderer.apply(renderer, args3);
            }
            return ret || "";
          };
        }
        opts.renderer = renderer;
      }
      if (pack.tokenizer) {
        const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
        for (const prop in pack.tokenizer) {
          if (!(prop in tokenizer)) {
            throw new Error(`tokenizer '${prop}' does not exist`);
          }
          if (["options", "rules", "lexer"].includes(prop)) {
            continue;
          }
          const tokenizerProp = prop;
          const tokenizerFunc = pack.tokenizer[tokenizerProp];
          const prevTokenizer = tokenizer[tokenizerProp];
          tokenizer[tokenizerProp] = (...args3) => {
            let ret = tokenizerFunc.apply(tokenizer, args3);
            if (ret === false) {
              ret = prevTokenizer.apply(tokenizer, args3);
            }
            return ret;
          };
        }
        opts.tokenizer = tokenizer;
      }
      if (pack.hooks) {
        const hooks = this.defaults.hooks || new _Hooks();
        for (const prop in pack.hooks) {
          if (!(prop in hooks)) {
            throw new Error(`hook '${prop}' does not exist`);
          }
          if (prop === "options") {
            continue;
          }
          const hooksProp = prop;
          const hooksFunc = pack.hooks[hooksProp];
          const prevHook = hooks[hooksProp];
          if (_Hooks.passThroughHooks.has(prop)) {
            hooks[hooksProp] = (arg) => {
              if (this.defaults.async) {
                return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {
                  return prevHook.call(hooks, ret2);
                });
              }
              const ret = hooksFunc.call(hooks, arg);
              return prevHook.call(hooks, ret);
            };
          } else {
            hooks[hooksProp] = (...args3) => {
              let ret = hooksFunc.apply(hooks, args3);
              if (ret === false) {
                ret = prevHook.apply(hooks, args3);
              }
              return ret;
            };
          }
        }
        opts.hooks = hooks;
      }
      if (pack.walkTokens) {
        const walkTokens2 = this.defaults.walkTokens;
        const packWalktokens = pack.walkTokens;
        opts.walkTokens = function(token) {
          let values = [];
          values.push(packWalktokens.call(this, token));
          if (walkTokens2) {
            values = values.concat(walkTokens2.call(this, token));
          }
          return values;
        };
      }
      this.defaults = { ...this.defaults, ...opts };
    });
    return this;
  }
  setOptions(opt) {
    this.defaults = { ...this.defaults, ...opt };
    return this;
  }
  lexer(src, options2) {
    return _Lexer.lex(src, options2 ?? this.defaults);
  }
  parser(tokens, options2) {
    return _Parser.parse(tokens, options2 ?? this.defaults);
  }
  parseMarkdown(lexer2, parser2) {
    const parse2 = (src, options2) => {
      const origOpt = { ...options2 };
      const opt = { ...this.defaults, ...origOpt };
      const throwError = this.onError(!!opt.silent, !!opt.async);
      if (this.defaults.async === true && origOpt.async === false) {
        return throwError(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
      }
      if (typeof src === "undefined" || src === null) {
        return throwError(new Error("marked(): input parameter is undefined or null"));
      }
      if (typeof src !== "string") {
        return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"));
      }
      if (opt.hooks) {
        opt.hooks.options = opt;
      }
      if (opt.async) {
        return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser2(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);
      }
      try {
        if (opt.hooks) {
          src = opt.hooks.preprocess(src);
        }
        let tokens = lexer2(src, opt);
        if (opt.hooks) {
          tokens = opt.hooks.processAllTokens(tokens);
        }
        if (opt.walkTokens) {
          this.walkTokens(tokens, opt.walkTokens);
        }
        let html2 = parser2(tokens, opt);
        if (opt.hooks) {
          html2 = opt.hooks.postprocess(html2);
        }
        return html2;
      } catch (e) {
        return throwError(e);
      }
    };
    return parse2;
  }
  onError(silent, async) {
    return (e) => {
      e.message += "\nPlease report this to https://github.com/markedjs/marked.";
      if (silent) {
        const msg = "<p>An error occurred:</p><pre>" + escape$1(e.message + "", true) + "</pre>";
        if (async) {
          return Promise.resolve(msg);
        }
        return msg;
      }
      if (async) {
        return Promise.reject(e);
      }
      throw e;
    };
  }
};
var markedInstance = new Marked();
function marked(src, opt) {
  return markedInstance.parse(src, opt);
}
marked.options = marked.setOptions = function(options2) {
  markedInstance.setOptions(options2);
  marked.defaults = markedInstance.defaults;
  changeDefaults(marked.defaults);
  return marked;
};
marked.getDefaults = _getDefaults;
marked.defaults = _defaults;
marked.use = function(...args2) {
  markedInstance.use(...args2);
  marked.defaults = markedInstance.defaults;
  changeDefaults(marked.defaults);
  return marked;
};
marked.walkTokens = function(tokens, callback) {
  return markedInstance.walkTokens(tokens, callback);
};
marked.parseInline = markedInstance.parseInline;
marked.Parser = _Parser;
marked.parser = _Parser.parse;
marked.Renderer = _Renderer;
marked.TextRenderer = _TextRenderer;
marked.Lexer = _Lexer;
marked.lexer = _Lexer.lex;
marked.Tokenizer = _Tokenizer;
marked.Hooks = _Hooks;
marked.parse = marked;
var options = marked.options;
var setOptions = marked.setOptions;
var use = marked.use;
var walkTokens = marked.walkTokens;
var parseInline = marked.parseInline;
var parser = _Parser.parse;
var lexer = _Lexer.lex;

// out-build/vs/base/common/mime.js
var $YC = Object.freeze({
  text: "text/plain",
  binary: "application/octet-stream",
  unknown: "application/unknown",
  markdown: "text/markdown",
  latex: "text/latex",
  uriList: "text/uri-list"
});
var _simplePattern = /^(.+)\/(.+?)(;.+)?$/;
function $3C(mimeType, strict) {
  const match = _simplePattern.exec(mimeType);
  if (!match) {
    return strict ? void 0 : mimeType;
  }
  return `${match[1].toLowerCase()}/${match[2].toLowerCase()}${match[3] ?? ""}`;
}

// out-build/vs/base/common/prefixTree.js
var unset = Symbol("unset");
var $lQ = class {
  constructor() {
    this.root = new Node2();
    this.a = 0;
  }
  /** Tree size, not including the root. */
  get size() {
    return this.a;
  }
  /** Gets the top-level nodes of the tree */
  get nodes() {
    return this.root.children?.values() || Iterable.empty();
  }
  /** Gets the top-level nodes of the tree */
  get entries() {
    return this.root.children?.entries() || Iterable.empty();
  }
  /**
   * Inserts a new value in the prefix tree.
   * @param onNode - called for each node as we descend to the insertion point,
   * including the insertion point itself.
   */
  insert(key, value, onNode) {
    this.c(key, (n) => n._value = value, onNode);
  }
  /** Mutates a value in the prefix tree. */
  mutate(key, mutate) {
    this.c(key, (n) => n._value = mutate(n._value === unset ? void 0 : n._value));
  }
  /** Mutates nodes along the path in the prefix tree. */
  mutatePath(key, mutate) {
    this.c(key, () => {
    }, (n) => mutate(n));
  }
  /** Deletes a node from the prefix tree, returning the value it contained. */
  delete(key) {
    const path = this.b(key);
    if (!path) {
      return;
    }
    let i = path.length - 1;
    const value = path[i].node._value;
    if (value === unset) {
      return;
    }
    this.a--;
    path[i].node._value = unset;
    for (; i > 0; i--) {
      const { node, part } = path[i];
      if (node.children?.size || node._value !== unset) {
        break;
      }
      path[i - 1].node.children.delete(part);
    }
    return value;
  }
  /** Deletes a subtree from the prefix tree, returning the values they contained. */
  *deleteRecursive(key) {
    const path = this.b(key);
    if (!path) {
      return;
    }
    const subtree = path[path.length - 1].node;
    for (let i = path.length - 1; i > 0; i--) {
      const parent = path[i - 1];
      parent.node.children.delete(path[i].part);
      if (parent.node.children.size > 0 || parent.node._value !== unset) {
        break;
      }
    }
    for (const node of bfsIterate(subtree)) {
      if (node._value !== unset) {
        this.a--;
        yield node._value;
      }
    }
    if (subtree === this.root) {
      this.root._value = unset;
      this.root.children = void 0;
    }
  }
  /** Gets a value from the tree. */
  find(key) {
    let node = this.root;
    for (const segment of key) {
      const next = node.children?.get(segment);
      if (!next) {
        return void 0;
      }
      node = next;
    }
    return node._value === unset ? void 0 : node._value;
  }
  /** Gets whether the tree has the key, or a parent of the key, already inserted. */
  hasKeyOrParent(key) {
    let node = this.root;
    for (const segment of key) {
      const next = node.children?.get(segment);
      if (!next) {
        return false;
      }
      if (next._value !== unset) {
        return true;
      }
      node = next;
    }
    return false;
  }
  /** Gets whether the tree has the given key or any children. */
  hasKeyOrChildren(key) {
    let node = this.root;
    for (const segment of key) {
      const next = node.children?.get(segment);
      if (!next) {
        return false;
      }
      node = next;
    }
    return true;
  }
  /** Gets whether the tree has the given key. */
  hasKey(key) {
    let node = this.root;
    for (const segment of key) {
      const next = node.children?.get(segment);
      if (!next) {
        return false;
      }
      node = next;
    }
    return node._value !== unset;
  }
  b(key) {
    const path = [{ part: "", node: this.root }];
    let i = 0;
    for (const part of key) {
      const node = path[i].node.children?.get(part);
      if (!node) {
        return;
      }
      path.push({ part, node });
      i++;
    }
    return path;
  }
  c(key, fn, onDescend) {
    let node = this.root;
    for (const part of key) {
      if (!node.children) {
        const next = new Node2();
        node.children = /* @__PURE__ */ new Map([[part, next]]);
        node = next;
      } else if (!node.children.has(part)) {
        const next = new Node2();
        node.children.set(part, next);
        node = next;
      } else {
        node = node.children.get(part);
      }
      onDescend?.(node);
    }
    const sizeBefore = node._value === unset ? 0 : 1;
    fn(node);
    const sizeAfter = node._value === unset ? 0 : 1;
    this.a += sizeAfter - sizeBefore;
  }
  /** Returns an iterable of the tree values in no defined order. */
  *values() {
    for (const { _value } of bfsIterate(this.root)) {
      if (_value !== unset) {
        yield _value;
      }
    }
  }
};
function* bfsIterate(root) {
  const stack = [root];
  while (stack.length > 0) {
    const node = stack.pop();
    yield node;
    if (node.children) {
      for (const child of node.children.values()) {
        stack.push(child);
      }
    }
  }
}
var Node2 = class {
  constructor() {
    this._value = unset;
  }
  get value() {
    return this._value === unset ? void 0 : this._value;
  }
  set value(value) {
    this._value = value === void 0 ? unset : value;
  }
};

// out-build/vs/editor/common/core/position.js
var $8C = class _$8C {
  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 _$8C(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 _$8C.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 _$8C.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 _$8C.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 _$8C(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 _$8C(pos.lineNumber, pos.column);
  }
  /**
   * Test if `obj` is an `IPosition`.
   */
  static isIPosition(obj) {
    return obj && typeof obj.lineNumber === "number" && typeof obj.column === "number";
  }
  toJSON() {
    return {
      lineNumber: this.lineNumber,
      column: this.column
    };
  }
};

// out-build/vs/editor/common/core/range.js
var $9C = class _$9C {
  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 _$9C.isEmpty(this);
  }
  /**
   * Test if `range` is empty.
   */
  static isEmpty(range) {
    return range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn;
  }
  /**
   * Test if position is in this range. If the position is at the edges, will return true.
   */
  containsPosition(position) {
    return _$9C.containsPosition(this, position);
  }
  /**
   * Test if `position` is in `range`. If the position is at the edges, will return true.
   */
  static containsPosition(range, position) {
    if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
      return false;
    }
    if (position.lineNumber === range.startLineNumber && position.column < range.startColumn) {
      return false;
    }
    if (position.lineNumber === range.endLineNumber && position.column > range.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if `position` is in `range`. If the position is at the edges, will return false.
   * @internal
   */
  static strictContainsPosition(range, position) {
    if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
      return false;
    }
    if (position.lineNumber === range.startLineNumber && position.column <= range.startColumn) {
      return false;
    }
    if (position.lineNumber === range.endLineNumber && position.column >= range.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if range is in this range. If the range is equal to this range, will return true.
   */
  containsRange(range) {
    return _$9C.containsRange(this, range);
  }
  /**
   * Test if `otherRange` is in `range`. If the ranges are equal, will return true.
   */
  static containsRange(range, otherRange) {
    if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn < range.startColumn) {
      return false;
    }
    if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn > range.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(range) {
    return _$9C.strictContainsRange(this, range);
  }
  /**
   * Test if `otherRange` is strictly in `range` (must start after, and end before). If the ranges are equal, will return false.
   */
  static strictContainsRange(range, otherRange) {
    if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn <= range.startColumn) {
      return false;
    }
    if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn >= range.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(range) {
    return _$9C.plusRange(this, range);
  }
  /**
   * 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 _$9C(startLineNumber, startColumn, endLineNumber, endColumn);
  }
  /**
   * A intersection of the two ranges.
   */
  intersectRanges(range) {
    return _$9C.intersectRanges(this, range);
  }
  /**
   * 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 _$9C(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
  }
  /**
   * Test if this range equals other.
   */
  equalsRange(other) {
    return _$9C.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 _$9C.getEndPosition(this);
  }
  /**
   * Return the end position (which will be after or equal to the start position)
   */
  static getEndPosition(range) {
    return new $8C(range.endLineNumber, range.endColumn);
  }
  /**
   * Return the start position (which will be before or equal to the end position)
   */
  getStartPosition() {
    return _$9C.getStartPosition(this);
  }
  /**
   * Return the start position (which will be before or equal to the end position)
   */
  static getStartPosition(range) {
    return new $8C(range.startLineNumber, range.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 _$9C(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 _$9C(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
  }
  /**
   * Create a new empty range using this range's start position.
   */
  collapseToStart() {
    return _$9C.collapseToStart(this);
  }
  /**
   * Create a new empty range using this range's start position.
   */
  static collapseToStart(range) {
    return new _$9C(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
  }
  /**
   * Create a new empty range using this range's end position.
   */
  collapseToEnd() {
    return _$9C.collapseToEnd(this);
  }
  /**
   * Create a new empty range using this range's end position.
   */
  static collapseToEnd(range) {
    return new _$9C(range.endLineNumber, range.endColumn, range.endLineNumber, range.endColumn);
  }
  /**
   * Moves the range by the given amount of lines.
   */
  delta(lineCount) {
    return new _$9C(this.startLineNumber + lineCount, this.startColumn, this.endLineNumber + lineCount, this.endColumn);
  }
  // ---
  static fromPositions(start, end = start) {
    return new _$9C(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  static lift(range) {
    if (!range) {
      return null;
    }
    return new _$9C(range.startLineNumber, range.startColumn, range.endLineNumber, range.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(range) {
    return range.endLineNumber > range.startLineNumber;
  }
  toJSON() {
    return this;
  }
};

// out-build/vs/editor/common/tokenizationRegistry.js
var $sE = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = new $ze();
    this.onDidChange = this.c.event;
    this.d = null;
  }
  handleChange(languageIds) {
    this.c.fire({
      changedLanguages: languageIds,
      changedColorMap: false
    });
  }
  register(languageId, support) {
    this.a.set(languageId, support);
    this.handleChange([languageId]);
    return $1c(() => {
      if (this.a.get(languageId) !== support) {
        return;
      }
      this.a.delete(languageId);
      this.handleChange([languageId]);
    });
  }
  get(languageId) {
    return this.a.get(languageId) || null;
  }
  registerFactory(languageId, factory) {
    this.b.get(languageId)?.dispose();
    const myData = new TokenizationSupportFactoryData(this, languageId, factory);
    this.b.set(languageId, myData);
    return $1c(() => {
      const v = this.b.get(languageId);
      if (!v || v !== myData) {
        return;
      }
      this.b.delete(languageId);
      v.dispose();
    });
  }
  async getOrCreate(languageId) {
    const tokenizationSupport = this.get(languageId);
    if (tokenizationSupport) {
      return tokenizationSupport;
    }
    const factory = this.b.get(languageId);
    if (!factory || factory.isResolved) {
      return null;
    }
    await factory.resolve();
    return this.get(languageId);
  }
  isResolved(languageId) {
    const tokenizationSupport = this.get(languageId);
    if (tokenizationSupport) {
      return true;
    }
    const factory = this.b.get(languageId);
    if (!factory || factory.isResolved) {
      return true;
    }
    return false;
  }
  setColorMap(colorMap) {
    this.d = colorMap;
    this.c.fire({
      changedLanguages: Array.from(this.a.keys()),
      changedColorMap: true
    });
  }
  getColorMap() {
    return this.d;
  }
  getDefaultBackground() {
    if (this.d && this.d.length > 2) {
      return this.d[
        2
        /* ColorId.DefaultBackground */
      ];
    }
    return null;
  }
};
var TokenizationSupportFactoryData = class extends $3c {
  get isResolved() {
    return this.c;
  }
  constructor(f, g, h) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.a = false;
    this.b = null;
    this.c = false;
  }
  dispose() {
    this.a = true;
    super.dispose();
  }
  async resolve() {
    if (!this.b) {
      this.b = this.j();
    }
    return this.b;
  }
  async j() {
    const value = await this.h.tokenizationSupport;
    this.c = true;
    if (value && !this.a) {
      this.B(this.f.register(this.g, value));
    }
  }
};

// out-build/vs/editor/common/languages.js
var HoverVerbosityAction;
(function(HoverVerbosityAction3) {
  HoverVerbosityAction3[HoverVerbosityAction3["Increase"] = 0] = "Increase";
  HoverVerbosityAction3[HoverVerbosityAction3["Decrease"] = 1] = "Decrease";
})(HoverVerbosityAction || (HoverVerbosityAction = {}));
var CompletionItemKind;
(function(CompletionItemKind4) {
  CompletionItemKind4[CompletionItemKind4["Method"] = 0] = "Method";
  CompletionItemKind4[CompletionItemKind4["Function"] = 1] = "Function";
  CompletionItemKind4[CompletionItemKind4["Constructor"] = 2] = "Constructor";
  CompletionItemKind4[CompletionItemKind4["Field"] = 3] = "Field";
  CompletionItemKind4[CompletionItemKind4["Variable"] = 4] = "Variable";
  CompletionItemKind4[CompletionItemKind4["Class"] = 5] = "Class";
  CompletionItemKind4[CompletionItemKind4["Struct"] = 6] = "Struct";
  CompletionItemKind4[CompletionItemKind4["Interface"] = 7] = "Interface";
  CompletionItemKind4[CompletionItemKind4["Module"] = 8] = "Module";
  CompletionItemKind4[CompletionItemKind4["Property"] = 9] = "Property";
  CompletionItemKind4[CompletionItemKind4["Event"] = 10] = "Event";
  CompletionItemKind4[CompletionItemKind4["Operator"] = 11] = "Operator";
  CompletionItemKind4[CompletionItemKind4["Unit"] = 12] = "Unit";
  CompletionItemKind4[CompletionItemKind4["Value"] = 13] = "Value";
  CompletionItemKind4[CompletionItemKind4["Constant"] = 14] = "Constant";
  CompletionItemKind4[CompletionItemKind4["Enum"] = 15] = "Enum";
  CompletionItemKind4[CompletionItemKind4["EnumMember"] = 16] = "EnumMember";
  CompletionItemKind4[CompletionItemKind4["Keyword"] = 17] = "Keyword";
  CompletionItemKind4[CompletionItemKind4["Text"] = 18] = "Text";
  CompletionItemKind4[CompletionItemKind4["Color"] = 19] = "Color";
  CompletionItemKind4[CompletionItemKind4["File"] = 20] = "File";
  CompletionItemKind4[CompletionItemKind4["Reference"] = 21] = "Reference";
  CompletionItemKind4[CompletionItemKind4["Customcolor"] = 22] = "Customcolor";
  CompletionItemKind4[CompletionItemKind4["Folder"] = 23] = "Folder";
  CompletionItemKind4[CompletionItemKind4["TypeParameter"] = 24] = "TypeParameter";
  CompletionItemKind4[CompletionItemKind4["User"] = 25] = "User";
  CompletionItemKind4[CompletionItemKind4["Issue"] = 26] = "Issue";
  CompletionItemKind4[CompletionItemKind4["Snippet"] = 27] = "Snippet";
})(CompletionItemKind || (CompletionItemKind = {}));
var CompletionItemKinds;
(function(CompletionItemKinds2) {
  const byKind = /* @__PURE__ */ new Map();
  byKind.set(0, $6l.symbolMethod);
  byKind.set(1, $6l.symbolFunction);
  byKind.set(2, $6l.symbolConstructor);
  byKind.set(3, $6l.symbolField);
  byKind.set(4, $6l.symbolVariable);
  byKind.set(5, $6l.symbolClass);
  byKind.set(6, $6l.symbolStruct);
  byKind.set(7, $6l.symbolInterface);
  byKind.set(8, $6l.symbolModule);
  byKind.set(9, $6l.symbolProperty);
  byKind.set(10, $6l.symbolEvent);
  byKind.set(11, $6l.symbolOperator);
  byKind.set(12, $6l.symbolUnit);
  byKind.set(13, $6l.symbolValue);
  byKind.set(15, $6l.symbolEnum);
  byKind.set(14, $6l.symbolConstant);
  byKind.set(15, $6l.symbolEnum);
  byKind.set(16, $6l.symbolEnumMember);
  byKind.set(17, $6l.symbolKeyword);
  byKind.set(27, $6l.symbolSnippet);
  byKind.set(18, $6l.symbolText);
  byKind.set(19, $6l.symbolColor);
  byKind.set(20, $6l.symbolFile);
  byKind.set(21, $6l.symbolReference);
  byKind.set(22, $6l.symbolCustomColor);
  byKind.set(23, $6l.symbolFolder);
  byKind.set(24, $6l.symbolTypeParameter);
  byKind.set(25, $6l.account);
  byKind.set(26, $6l.issues);
  function toIcon(kind) {
    let codicon = byKind.get(kind);
    if (!codicon) {
      console.info("No codicon found for CompletionItemKind " + kind);
      codicon = $6l.symbolProperty;
    }
    return codicon;
  }
  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 fromString(value, strict) {
    let res = data.get(value);
    if (typeof res === "undefined" && !strict) {
      res = 9;
    }
    return res;
  }
  CompletionItemKinds2.fromString = fromString;
})(CompletionItemKinds || (CompletionItemKinds = {}));
var CompletionItemTag;
(function(CompletionItemTag4) {
  CompletionItemTag4[CompletionItemTag4["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag || (CompletionItemTag = {}));
var CompletionItemInsertTextRule;
(function(CompletionItemInsertTextRule2) {
  CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["None"] = 0] = "None";
  CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["KeepWhitespace"] = 1] = "KeepWhitespace";
  CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["InsertAsSnippet"] = 4] = "InsertAsSnippet";
})(CompletionItemInsertTextRule || (CompletionItemInsertTextRule = {}));
var PartialAcceptTriggerKind;
(function(PartialAcceptTriggerKind4) {
  PartialAcceptTriggerKind4[PartialAcceptTriggerKind4["Word"] = 0] = "Word";
  PartialAcceptTriggerKind4[PartialAcceptTriggerKind4["Line"] = 1] = "Line";
  PartialAcceptTriggerKind4[PartialAcceptTriggerKind4["Suggest"] = 2] = "Suggest";
})(PartialAcceptTriggerKind || (PartialAcceptTriggerKind = {}));
var CompletionTriggerKind;
(function(CompletionTriggerKind4) {
  CompletionTriggerKind4[CompletionTriggerKind4["Invoke"] = 0] = "Invoke";
  CompletionTriggerKind4[CompletionTriggerKind4["TriggerCharacter"] = 1] = "TriggerCharacter";
  CompletionTriggerKind4[CompletionTriggerKind4["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind || (CompletionTriggerKind = {}));
var InlineCompletionTriggerKind;
(function(InlineCompletionTriggerKind3) {
  InlineCompletionTriggerKind3[InlineCompletionTriggerKind3["Automatic"] = 0] = "Automatic";
  InlineCompletionTriggerKind3[InlineCompletionTriggerKind3["Explicit"] = 1] = "Explicit";
})(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
var CodeActionTriggerType;
(function(CodeActionTriggerType2) {
  CodeActionTriggerType2[CodeActionTriggerType2["Invoke"] = 1] = "Invoke";
  CodeActionTriggerType2[CodeActionTriggerType2["Auto"] = 2] = "Auto";
})(CodeActionTriggerType || (CodeActionTriggerType = {}));
var DocumentPasteTriggerKind;
(function(DocumentPasteTriggerKind3) {
  DocumentPasteTriggerKind3[DocumentPasteTriggerKind3["Automatic"] = 0] = "Automatic";
  DocumentPasteTriggerKind3[DocumentPasteTriggerKind3["PasteAs"] = 1] = "PasteAs";
})(DocumentPasteTriggerKind || (DocumentPasteTriggerKind = {}));
var SignatureHelpTriggerKind;
(function(SignatureHelpTriggerKind3) {
  SignatureHelpTriggerKind3[SignatureHelpTriggerKind3["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind3[SignatureHelpTriggerKind3["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind3[SignatureHelpTriggerKind3["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind || (SignatureHelpTriggerKind = {}));
var DocumentHighlightKind;
(function(DocumentHighlightKind3) {
  DocumentHighlightKind3[DocumentHighlightKind3["Text"] = 0] = "Text";
  DocumentHighlightKind3[DocumentHighlightKind3["Read"] = 1] = "Read";
  DocumentHighlightKind3[DocumentHighlightKind3["Write"] = 2] = "Write";
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
function $RE(thing) {
  return thing && URI.isUri(thing.uri) && $9C.isIRange(thing.range) && ($9C.isIRange(thing.originSelectionRange) || $9C.isIRange(thing.targetSelectionRange));
}
var SymbolKind;
(function(SymbolKind4) {
  SymbolKind4[SymbolKind4["File"] = 0] = "File";
  SymbolKind4[SymbolKind4["Module"] = 1] = "Module";
  SymbolKind4[SymbolKind4["Namespace"] = 2] = "Namespace";
  SymbolKind4[SymbolKind4["Package"] = 3] = "Package";
  SymbolKind4[SymbolKind4["Class"] = 4] = "Class";
  SymbolKind4[SymbolKind4["Method"] = 5] = "Method";
  SymbolKind4[SymbolKind4["Property"] = 6] = "Property";
  SymbolKind4[SymbolKind4["Field"] = 7] = "Field";
  SymbolKind4[SymbolKind4["Constructor"] = 8] = "Constructor";
  SymbolKind4[SymbolKind4["Enum"] = 9] = "Enum";
  SymbolKind4[SymbolKind4["Interface"] = 10] = "Interface";
  SymbolKind4[SymbolKind4["Function"] = 11] = "Function";
  SymbolKind4[SymbolKind4["Variable"] = 12] = "Variable";
  SymbolKind4[SymbolKind4["Constant"] = 13] = "Constant";
  SymbolKind4[SymbolKind4["String"] = 14] = "String";
  SymbolKind4[SymbolKind4["Number"] = 15] = "Number";
  SymbolKind4[SymbolKind4["Boolean"] = 16] = "Boolean";
  SymbolKind4[SymbolKind4["Array"] = 17] = "Array";
  SymbolKind4[SymbolKind4["Object"] = 18] = "Object";
  SymbolKind4[SymbolKind4["Key"] = 19] = "Key";
  SymbolKind4[SymbolKind4["Null"] = 20] = "Null";
  SymbolKind4[SymbolKind4["EnumMember"] = 21] = "EnumMember";
  SymbolKind4[SymbolKind4["Struct"] = 22] = "Struct";
  SymbolKind4[SymbolKind4["Event"] = 23] = "Event";
  SymbolKind4[SymbolKind4["Operator"] = 24] = "Operator";
  SymbolKind4[SymbolKind4["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind || (SymbolKind = {}));
var $TE = {
  [
    17
    /* SymbolKind.Array */
  ]: localize(804, null),
  [
    16
    /* SymbolKind.Boolean */
  ]: localize(805, null),
  [
    4
    /* SymbolKind.Class */
  ]: localize(806, null),
  [
    13
    /* SymbolKind.Constant */
  ]: localize(807, null),
  [
    8
    /* SymbolKind.Constructor */
  ]: localize(808, null),
  [
    9
    /* SymbolKind.Enum */
  ]: localize(809, null),
  [
    21
    /* SymbolKind.EnumMember */
  ]: localize(810, null),
  [
    23
    /* SymbolKind.Event */
  ]: localize(811, null),
  [
    7
    /* SymbolKind.Field */
  ]: localize(812, null),
  [
    0
    /* SymbolKind.File */
  ]: localize(813, null),
  [
    11
    /* SymbolKind.Function */
  ]: localize(814, null),
  [
    10
    /* SymbolKind.Interface */
  ]: localize(815, null),
  [
    19
    /* SymbolKind.Key */
  ]: localize(816, null),
  [
    5
    /* SymbolKind.Method */
  ]: localize(817, null),
  [
    1
    /* SymbolKind.Module */
  ]: localize(818, null),
  [
    2
    /* SymbolKind.Namespace */
  ]: localize(819, null),
  [
    20
    /* SymbolKind.Null */
  ]: localize(820, null),
  [
    15
    /* SymbolKind.Number */
  ]: localize(821, null),
  [
    18
    /* SymbolKind.Object */
  ]: localize(822, null),
  [
    24
    /* SymbolKind.Operator */
  ]: localize(823, null),
  [
    3
    /* SymbolKind.Package */
  ]: localize(824, null),
  [
    6
    /* SymbolKind.Property */
  ]: localize(825, null),
  [
    14
    /* SymbolKind.String */
  ]: localize(826, null),
  [
    22
    /* SymbolKind.Struct */
  ]: localize(827, null),
  [
    25
    /* SymbolKind.TypeParameter */
  ]: localize(828, null),
  [
    12
    /* SymbolKind.Variable */
  ]: localize(829, null)
};
var SymbolTag;
(function(SymbolTag4) {
  SymbolTag4[SymbolTag4["Deprecated"] = 1] = "Deprecated";
})(SymbolTag || (SymbolTag = {}));
var SymbolKinds;
(function(SymbolKinds2) {
  const byKind = /* @__PURE__ */ new Map();
  byKind.set(0, $6l.symbolFile);
  byKind.set(1, $6l.symbolModule);
  byKind.set(2, $6l.symbolNamespace);
  byKind.set(3, $6l.symbolPackage);
  byKind.set(4, $6l.symbolClass);
  byKind.set(5, $6l.symbolMethod);
  byKind.set(6, $6l.symbolProperty);
  byKind.set(7, $6l.symbolField);
  byKind.set(8, $6l.symbolConstructor);
  byKind.set(9, $6l.symbolEnum);
  byKind.set(10, $6l.symbolInterface);
  byKind.set(11, $6l.symbolFunction);
  byKind.set(12, $6l.symbolVariable);
  byKind.set(13, $6l.symbolConstant);
  byKind.set(14, $6l.symbolString);
  byKind.set(15, $6l.symbolNumber);
  byKind.set(16, $6l.symbolBoolean);
  byKind.set(17, $6l.symbolArray);
  byKind.set(18, $6l.symbolObject);
  byKind.set(19, $6l.symbolKey);
  byKind.set(20, $6l.symbolNull);
  byKind.set(21, $6l.symbolEnumMember);
  byKind.set(22, $6l.symbolStruct);
  byKind.set(23, $6l.symbolEvent);
  byKind.set(24, $6l.symbolOperator);
  byKind.set(25, $6l.symbolTypeParameter);
  function toIcon(kind) {
    let icon = byKind.get(kind);
    if (!icon) {
      console.info("No codicon found for SymbolKind " + kind);
      icon = $6l.symbolProperty;
    }
    return icon;
  }
  SymbolKinds2.toIcon = toIcon;
  const byCompletionKind = /* @__PURE__ */ new Map();
  byCompletionKind.set(
    0,
    20
    /* CompletionItemKind.File */
  );
  byCompletionKind.set(
    1,
    8
    /* CompletionItemKind.Module */
  );
  byCompletionKind.set(
    2,
    8
    /* CompletionItemKind.Module */
  );
  byCompletionKind.set(
    3,
    8
    /* CompletionItemKind.Module */
  );
  byCompletionKind.set(
    4,
    5
    /* CompletionItemKind.Class */
  );
  byCompletionKind.set(
    5,
    0
    /* CompletionItemKind.Method */
  );
  byCompletionKind.set(
    6,
    9
    /* CompletionItemKind.Property */
  );
  byCompletionKind.set(
    7,
    3
    /* CompletionItemKind.Field */
  );
  byCompletionKind.set(
    8,
    2
    /* CompletionItemKind.Constructor */
  );
  byCompletionKind.set(
    9,
    15
    /* CompletionItemKind.Enum */
  );
  byCompletionKind.set(
    10,
    7
    /* CompletionItemKind.Interface */
  );
  byCompletionKind.set(
    11,
    1
    /* CompletionItemKind.Function */
  );
  byCompletionKind.set(
    12,
    4
    /* CompletionItemKind.Variable */
  );
  byCompletionKind.set(
    13,
    14
    /* CompletionItemKind.Constant */
  );
  byCompletionKind.set(
    14,
    18
    /* CompletionItemKind.Text */
  );
  byCompletionKind.set(
    15,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    16,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    17,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    18,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    19,
    17
    /* CompletionItemKind.Keyword */
  );
  byCompletionKind.set(
    20,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    21,
    16
    /* CompletionItemKind.EnumMember */
  );
  byCompletionKind.set(
    22,
    6
    /* CompletionItemKind.Struct */
  );
  byCompletionKind.set(
    23,
    10
    /* CompletionItemKind.Event */
  );
  byCompletionKind.set(
    24,
    11
    /* CompletionItemKind.Operator */
  );
  byCompletionKind.set(
    25,
    24
    /* CompletionItemKind.TypeParameter */
  );
  function toCompletionKind(kind) {
    let completionKind = byCompletionKind.get(kind);
    if (completionKind === void 0) {
      console.info("No completion kind found for SymbolKind " + kind);
      completionKind = 20;
    }
    return completionKind;
  }
  SymbolKinds2.toCompletionKind = toCompletionKind;
})(SymbolKinds || (SymbolKinds = {}));
var $WE = class _$WE {
  static {
    this.Comment = new _$WE("comment");
  }
  static {
    this.Imports = new _$WE("imports");
  }
  static {
    this.Region = new _$WE("region");
  }
  /**
   * Returns a {@link $WE} for the given value.
   *
   * @param value of the kind.
   */
  static fromValue(value) {
    switch (value) {
      case "comment":
        return _$WE.Comment;
      case "imports":
        return _$WE.Imports;
      case "region":
        return _$WE.Region;
    }
    return new _$WE(value);
  }
  /**
   * Creates a new {@link $WE}.
   *
   * @param value of the kind.
   */
  constructor(value) {
    this.value = value;
  }
};
var NewSymbolNameTag;
(function(NewSymbolNameTag3) {
  NewSymbolNameTag3[NewSymbolNameTag3["AIGenerated"] = 1] = "AIGenerated";
})(NewSymbolNameTag || (NewSymbolNameTag = {}));
var NewSymbolNameTriggerKind;
(function(NewSymbolNameTriggerKind3) {
  NewSymbolNameTriggerKind3[NewSymbolNameTriggerKind3["Invoke"] = 0] = "Invoke";
  NewSymbolNameTriggerKind3[NewSymbolNameTriggerKind3["Automatic"] = 1] = "Automatic";
})(NewSymbolNameTriggerKind || (NewSymbolNameTriggerKind = {}));
var Command;
(function(Command2) {
  function is(obj) {
    if (!obj || typeof obj !== "object") {
      return false;
    }
    return typeof obj.id === "string" && typeof obj.title === "string";
  }
  Command2.is = is;
})(Command || (Command = {}));
var CommentThreadCollapsibleState;
(function(CommentThreadCollapsibleState3) {
  CommentThreadCollapsibleState3[CommentThreadCollapsibleState3["Collapsed"] = 0] = "Collapsed";
  CommentThreadCollapsibleState3[CommentThreadCollapsibleState3["Expanded"] = 1] = "Expanded";
})(CommentThreadCollapsibleState || (CommentThreadCollapsibleState = {}));
var CommentThreadState;
(function(CommentThreadState3) {
  CommentThreadState3[CommentThreadState3["Unresolved"] = 0] = "Unresolved";
  CommentThreadState3[CommentThreadState3["Resolved"] = 1] = "Resolved";
})(CommentThreadState || (CommentThreadState = {}));
var CommentThreadApplicability;
(function(CommentThreadApplicability3) {
  CommentThreadApplicability3[CommentThreadApplicability3["Current"] = 0] = "Current";
  CommentThreadApplicability3[CommentThreadApplicability3["Outdated"] = 1] = "Outdated";
})(CommentThreadApplicability || (CommentThreadApplicability = {}));
var CommentMode;
(function(CommentMode3) {
  CommentMode3[CommentMode3["Editing"] = 0] = "Editing";
  CommentMode3[CommentMode3["Preview"] = 1] = "Preview";
})(CommentMode || (CommentMode = {}));
var CommentState;
(function(CommentState3) {
  CommentState3[CommentState3["Published"] = 0] = "Published";
  CommentState3[CommentState3["Draft"] = 1] = "Draft";
})(CommentState || (CommentState = {}));
var InlayHintKind;
(function(InlayHintKind4) {
  InlayHintKind4[InlayHintKind4["Type"] = 1] = "Type";
  InlayHintKind4[InlayHintKind4["Parameter"] = 2] = "Parameter";
})(InlayHintKind || (InlayHintKind = {}));
var $YE = new $sE();
var $ZE = new $sE();
var ExternalUriOpenerPriority;
(function(ExternalUriOpenerPriority3) {
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["None"] = 0] = "None";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Option"] = 1] = "Option";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Default"] = 2] = "Default";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Preferred"] = 3] = "Preferred";
})(ExternalUriOpenerPriority || (ExternalUriOpenerPriority = {}));
var InlineEditTriggerKind;
(function(InlineEditTriggerKind3) {
  InlineEditTriggerKind3[InlineEditTriggerKind3["Invoke"] = 0] = "Invoke";
  InlineEditTriggerKind3[InlineEditTriggerKind3["Automatic"] = 1] = "Automatic";
})(InlineEditTriggerKind || (InlineEditTriggerKind = {}));

// out-build/vs/platform/markers/common/markers.js
var MarkerTag;
(function(MarkerTag2) {
  MarkerTag2[MarkerTag2["Unnecessary"] = 1] = "Unnecessary";
  MarkerTag2[MarkerTag2["Deprecated"] = 2] = "Deprecated";
})(MarkerTag || (MarkerTag = {}));
var MarkerSeverity;
(function(MarkerSeverity2) {
  MarkerSeverity2[MarkerSeverity2["Hint"] = 1] = "Hint";
  MarkerSeverity2[MarkerSeverity2["Info"] = 2] = "Info";
  MarkerSeverity2[MarkerSeverity2["Warning"] = 4] = "Warning";
  MarkerSeverity2[MarkerSeverity2["Error"] = 8] = "Error";
})(MarkerSeverity || (MarkerSeverity = {}));
(function(MarkerSeverity2) {
  function compare3(a, b) {
    return b - a;
  }
  MarkerSeverity2.compare = compare3;
  const _displayStrings = /* @__PURE__ */ Object.create(null);
  _displayStrings[MarkerSeverity2.Error] = localize(1998, null);
  _displayStrings[MarkerSeverity2.Warning] = localize(1999, null);
  _displayStrings[MarkerSeverity2.Info] = localize(2e3, null);
  function toString(a) {
    return _displayStrings[a] || "";
  }
  MarkerSeverity2.toString = toString;
  function fromSeverity(severity) {
    switch (severity) {
      case severity_default.Error:
        return MarkerSeverity2.Error;
      case severity_default.Warning:
        return MarkerSeverity2.Warning;
      case severity_default.Info:
        return MarkerSeverity2.Info;
      case severity_default.Ignore:
        return MarkerSeverity2.Hint;
    }
  }
  MarkerSeverity2.fromSeverity = fromSeverity;
  function toSeverity(severity) {
    switch (severity) {
      case MarkerSeverity2.Error:
        return severity_default.Error;
      case MarkerSeverity2.Warning:
        return severity_default.Warning;
      case MarkerSeverity2.Info:
        return severity_default.Info;
      case MarkerSeverity2.Hint:
        return severity_default.Ignore;
    }
  }
  MarkerSeverity2.toSeverity = toSeverity;
})(MarkerSeverity || (MarkerSeverity = {}));
var IMarkerData;
(function(IMarkerData2) {
  const emptyString = "";
  function makeKey(markerData) {
    return makeKeyOptionalMessage(markerData, true);
  }
  IMarkerData2.makeKey = makeKey;
  function makeKeyOptionalMessage(markerData, useMessage) {
    const result = [emptyString];
    if (markerData.source) {
      result.push(markerData.source.replace("\xA6", "\\\xA6"));
    } else {
      result.push(emptyString);
    }
    if (markerData.code) {
      if (typeof markerData.code === "string") {
        result.push(markerData.code.replace("\xA6", "\\\xA6"));
      } else {
        result.push(markerData.code.value.replace("\xA6", "\\\xA6"));
      }
    } else {
      result.push(emptyString);
    }
    if (markerData.severity !== void 0 && markerData.severity !== null) {
      result.push(MarkerSeverity.toString(markerData.severity));
    } else {
      result.push(emptyString);
    }
    if (markerData.message && useMessage) {
      result.push(markerData.message.replace("\xA6", "\\\xA6"));
    } else {
      result.push(emptyString);
    }
    if (markerData.startLineNumber !== void 0 && markerData.startLineNumber !== null) {
      result.push(markerData.startLineNumber.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.startColumn !== void 0 && markerData.startColumn !== null) {
      result.push(markerData.startColumn.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.endLineNumber !== void 0 && markerData.endLineNumber !== null) {
      result.push(markerData.endLineNumber.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.endColumn !== void 0 && markerData.endColumn !== null) {
      result.push(markerData.endColumn.toString());
    } else {
      result.push(emptyString);
    }
    result.push(emptyString);
    return result.join("\xA6");
  }
  IMarkerData2.makeKeyOptionalMessage = makeKeyOptionalMessage;
})(IMarkerData || (IMarkerData = {}));
var $DE = $Qk("markerService");

// out-build/vs/base/common/assert.js
function ok(value, message) {
  if (!value) {
    throw new Error(message ? `Assertion failed (${message})` : "Assertion Failed");
  }
}
function $hd(value, message = "Unreachable") {
  throw new Error(message);
}
function $kd(condition) {
  if (!condition()) {
    debugger;
    condition();
    $gb(new $vb("Assertion Failed"));
  }
}

// out-build/vs/platform/registry/common/platform.js
var RegistryImpl = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  add(id2, data) {
    ok($zg(id2));
    ok($Bg(data));
    ok(!this.a.has(id2), "There is already an extension with this id");
    this.a.set(id2, data);
  }
  knows(id2) {
    return this.a.has(id2);
  }
  as(id2) {
    return this.a.get(id2) || null;
  }
};
var $Wn = new RegistryImpl();

// out-build/vs/platform/files/common/files.js
var $km = $Qk("fileService");
function $lm(options2) {
  return options2.create === true;
}
var FileType;
(function(FileType2) {
  FileType2[FileType2["Unknown"] = 0] = "Unknown";
  FileType2[FileType2["File"] = 1] = "File";
  FileType2[FileType2["Directory"] = 2] = "Directory";
  FileType2[FileType2["SymbolicLink"] = 64] = "SymbolicLink";
})(FileType || (FileType = {}));
var FilePermission;
(function(FilePermission2) {
  FilePermission2[FilePermission2["Readonly"] = 1] = "Readonly";
  FilePermission2[FilePermission2["Locked"] = 2] = "Locked";
})(FilePermission || (FilePermission = {}));
var FileChangeFilter;
(function(FileChangeFilter2) {
  FileChangeFilter2[FileChangeFilter2["UPDATED"] = 2] = "UPDATED";
  FileChangeFilter2[FileChangeFilter2["ADDED"] = 4] = "ADDED";
  FileChangeFilter2[FileChangeFilter2["DELETED"] = 8] = "DELETED";
})(FileChangeFilter || (FileChangeFilter = {}));
var FileSystemProviderCapabilities;
(function(FileSystemProviderCapabilities2) {
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["None"] = 0] = "None";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileReadWrite"] = 2] = "FileReadWrite";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileOpenReadWriteClose"] = 4] = "FileOpenReadWriteClose";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileReadStream"] = 16] = "FileReadStream";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileFolderCopy"] = 8] = "FileFolderCopy";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["PathCaseSensitive"] = 1024] = "PathCaseSensitive";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["Readonly"] = 2048] = "Readonly";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["Trash"] = 4096] = "Trash";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileWriteUnlock"] = 8192] = "FileWriteUnlock";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileAtomicRead"] = 16384] = "FileAtomicRead";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileAtomicWrite"] = 32768] = "FileAtomicWrite";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileAtomicDelete"] = 65536] = "FileAtomicDelete";
  FileSystemProviderCapabilities2[FileSystemProviderCapabilities2["FileClone"] = 131072] = "FileClone";
})(FileSystemProviderCapabilities || (FileSystemProviderCapabilities = {}));
var FileSystemProviderErrorCode;
(function(FileSystemProviderErrorCode2) {
  FileSystemProviderErrorCode2["FileExists"] = "EntryExists";
  FileSystemProviderErrorCode2["FileNotFound"] = "EntryNotFound";
  FileSystemProviderErrorCode2["FileNotADirectory"] = "EntryNotADirectory";
  FileSystemProviderErrorCode2["FileIsADirectory"] = "EntryIsADirectory";
  FileSystemProviderErrorCode2["FileExceedsStorageQuota"] = "EntryExceedsStorageQuota";
  FileSystemProviderErrorCode2["FileTooLarge"] = "EntryTooLarge";
  FileSystemProviderErrorCode2["FileWriteLocked"] = "EntryWriteLocked";
  FileSystemProviderErrorCode2["NoPermissions"] = "NoPermissions";
  FileSystemProviderErrorCode2["Unavailable"] = "Unavailable";
  FileSystemProviderErrorCode2["Unknown"] = "Unknown";
})(FileSystemProviderErrorCode || (FileSystemProviderErrorCode = {}));
var $wm = class _$wm extends Error {
  static create(error, code) {
    const providerError = new _$wm(error.toString(), code);
    $zm(providerError, code);
    return providerError;
  }
  constructor(message, code) {
    super(message);
    this.code = code;
  }
};
function $xm(error, code) {
  return $wm.create(error, code);
}
function $ym(error) {
  if (!error) {
    return $xm(localize(1910, null), FileSystemProviderErrorCode.Unknown);
  }
  return error;
}
function $zm(error, code) {
  error.name = code ? `${code} (FileSystemError)` : `FileSystemError`;
  return error;
}
function $Am(error) {
  if (!error) {
    return FileSystemProviderErrorCode.Unknown;
  }
  if (error instanceof $wm) {
    return error.code;
  }
  const match = /^(.+) \(FileSystemError\)$/.exec(error.name);
  if (!match) {
    return FileSystemProviderErrorCode.Unknown;
  }
  switch (match[1]) {
    case FileSystemProviderErrorCode.FileExists:
      return FileSystemProviderErrorCode.FileExists;
    case FileSystemProviderErrorCode.FileIsADirectory:
      return FileSystemProviderErrorCode.FileIsADirectory;
    case FileSystemProviderErrorCode.FileNotADirectory:
      return FileSystemProviderErrorCode.FileNotADirectory;
    case FileSystemProviderErrorCode.FileNotFound:
      return FileSystemProviderErrorCode.FileNotFound;
    case FileSystemProviderErrorCode.FileTooLarge:
      return FileSystemProviderErrorCode.FileTooLarge;
    case FileSystemProviderErrorCode.FileWriteLocked:
      return FileSystemProviderErrorCode.FileWriteLocked;
    case FileSystemProviderErrorCode.NoPermissions:
      return FileSystemProviderErrorCode.NoPermissions;
    case FileSystemProviderErrorCode.Unavailable:
      return FileSystemProviderErrorCode.Unavailable;
  }
  return FileSystemProviderErrorCode.Unknown;
}
function $Bm(error) {
  if (error instanceof $Fm) {
    return error.fileOperationResult;
  }
  switch ($Am(error)) {
    case FileSystemProviderErrorCode.FileNotFound:
      return 1;
    case FileSystemProviderErrorCode.FileIsADirectory:
      return 0;
    case FileSystemProviderErrorCode.FileNotADirectory:
      return 9;
    case FileSystemProviderErrorCode.FileWriteLocked:
      return 5;
    case FileSystemProviderErrorCode.NoPermissions:
      return 6;
    case FileSystemProviderErrorCode.FileExists:
      return 4;
    case FileSystemProviderErrorCode.FileTooLarge:
      return 7;
    default:
      return 10;
  }
}
var FileOperation;
(function(FileOperation2) {
  FileOperation2[FileOperation2["CREATE"] = 0] = "CREATE";
  FileOperation2[FileOperation2["DELETE"] = 1] = "DELETE";
  FileOperation2[FileOperation2["MOVE"] = 2] = "MOVE";
  FileOperation2[FileOperation2["COPY"] = 3] = "COPY";
  FileOperation2[FileOperation2["WRITE"] = 4] = "WRITE";
})(FileOperation || (FileOperation = {}));
var FileChangeType;
(function(FileChangeType3) {
  FileChangeType3[FileChangeType3["UPDATED"] = 0] = "UPDATED";
  FileChangeType3[FileChangeType3["ADDED"] = 1] = "ADDED";
  FileChangeType3[FileChangeType3["DELETED"] = 2] = "DELETED";
})(FileChangeType || (FileChangeType = {}));
var $Dm = class _$Dm {
  static {
    this.a = null;
  }
  constructor(changes, c) {
    this.c = c;
    this.b = void 0;
    this.d = new $sf(() => {
      const added = $Wk.forUris(() => this.c);
      added.fill(this.rawAdded.map((resource) => [resource, true]));
      return added;
    });
    this.f = new $sf(() => {
      const updated = $Wk.forUris(() => this.c);
      updated.fill(this.rawUpdated.map((resource) => [resource, true]));
      return updated;
    });
    this.g = new $sf(() => {
      const deleted = $Wk.forUris(() => this.c);
      deleted.fill(this.rawDeleted.map((resource) => [resource, true]));
      return deleted;
    });
    this.rawAdded = [];
    this.rawUpdated = [];
    this.rawDeleted = [];
    for (const change of changes) {
      switch (change.type) {
        case 1:
          this.rawAdded.push(change.resource);
          break;
        case 0:
          this.rawUpdated.push(change.resource);
          break;
        case 2:
          this.rawDeleted.push(change.resource);
          break;
      }
      if (this.b !== _$Dm.a) {
        if (typeof change.cId === "number") {
          if (this.b === void 0) {
            this.b = change.cId;
          } else if (this.b !== change.cId) {
            this.b = _$Dm.a;
          }
        } else {
          if (this.b !== void 0) {
            this.b = _$Dm.a;
          }
        }
      }
    }
  }
  /**
   * Find out if the file change events match the provided resource.
   *
   * Note: when passing `FileChangeType.DELETED`, we consider a match
   * also when the parent of the resource got deleted.
   */
  contains(resource, ...types) {
    return this.h(resource, { includeChildren: false }, ...types);
  }
  /**
   * Find out if the file change events either match the provided
   * resource, or contain a child of this resource.
   */
  affects(resource, ...types) {
    return this.h(resource, { includeChildren: true }, ...types);
  }
  h(resource, options2, ...types) {
    if (!resource) {
      return false;
    }
    const hasTypesFilter = types.length > 0;
    if (!hasTypesFilter || types.includes(
      1
      /* FileChangeType.ADDED */
    )) {
      if (this.d.value.get(resource)) {
        return true;
      }
      if (options2.includeChildren && this.d.value.findSuperstr(resource)) {
        return true;
      }
    }
    if (!hasTypesFilter || types.includes(
      0
      /* FileChangeType.UPDATED */
    )) {
      if (this.f.value.get(resource)) {
        return true;
      }
      if (options2.includeChildren && this.f.value.findSuperstr(resource)) {
        return true;
      }
    }
    if (!hasTypesFilter || types.includes(
      2
      /* FileChangeType.DELETED */
    )) {
      if (this.g.value.findSubstr(resource)) {
        return true;
      }
      if (options2.includeChildren && this.g.value.findSuperstr(resource)) {
        return true;
      }
    }
    return false;
  }
  /**
   * Returns if this event contains added files.
   */
  gotAdded() {
    return this.rawAdded.length > 0;
  }
  /**
   * Returns if this event contains deleted files.
   */
  gotDeleted() {
    return this.rawDeleted.length > 0;
  }
  /**
   * Returns if this event contains updated files.
   */
  gotUpdated() {
    return this.rawUpdated.length > 0;
  }
  /**
   * Returns if this event contains changes that correlate to the
   * provided `correlationId`.
   *
   * File change event correlation is an advanced watch feature that
   * allows to  identify from which watch request the events originate
   * from. This correlation allows to route events specifically
   * only to the requestor and not emit them to all listeners.
   */
  correlates(correlationId) {
    return this.b === correlationId;
  }
  /**
   * Figure out if the event contains changes that correlate to one
   * correlation identifier.
   *
   * File change event correlation is an advanced watch feature that
   * allows to  identify from which watch request the events originate
   * from. This correlation allows to route events specifically
   * only to the requestor and not emit them to all listeners.
   */
  hasCorrelation() {
    return typeof this.b === "number";
  }
};
function $Em(path, candidate, ignoreCase) {
  if (!path || !candidate || path === candidate) {
    return false;
  }
  if (candidate.length > path.length) {
    return false;
  }
  if (candidate.charAt(candidate.length - 1) !== sep) {
    candidate += sep;
  }
  if (ignoreCase) {
    return $2f(path, candidate);
  }
  return path.indexOf(candidate) === 0;
}
var $Fm = class extends Error {
  constructor(message, fileOperationResult, options2) {
    super(message);
    this.fileOperationResult = fileOperationResult;
    this.options = options2;
  }
};
var FileOperationResult;
(function(FileOperationResult2) {
  FileOperationResult2[FileOperationResult2["FILE_IS_DIRECTORY"] = 0] = "FILE_IS_DIRECTORY";
  FileOperationResult2[FileOperationResult2["FILE_NOT_FOUND"] = 1] = "FILE_NOT_FOUND";
  FileOperationResult2[FileOperationResult2["FILE_NOT_MODIFIED_SINCE"] = 2] = "FILE_NOT_MODIFIED_SINCE";
  FileOperationResult2[FileOperationResult2["FILE_MODIFIED_SINCE"] = 3] = "FILE_MODIFIED_SINCE";
  FileOperationResult2[FileOperationResult2["FILE_MOVE_CONFLICT"] = 4] = "FILE_MOVE_CONFLICT";
  FileOperationResult2[FileOperationResult2["FILE_WRITE_LOCKED"] = 5] = "FILE_WRITE_LOCKED";
  FileOperationResult2[FileOperationResult2["FILE_PERMISSION_DENIED"] = 6] = "FILE_PERMISSION_DENIED";
  FileOperationResult2[FileOperationResult2["FILE_TOO_LARGE"] = 7] = "FILE_TOO_LARGE";
  FileOperationResult2[FileOperationResult2["FILE_INVALID_PATH"] = 8] = "FILE_INVALID_PATH";
  FileOperationResult2[FileOperationResult2["FILE_NOT_DIRECTORY"] = 9] = "FILE_NOT_DIRECTORY";
  FileOperationResult2[FileOperationResult2["FILE_OTHER_ERROR"] = 10] = "FILE_OTHER_ERROR";
})(FileOperationResult || (FileOperationResult = {}));
var FileKind;
(function(FileKind2) {
  FileKind2[FileKind2["FILE"] = 0] = "FILE";
  FileKind2[FileKind2["FOLDER"] = 1] = "FOLDER";
  FileKind2[FileKind2["ROOT_FOLDER"] = 2] = "ROOT_FOLDER";
})(FileKind || (FileKind = {}));
var $Pm = "";
function $Qm(stat2) {
  if (typeof stat2.size !== "number" || typeof stat2.mtime !== "number") {
    return void 0;
  }
  return stat2.mtime.toString(29) + stat2.size.toString(31);
}
var $Sm = class _$Sm {
  static {
    this.KB = 1024;
  }
  static {
    this.MB = _$Sm.KB * _$Sm.KB;
  }
  static {
    this.GB = _$Sm.MB * _$Sm.KB;
  }
  static {
    this.TB = _$Sm.GB * _$Sm.KB;
  }
  static formatSize(size) {
    if (!$Dg(size)) {
      size = 0;
    }
    if (size < _$Sm.KB) {
      return localize(1911, null, size.toFixed(0));
    }
    if (size < _$Sm.MB) {
      return localize(1912, null, (size / _$Sm.KB).toFixed(2));
    }
    if (size < _$Sm.GB) {
      return localize(1913, null, (size / _$Sm.MB).toFixed(2));
    }
    if (size < _$Sm.TB) {
      return localize(1914, null, (size / _$Sm.GB).toFixed(2));
    }
    return localize(1915, null, (size / _$Sm.TB).toFixed(2));
  }
};

// out-build/vs/base/common/actions.js
var $Um = class extends $3c {
  constructor(id2, label = "", cssClass = "", enabled = true, actionCallback) {
    super();
    this.j = this.B(new $ze());
    this.onDidChange = this.j.event;
    this.z = true;
    this.m = id2;
    this.n = label;
    this.w = cssClass;
    this.z = enabled;
    this.D = actionCallback;
  }
  get id() {
    return this.m;
  }
  get label() {
    return this.n;
  }
  set label(value) {
    this.F(value);
  }
  F(value) {
    if (this.n !== value) {
      this.n = value;
      this.j.fire({ label: value });
    }
  }
  get tooltip() {
    return this.u || "";
  }
  set tooltip(value) {
    this.G(value);
  }
  G(value) {
    if (this.u !== value) {
      this.u = value;
      this.j.fire({ tooltip: value });
    }
  }
  get class() {
    return this.w;
  }
  set class(value) {
    this.H(value);
  }
  H(value) {
    if (this.w !== value) {
      this.w = value;
      this.j.fire({ class: value });
    }
  }
  get enabled() {
    return this.z;
  }
  set enabled(value) {
    this.I(value);
  }
  I(value) {
    if (this.z !== value) {
      this.z = value;
      this.j.fire({ enabled: value });
    }
  }
  get checked() {
    return this.C;
  }
  set checked(value) {
    this.J(value);
  }
  J(value) {
    if (this.C !== value) {
      this.C = value;
      this.j.fire({ checked: value });
    }
  }
  async run(event, data) {
    if (this.D) {
      await this.D(event);
    }
  }
};
var $Wm = class _$Wm {
  constructor() {
    this.id = _$Wm.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 _$Wm(), ...list2];
      } else {
        out = list2;
      }
    }
    return out;
  }
  static {
    this.ID = "vs.actions.separator";
  }
  async run() {
  }
};
var $Ym = class _$Ym extends $Um {
  static {
    this.ID = "vs.actions.empty";
  }
  constructor() {
    super(_$Ym.ID, localize(44, null), void 0, false);
  }
};

// out-build/vs/workbench/common/editor.js
var $ZK = {
  EditorPane: "workbench.contributions.editors",
  EditorFactory: "workbench.contributions.editor.inputFactories"
};
var $1K = {
  id: "default",
  displayName: localize(4133, null),
  providerDisplayName: localize(4134, null)
};
var EditorPaneSelectionChangeReason;
(function(EditorPaneSelectionChangeReason2) {
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["PROGRAMMATIC"] = 1] = "PROGRAMMATIC";
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["USER"] = 2] = "USER";
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["EDIT"] = 3] = "EDIT";
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["NAVIGATION"] = 4] = "NAVIGATION";
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["JUMP"] = 5] = "JUMP";
})(EditorPaneSelectionChangeReason || (EditorPaneSelectionChangeReason = {}));
var EditorPaneSelectionCompareResult;
(function(EditorPaneSelectionCompareResult2) {
  EditorPaneSelectionCompareResult2[EditorPaneSelectionCompareResult2["IDENTICAL"] = 1] = "IDENTICAL";
  EditorPaneSelectionCompareResult2[EditorPaneSelectionCompareResult2["SIMILAR"] = 2] = "SIMILAR";
  EditorPaneSelectionCompareResult2[EditorPaneSelectionCompareResult2["DIFFERENT"] = 3] = "DIFFERENT";
})(EditorPaneSelectionCompareResult || (EditorPaneSelectionCompareResult = {}));
function $9K(editor) {
  if ($dL(editor)) {
    return false;
  }
  const candidate = editor;
  return candidate?.original !== void 0 && candidate.modified !== void 0;
}
function $0K(editor) {
  if ($dL(editor)) {
    return false;
  }
  const candidate = editor;
  if (!candidate) {
    return false;
  }
  if (candidate.resources && !Array.isArray(candidate.resources)) {
    return false;
  }
  return !!candidate.resources || !!candidate.multiDiffSource;
}
function $$K(editor) {
  if ($dL(editor)) {
    return false;
  }
  if ($9K(editor)) {
    return false;
  }
  const candidate = editor;
  return candidate?.primary !== void 0 && candidate.secondary !== void 0;
}
function $aL(editor) {
  if ($dL(editor)) {
    return false;
  }
  const candidate = editor;
  return URI.isUri(candidate?.base?.resource) && URI.isUri(candidate?.input1?.resource) && URI.isUri(candidate?.input2?.resource) && URI.isUri(candidate?.result?.resource);
}
var Verbosity;
(function(Verbosity2) {
  Verbosity2[Verbosity2["SHORT"] = 0] = "SHORT";
  Verbosity2[Verbosity2["MEDIUM"] = 1] = "MEDIUM";
  Verbosity2[Verbosity2["LONG"] = 2] = "LONG";
})(Verbosity || (Verbosity = {}));
var SaveReason;
(function(SaveReason2) {
  SaveReason2[SaveReason2["EXPLICIT"] = 1] = "EXPLICIT";
  SaveReason2[SaveReason2["AUTO"] = 2] = "AUTO";
  SaveReason2[SaveReason2["FOCUS_CHANGE"] = 3] = "FOCUS_CHANGE";
  SaveReason2[SaveReason2["WINDOW_CHANGE"] = 4] = "WINDOW_CHANGE";
})(SaveReason || (SaveReason = {}));
var SaveSourceFactory = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  /**
   * Registers a `SaveSource` with an identifier and label
   * to the registry so that it can be used in save operations.
   */
  registerSource(id2, label) {
    let sourceDescriptor = this.a.get(id2);
    if (!sourceDescriptor) {
      sourceDescriptor = { source: id2, label };
      this.a.set(id2, sourceDescriptor);
    }
    return sourceDescriptor.source;
  }
  getSourceLabel(source) {
    return this.a.get(source)?.label ?? source;
  }
};
var $bL = new SaveSourceFactory();
var EditorInputCapabilities;
(function(EditorInputCapabilities2) {
  EditorInputCapabilities2[EditorInputCapabilities2["None"] = 0] = "None";
  EditorInputCapabilities2[EditorInputCapabilities2["Readonly"] = 2] = "Readonly";
  EditorInputCapabilities2[EditorInputCapabilities2["Untitled"] = 4] = "Untitled";
  EditorInputCapabilities2[EditorInputCapabilities2["Singleton"] = 8] = "Singleton";
  EditorInputCapabilities2[EditorInputCapabilities2["RequiresTrust"] = 16] = "RequiresTrust";
  EditorInputCapabilities2[EditorInputCapabilities2["CanSplitInGroup"] = 32] = "CanSplitInGroup";
  EditorInputCapabilities2[EditorInputCapabilities2["ForceDescription"] = 64] = "ForceDescription";
  EditorInputCapabilities2[EditorInputCapabilities2["CanDropIntoEditor"] = 128] = "CanDropIntoEditor";
  EditorInputCapabilities2[EditorInputCapabilities2["MultipleEditors"] = 256] = "MultipleEditors";
  EditorInputCapabilities2[EditorInputCapabilities2["Scratchpad"] = 512] = "Scratchpad";
})(EditorInputCapabilities || (EditorInputCapabilities = {}));
var $cL = class extends $3c {
};
function $dL(editor) {
  return editor instanceof $cL;
}
function isEditorInputWithPreferredResource(editor) {
  const candidate = editor;
  return URI.isUri(candidate?.preferredResource);
}
function $eL(editor) {
  const candidate = editor;
  return $dL(candidate?.primary) && $dL(candidate?.secondary);
}
function $fL(editor) {
  const candidate = editor;
  return $dL(candidate?.modified) && $dL(candidate?.original);
}
var EditorCloseContext;
(function(EditorCloseContext2) {
  EditorCloseContext2[EditorCloseContext2["UNKNOWN"] = 0] = "UNKNOWN";
  EditorCloseContext2[EditorCloseContext2["REPLACE"] = 1] = "REPLACE";
  EditorCloseContext2[EditorCloseContext2["MOVE"] = 2] = "MOVE";
  EditorCloseContext2[EditorCloseContext2["UNPIN"] = 3] = "UNPIN";
})(EditorCloseContext || (EditorCloseContext = {}));
var GroupModelChangeKind;
(function(GroupModelChangeKind2) {
  GroupModelChangeKind2[GroupModelChangeKind2["GROUP_ACTIVE"] = 0] = "GROUP_ACTIVE";
  GroupModelChangeKind2[GroupModelChangeKind2["GROUP_INDEX"] = 1] = "GROUP_INDEX";
  GroupModelChangeKind2[GroupModelChangeKind2["GROUP_LABEL"] = 2] = "GROUP_LABEL";
  GroupModelChangeKind2[GroupModelChangeKind2["GROUP_LOCKED"] = 3] = "GROUP_LOCKED";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITORS_SELECTION"] = 4] = "EDITORS_SELECTION";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_OPEN"] = 5] = "EDITOR_OPEN";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_CLOSE"] = 6] = "EDITOR_CLOSE";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_MOVE"] = 7] = "EDITOR_MOVE";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_ACTIVE"] = 8] = "EDITOR_ACTIVE";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_LABEL"] = 9] = "EDITOR_LABEL";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_CAPABILITIES"] = 10] = "EDITOR_CAPABILITIES";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_PIN"] = 11] = "EDITOR_PIN";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_TRANSIENT"] = 12] = "EDITOR_TRANSIENT";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_STICKY"] = 13] = "EDITOR_STICKY";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_DIRTY"] = 14] = "EDITOR_DIRTY";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_WILL_DISPOSE"] = 15] = "EDITOR_WILL_DISPOSE";
})(GroupModelChangeKind || (GroupModelChangeKind = {}));
var SideBySideEditor;
(function(SideBySideEditor2) {
  SideBySideEditor2[SideBySideEditor2["PRIMARY"] = 1] = "PRIMARY";
  SideBySideEditor2[SideBySideEditor2["SECONDARY"] = 2] = "SECONDARY";
  SideBySideEditor2[SideBySideEditor2["BOTH"] = 3] = "BOTH";
  SideBySideEditor2[SideBySideEditor2["ANY"] = 4] = "ANY";
})(SideBySideEditor || (SideBySideEditor = {}));
var EditorResourceAccessorImpl = class {
  getOriginalUri(editor, options2) {
    if (!editor) {
      return void 0;
    }
    if ($aL(editor)) {
      return $mL.getOriginalUri(editor.result, options2);
    }
    if (options2?.supportSideBySide) {
      const { primary, secondary } = this.a(editor);
      if (primary && secondary) {
        if (options2?.supportSideBySide === SideBySideEditor.BOTH) {
          return {
            primary: this.getOriginalUri(primary, { filterByScheme: options2.filterByScheme }),
            secondary: this.getOriginalUri(secondary, { filterByScheme: options2.filterByScheme })
          };
        } else if (options2?.supportSideBySide === SideBySideEditor.ANY) {
          return this.getOriginalUri(primary, { filterByScheme: options2.filterByScheme }) ?? this.getOriginalUri(secondary, { filterByScheme: options2.filterByScheme });
        }
        editor = options2.supportSideBySide === SideBySideEditor.PRIMARY ? primary : secondary;
      }
    }
    if ($9K(editor) || $0K(editor) || $$K(editor) || $aL(editor)) {
      return void 0;
    }
    const originalResource = isEditorInputWithPreferredResource(editor) ? editor.preferredResource : editor.resource;
    if (!originalResource || !options2 || !options2.filterByScheme) {
      return originalResource;
    }
    return this.b(originalResource, options2.filterByScheme);
  }
  a(editor) {
    if ($eL(editor) || $$K(editor)) {
      return { primary: editor.primary, secondary: editor.secondary };
    }
    if ($fL(editor) || $9K(editor)) {
      return { primary: editor.modified, secondary: editor.original };
    }
    return { primary: void 0, secondary: void 0 };
  }
  getCanonicalUri(editor, options2) {
    if (!editor) {
      return void 0;
    }
    if ($aL(editor)) {
      return $mL.getCanonicalUri(editor.result, options2);
    }
    if (options2?.supportSideBySide) {
      const { primary, secondary } = this.a(editor);
      if (primary && secondary) {
        if (options2?.supportSideBySide === SideBySideEditor.BOTH) {
          return {
            primary: this.getCanonicalUri(primary, { filterByScheme: options2.filterByScheme }),
            secondary: this.getCanonicalUri(secondary, { filterByScheme: options2.filterByScheme })
          };
        } else if (options2?.supportSideBySide === SideBySideEditor.ANY) {
          return this.getCanonicalUri(primary, { filterByScheme: options2.filterByScheme }) ?? this.getCanonicalUri(secondary, { filterByScheme: options2.filterByScheme });
        }
        editor = options2.supportSideBySide === SideBySideEditor.PRIMARY ? primary : secondary;
      }
    }
    if ($9K(editor) || $0K(editor) || $$K(editor) || $aL(editor)) {
      return void 0;
    }
    const canonicalResource = editor.resource;
    if (!canonicalResource || !options2 || !options2.filterByScheme) {
      return canonicalResource;
    }
    return this.b(canonicalResource, options2.filterByScheme);
  }
  b(resource, filter) {
    if (Array.isArray(filter)) {
      if (filter.some((scheme) => resource.scheme === scheme)) {
        return resource;
      }
    } else {
      if (filter === resource.scheme) {
        return resource;
      }
    }
    return void 0;
  }
};
var EditorCloseMethod;
(function(EditorCloseMethod2) {
  EditorCloseMethod2[EditorCloseMethod2["UNKNOWN"] = 0] = "UNKNOWN";
  EditorCloseMethod2[EditorCloseMethod2["KEYBOARD"] = 1] = "KEYBOARD";
  EditorCloseMethod2[EditorCloseMethod2["MOUSE"] = 2] = "MOUSE";
})(EditorCloseMethod || (EditorCloseMethod = {}));
var $mL = new EditorResourceAccessorImpl();
var CloseDirection;
(function(CloseDirection2) {
  CloseDirection2[CloseDirection2["LEFT"] = 0] = "LEFT";
  CloseDirection2[CloseDirection2["RIGHT"] = 1] = "RIGHT";
})(CloseDirection || (CloseDirection = {}));
var EditorFactoryRegistry = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
  }
  start(accessor) {
    const instantiationService = this.a = accessor.get($Pk);
    for (const [key, ctor] of this.c) {
      this.e(key, ctor, instantiationService);
    }
    this.c.clear();
  }
  e(editorTypeId, ctor, instantiationService) {
    const instance = instantiationService.createInstance(ctor);
    this.d.set(editorTypeId, instance);
  }
  registerFileEditorFactory(factory) {
    if (this.b) {
      throw new Error("Can only register one file editor factory.");
    }
    this.b = factory;
  }
  getFileEditorFactory() {
    return $Kg(this.b);
  }
  registerEditorSerializer(editorTypeId, ctor) {
    if (this.c.has(editorTypeId) || this.d.has(editorTypeId)) {
      throw new Error(`A editor serializer with type ID '${editorTypeId}' was already registered.`);
    }
    if (!this.a) {
      this.c.set(editorTypeId, ctor);
    } else {
      this.e(editorTypeId, ctor, this.a);
    }
    return $1c(() => {
      this.c.delete(editorTypeId);
      this.d.delete(editorTypeId);
    });
  }
  getEditorSerializer(arg1) {
    return this.d.get(typeof arg1 === "string" ? arg1 : arg1.typeId);
  }
};
$Wn.add($ZK.EditorFactory, new EditorFactoryRegistry());
var EditorsOrder;
(function(EditorsOrder2) {
  EditorsOrder2[EditorsOrder2["MOST_RECENTLY_ACTIVE"] = 0] = "MOST_RECENTLY_ACTIVE";
  EditorsOrder2[EditorsOrder2["SEQUENTIAL"] = 1] = "SEQUENTIAL";
})(EditorsOrder || (EditorsOrder = {}));

// out-build/vs/base/common/observableInternal/debugName.js
var $dd = class {
  constructor(owner, debugNameSource, referenceFn) {
    this.owner = owner;
    this.debugNameSource = debugNameSource;
    this.referenceFn = referenceFn;
  }
  getDebugName(target) {
    return $ed(target, this);
  }
};
var countPerName = /* @__PURE__ */ new Map();
var cachedDebugName = /* @__PURE__ */ new WeakMap();
function $ed(target, data) {
  const cached = cachedDebugName.get(target);
  if (cached) {
    return cached;
  }
  const dbgName = computeDebugName(target, data);
  if (dbgName) {
    let count = countPerName.get(dbgName) ?? 0;
    count++;
    countPerName.set(dbgName, count);
    const result = count === 1 ? dbgName : `${dbgName}#${count}`;
    cachedDebugName.set(target, result);
    return result;
  }
  return void 0;
}
function computeDebugName(self2, data) {
  const cached = cachedDebugName.get(self2);
  if (cached) {
    return cached;
  }
  const ownerStr = data.owner ? formatOwner(data.owner) + `.` : "";
  let result;
  const debugNameSource = data.debugNameSource;
  if (debugNameSource !== void 0) {
    if (typeof debugNameSource === "function") {
      result = debugNameSource();
      if (result !== void 0) {
        return ownerStr + result;
      }
    } else {
      return ownerStr + debugNameSource;
    }
  }
  const referenceFn = data.referenceFn;
  if (referenceFn !== void 0) {
    result = $fd(referenceFn);
    if (result !== void 0) {
      return ownerStr + result;
    }
  }
  if (data.owner !== void 0) {
    const key = findKey(data.owner, self2);
    if (key !== void 0) {
      return ownerStr + key;
    }
  }
  return void 0;
}
function findKey(obj, value) {
  for (const key in obj) {
    if (obj[key] === value) {
      return key;
    }
  }
  return void 0;
}
var countPerClassName = /* @__PURE__ */ new Map();
var ownerId = /* @__PURE__ */ new WeakMap();
function formatOwner(owner) {
  const id2 = ownerId.get(owner);
  if (id2) {
    return id2;
  }
  const className = getClassName(owner);
  let count = countPerClassName.get(className) ?? 0;
  count++;
  countPerClassName.set(className, count);
  const result = count === 1 ? className : `${className}#${count}`;
  ownerId.set(owner, result);
  return result;
}
function getClassName(obj) {
  const ctor = obj.constructor;
  if (ctor) {
    return ctor.name;
  }
  return "Object";
}
function $fd(fn) {
  const fnSrc = fn.toString();
  const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//;
  const match = regexp.exec(fnSrc);
  const result = match ? match[1] : void 0;
  return result?.trim();
}

// out-build/vs/base/common/equals.js
var $md = (a, b) => a === b;
function $rd(a, b) {
  if (a === b) {
    return true;
  }
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return false;
    }
    for (let i = 0; i < a.length; i++) {
      if (!$rd(a[i], b[i])) {
        return false;
      }
    }
    return true;
  }
  if (a && typeof a === "object" && b && typeof b === "object") {
    if (Object.getPrototypeOf(a) === Object.prototype && Object.getPrototypeOf(b) === Object.prototype) {
      const aObj = a;
      const bObj = b;
      const keysA = Object.keys(aObj);
      const keysB = Object.keys(bObj);
      const keysBSet = new Set(keysB);
      if (keysA.length !== keysB.length) {
        return false;
      }
      for (const key of keysA) {
        if (!keysBSet.has(key)) {
          return false;
        }
        if (!$rd(aObj[key], bObj[key])) {
          return false;
        }
      }
      return true;
    }
  }
  return false;
}

// out-build/vs/base/common/observableInternal/logging.js
var globalObservableLogger;
function $Yd(logger) {
  globalObservableLogger = logger;
}
function $Zd() {
  return globalObservableLogger;
}
var $1d = class {
  constructor() {
    this.a = 0;
    this.d = /* @__PURE__ */ new WeakMap();
  }
  b(text) {
    return consoleTextToArgs([
      normalText(repeat("|  ", this.a)),
      text
    ]);
  }
  c(info) {
    if (!info.hadValue) {
      return [
        normalText(` `),
        styled(formatValue(info.newValue, 60), {
          color: "green"
        }),
        normalText(` (initial)`)
      ];
    }
    return info.didChange ? [
      normalText(` `),
      styled(formatValue(info.oldValue, 70), {
        color: "red",
        strikeThrough: true
      }),
      normalText(` `),
      styled(formatValue(info.newValue, 60), {
        color: "green"
      })
    ] : [normalText(` (unchanged)`)];
  }
  handleObservableChanged(observable, info) {
    console.log(...this.b([
      formatKind("observable value changed"),
      styled(observable.debugName, { color: "BlueViolet" }),
      ...this.c(info)
    ]));
  }
  formatChanges(changes) {
    if (changes.size === 0) {
      return void 0;
    }
    return styled(" (changed deps: " + [...changes].map((o) => o.debugName).join(", ") + ")", { color: "gray" });
  }
  handleDerivedCreated(derived) {
    const existingHandleChange = derived.handleChange;
    this.d.set(derived, /* @__PURE__ */ new Set());
    derived.handleChange = (observable, change) => {
      this.d.get(derived).add(observable);
      return existingHandleChange.apply(derived, [observable, change]);
    };
  }
  handleDerivedRecomputed(derived, info) {
    const changedObservables = this.d.get(derived);
    console.log(...this.b([
      formatKind("derived recomputed"),
      styled(derived.debugName, { color: "BlueViolet" }),
      ...this.c(info),
      this.formatChanges(changedObservables),
      { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] }
    ]));
    changedObservables.clear();
  }
  handleFromEventObservableTriggered(observable, info) {
    console.log(...this.b([
      formatKind("observable from event triggered"),
      styled(observable.debugName, { color: "BlueViolet" }),
      ...this.c(info),
      { data: [{ fn: observable._getValue }] }
    ]));
  }
  handleAutorunCreated(autorun) {
    const existingHandleChange = autorun.handleChange;
    this.d.set(autorun, /* @__PURE__ */ new Set());
    autorun.handleChange = (observable, change) => {
      this.d.get(autorun).add(observable);
      return existingHandleChange.apply(autorun, [observable, change]);
    };
  }
  handleAutorunTriggered(autorun) {
    const changedObservables = this.d.get(autorun);
    console.log(...this.b([
      formatKind("autorun"),
      styled(autorun.debugName, { color: "BlueViolet" }),
      this.formatChanges(changedObservables),
      { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] }
    ]));
    changedObservables.clear();
    this.a++;
  }
  handleAutorunFinished(autorun) {
    this.a--;
  }
  handleBeginTransaction(transaction) {
    let transactionName = transaction.getDebugName();
    if (transactionName === void 0) {
      transactionName = "";
    }
    console.log(...this.b([
      formatKind("transaction"),
      styled(transactionName, { color: "BlueViolet" }),
      { data: [{ fn: transaction._fn }] }
    ]));
    this.a++;
  }
  handleEndTransaction() {
    this.a--;
  }
};
function consoleTextToArgs(text) {
  const styles = new Array();
  const data = [];
  let firstArg = "";
  function process2(t) {
    if ("length" in t) {
      for (const item of t) {
        if (item) {
          process2(item);
        }
      }
    } else if ("text" in t) {
      firstArg += `%c${t.text}`;
      styles.push(t.style);
      if (t.data) {
        data.push(...t.data);
      }
    } else if ("data" in t) {
      data.push(...t.data);
    }
  }
  process2(text);
  const result = [firstArg, ...styles];
  result.push(...data);
  return result;
}
function normalText(text) {
  return styled(text, { color: "black" });
}
function formatKind(kind) {
  return styled(padStr(`${kind}: `, 10), { color: "black", bold: true });
}
function styled(text, options2 = {
  color: "black"
}) {
  function objToCss(styleObj) {
    return Object.entries(styleObj).reduce((styleString, [propName, propValue]) => {
      return `${styleString}${propName}:${propValue};`;
    }, "");
  }
  const style = {
    color: options2.color
  };
  if (options2.strikeThrough) {
    style["text-decoration"] = "line-through";
  }
  if (options2.bold) {
    style["font-weight"] = "bold";
  }
  return {
    text,
    style: objToCss(style)
  };
}
function formatValue(value, availableLen) {
  switch (typeof value) {
    case "number":
      return "" + value;
    case "string":
      if (value.length + 2 <= availableLen) {
        return `"${value}"`;
      }
      return `"${value.substr(0, availableLen - 7)}"+...`;
    case "boolean":
      return value ? "true" : "false";
    case "undefined":
      return "undefined";
    case "object":
      if (value === null) {
        return "null";
      }
      if (Array.isArray(value)) {
        return formatArray(value, availableLen);
      }
      return formatObject(value, availableLen);
    case "symbol":
      return value.toString();
    case "function":
      return `[[Function${value.name ? " " + value.name : ""}]]`;
    default:
      return "" + value;
  }
}
function formatArray(value, availableLen) {
  let result = "[ ";
  let first = true;
  for (const val of value) {
    if (!first) {
      result += ", ";
    }
    if (result.length - 5 > availableLen) {
      result += "...";
      break;
    }
    first = false;
    result += `${formatValue(val, availableLen - result.length)}`;
  }
  result += " ]";
  return result;
}
function formatObject(value, availableLen) {
  let result = "{ ";
  let first = true;
  for (const [key, val] of Object.entries(value)) {
    if (!first) {
      result += ", ";
    }
    if (result.length - 5 > availableLen) {
      result += "...";
      break;
    }
    first = false;
    result += `${key}: ${formatValue(val, availableLen - result.length)}`;
  }
  result += " }";
  return result;
}
function repeat(str, count) {
  let result = "";
  for (let i = 1; i <= count; i++) {
    result += str;
  }
  return result;
}
function padStr(str, length) {
  while (str.length < length) {
    str += " ";
  }
  return str;
}

// out-build/vs/base/common/observableInternal/base.js
var _recomputeInitiallyAndOnChange;
function $0d(recomputeInitiallyAndOnChange) {
  _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange;
}
var _keepObserved;
function $$d(keepObserved) {
  _keepObserved = keepObserved;
}
var _derived;
function $_d(derived) {
  _derived = derived;
}
var $ae = class {
  get TChange() {
    return null;
  }
  reportChanges() {
    this.get();
  }
  /** @sealed */
  read(reader) {
    if (reader) {
      return reader.readObservable(this);
    } else {
      return this.get();
    }
  }
  map(fnOrOwner, fnOrUndefined) {
    const owner = fnOrUndefined === void 0 ? void 0 : fnOrOwner;
    const fn = fnOrUndefined === void 0 ? fnOrOwner : fnOrUndefined;
    return _derived({
      owner,
      debugName: () => {
        const name = $fd(fn);
        if (name !== void 0) {
          return name;
        }
        const regexp = /^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/;
        const match = regexp.exec(fn.toString());
        if (match) {
          return `${this.debugName}.${match[2]}`;
        }
        if (!owner) {
          return `${this.debugName} (mapped)`;
        }
        return void 0;
      },
      debugReferenceFn: fn
    }, (reader) => fn(this.read(reader), reader));
  }
  /**
   * @sealed
   * Converts an observable of an observable value into a direct observable of the value.
  */
  flatten() {
    return _derived({
      owner: void 0,
      debugName: () => `${this.debugName} (flattened)`
    }, (reader) => this.read(reader).read(reader));
  }
  recomputeInitiallyAndOnChange(store, handleValue) {
    store.add(_recomputeInitiallyAndOnChange(this, handleValue));
    return this;
  }
  /**
   * Ensures that this observable is observed. This keeps the cache alive.
   * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get).
   * Use `recomputeInitiallyAndOnChange` for eager evaluation.
   */
  keepObserved(store) {
    store.add(_keepObserved(this));
    return this;
  }
  get a() {
    return this.get();
  }
};
var $be = class extends $ae {
  constructor() {
    super(...arguments);
    this.b = /* @__PURE__ */ new Set();
  }
  addObserver(observer) {
    const len = this.b.size;
    this.b.add(observer);
    if (len === 0) {
      this.c();
    }
  }
  removeObserver(observer) {
    const deleted = this.b.delete(observer);
    if (deleted && this.b.size === 0) {
      this.f();
    }
  }
  c() {
  }
  f() {
  }
};
function $ce(fn, getDebugName) {
  const tx = new $ge(fn, getDebugName);
  try {
    fn(tx);
  } finally {
    tx.finish();
  }
}
function $fe(tx, fn, getDebugName) {
  if (!tx) {
    $ce(fn, getDebugName);
  } else {
    fn(tx);
  }
}
var $ge = class {
  constructor(_fn, b) {
    this._fn = _fn;
    this.b = b;
    this.a = [];
    $Zd()?.handleBeginTransaction(this);
  }
  getDebugName() {
    if (this.b) {
      return this.b();
    }
    return $fd(this._fn);
  }
  updateObserver(observer, observable) {
    this.a.push({ observer, observable });
    observer.beginUpdate(observable);
  }
  finish() {
    const updatingObservers = this.a;
    for (let i = 0; i < updatingObservers.length; i++) {
      const { observer, observable } = updatingObservers[i];
      observer.endUpdate(observable);
    }
    this.a = null;
    $Zd()?.handleEndTransaction();
  }
};
function $he(nameOrOwner, initialValue) {
  let debugNameData;
  if (typeof nameOrOwner === "string") {
    debugNameData = new $dd(void 0, nameOrOwner, void 0);
  } else {
    debugNameData = new $dd(nameOrOwner, void 0, void 0);
  }
  return new $ie(debugNameData, initialValue, $md);
}
var $ie = class extends $be {
  get debugName() {
    return this.e.getDebugName(this) ?? "ObservableValue";
  }
  constructor(e, initialValue, g) {
    super();
    this.e = e;
    this.g = g;
    this.d = initialValue;
  }
  get() {
    return this.d;
  }
  set(value, tx, change) {
    if (change === void 0 && this.g(this.d, value)) {
      return;
    }
    let _tx;
    if (!tx) {
      tx = _tx = new $ge(() => {
      }, () => `Setting ${this.debugName}`);
    }
    try {
      const oldValue = this.d;
      this.h(value);
      $Zd()?.handleObservableChanged(this, { oldValue, newValue: value, change, didChange: true, hadValue: true });
      for (const observer of this.b) {
        tx.updateObserver(observer, this);
        observer.handleChange(this, change);
      }
    } finally {
      if (_tx) {
        _tx.finish();
      }
    }
  }
  toString() {
    return `${this.debugName}: ${this.d}`;
  }
  h(newValue) {
    this.d = newValue;
  }
};

// out-build/vs/base/common/observableInternal/autorun.js
function $td(fn) {
  return new $Ad(new $dd(void 0, void 0, fn), fn, void 0, void 0);
}
var AutorunState;
(function(AutorunState2) {
  AutorunState2[AutorunState2["dependenciesMightHaveChanged"] = 1] = "dependenciesMightHaveChanged";
  AutorunState2[AutorunState2["stale"] = 2] = "stale";
  AutorunState2[AutorunState2["upToDate"] = 3] = "upToDate";
})(AutorunState || (AutorunState = {}));
var $Ad = class {
  get debugName() {
    return this._debugNameData.getDebugName(this) ?? "(anonymous)";
  }
  constructor(_debugNameData, _runFn, i, j) {
    this._debugNameData = _debugNameData;
    this._runFn = _runFn;
    this.i = i;
    this.j = j;
    this.a = 2;
    this.b = 0;
    this.c = false;
    this.f = /* @__PURE__ */ new Set();
    this.g = /* @__PURE__ */ new Set();
    this.l = false;
    this.h = this.i?.();
    $Zd()?.handleAutorunCreated(this);
    this.k();
    $Tc(this);
  }
  dispose() {
    this.c = true;
    for (const o of this.f) {
      o.removeObserver(this);
    }
    this.f.clear();
    $Uc(this);
  }
  k() {
    if (this.a === 3) {
      return;
    }
    const emptySet = this.g;
    this.g = this.f;
    this.f = emptySet;
    this.a = 3;
    const isDisposed = this.c;
    try {
      if (!isDisposed) {
        $Zd()?.handleAutorunTriggered(this);
        const changeSummary = this.h;
        try {
          this.h = this.i?.();
          this.l = true;
          this._runFn(this, changeSummary);
        } catch (e) {
          $fb(e);
        } finally {
          this.l = false;
        }
      }
    } finally {
      if (!isDisposed) {
        $Zd()?.handleAutorunFinished(this);
      }
      for (const o of this.g) {
        o.removeObserver(this);
      }
      this.g.clear();
    }
  }
  toString() {
    return `Autorun<${this.debugName}>`;
  }
  // IObserver implementation
  beginUpdate() {
    if (this.a === 3) {
      this.a = 1;
    }
    this.b++;
  }
  endUpdate() {
    try {
      if (this.b === 1) {
        do {
          if (this.a === 1) {
            this.a = 3;
            for (const d of this.f) {
              d.reportChanges();
              if (this.a === 2) {
                break;
              }
            }
          }
          this.k();
        } while (this.a !== 3);
      }
    } finally {
      this.b--;
    }
    $kd(() => this.b >= 0);
  }
  handlePossibleChange(observable) {
    if (this.a === 3 && this.f.has(observable) && !this.g.has(observable)) {
      this.a = 1;
    }
  }
  handleChange(observable, change) {
    if (this.f.has(observable) && !this.g.has(observable)) {
      try {
        const shouldReact = this.j ? this.j({
          changedObservable: observable,
          change,
          didChange: (o) => o === observable
        }, this.h) : true;
        if (shouldReact) {
          this.a = 2;
        }
      } catch (e) {
        $fb(e);
      }
    }
  }
  readObservable(observable) {
    if (!this.l) {
      throw new $vb("The reader object cannot be used outside its compute function!");
    }
    if (this.c) {
      return observable.get();
    }
    observable.addObserver(this);
    const value = observable.get();
    this.f.add(observable);
    this.g.delete(observable);
    return value;
  }
};
(function($td2) {
  $td2.Observer = $Ad;
})($td || ($td = {}));

// out-build/vs/base/common/observableInternal/derived.js
function $4d(options2, computeFn) {
  return new $8d(new $dd(options2.owner, options2.debugName, options2.debugReferenceFn), computeFn, void 0, void 0, options2.onLastObserverRemoved, options2.equalsFn ?? $md);
}
$_d($4d);
var DerivedState;
(function(DerivedState2) {
  DerivedState2[DerivedState2["initial"] = 0] = "initial";
  DerivedState2[DerivedState2["dependenciesMightHaveChanged"] = 1] = "dependenciesMightHaveChanged";
  DerivedState2[DerivedState2["stale"] = 2] = "stale";
  DerivedState2[DerivedState2["upToDate"] = 3] = "upToDate";
})(DerivedState || (DerivedState = {}));
var $8d = class extends $be {
  get debugName() {
    return this._debugNameData.getDebugName(this) ?? "(anonymous)";
  }
  constructor(_debugNameData, _computeFn, q, s, t = void 0, u) {
    super();
    this._debugNameData = _debugNameData;
    this._computeFn = _computeFn;
    this.q = q;
    this.s = s;
    this.t = t;
    this.u = u;
    this.g = 0;
    this.h = void 0;
    this.j = 0;
    this.k = /* @__PURE__ */ new Set();
    this.l = /* @__PURE__ */ new Set();
    this.m = void 0;
    this.n = false;
    this.p = false;
    this.x = false;
    this.m = this.q?.();
    $Zd()?.handleDerivedCreated(this);
  }
  f() {
    this.g = 0;
    this.h = void 0;
    for (const d of this.k) {
      d.removeObserver(this);
    }
    this.k.clear();
    this.t?.();
  }
  get() {
    if (this.p) {
      throw new $vb("Cyclic deriveds are not supported yet!");
    }
    if (this.b.size === 0) {
      let result;
      try {
        this.x = true;
        result = this._computeFn(this, this.q?.());
      } finally {
        this.x = false;
      }
      this.f();
      return result;
    } else {
      do {
        if (this.g === 1) {
          for (const d of this.k) {
            d.reportChanges();
            if (this.g === 2) {
              break;
            }
          }
        }
        if (this.g === 1) {
          this.g = 3;
        }
        this.w();
      } while (this.g !== 3);
      return this.h;
    }
  }
  w() {
    if (this.g === 3) {
      return;
    }
    const emptySet = this.l;
    this.l = this.k;
    this.k = emptySet;
    const hadValue = this.g !== 0;
    const oldValue = this.h;
    this.g = 3;
    let didChange = false;
    this.p = false;
    try {
      const changeSummary = this.m;
      this.m = this.q?.();
      try {
        this.x = true;
        this.h = this._computeFn(this, changeSummary);
      } finally {
        this.x = false;
        for (const o of this.l) {
          o.removeObserver(this);
        }
        this.l.clear();
      }
      didChange = hadValue && !this.u(oldValue, this.h);
      $Zd()?.handleDerivedRecomputed(this, {
        oldValue,
        newValue: this.h,
        change: void 0,
        didChange,
        hadValue
      });
    } catch (e) {
      $fb(e);
    }
    this.p = false;
    if (didChange) {
      for (const r of this.b) {
        r.handleChange(this, void 0);
      }
    }
  }
  toString() {
    return `LazyDerived<${this.debugName}>`;
  }
  // IObserver Implementation
  beginUpdate(_observable) {
    if (this.n) {
      throw new $vb("Cyclic deriveds are not supported yet!");
    }
    this.j++;
    this.n = true;
    try {
      const propagateBeginUpdate = this.j === 1;
      if (this.g === 3) {
        this.g = 1;
        if (!propagateBeginUpdate) {
          for (const r of this.b) {
            r.handlePossibleChange(this);
          }
        }
      }
      if (propagateBeginUpdate) {
        for (const r of this.b) {
          r.beginUpdate(this);
        }
      }
    } finally {
      this.n = false;
    }
  }
  endUpdate(_observable) {
    this.j--;
    if (this.j === 0) {
      const observers = [...this.b];
      for (const r of observers) {
        r.endUpdate(this);
      }
    }
    $kd(() => this.j >= 0);
  }
  handlePossibleChange(observable) {
    if (this.g === 3 && this.k.has(observable) && !this.l.has(observable)) {
      this.g = 1;
      for (const r of this.b) {
        r.handlePossibleChange(this);
      }
    }
  }
  handleChange(observable, change) {
    if (this.k.has(observable) && !this.l.has(observable)) {
      let shouldReact = false;
      try {
        shouldReact = this.s ? this.s({
          changedObservable: observable,
          change,
          didChange: (o) => o === observable
        }, this.m) : true;
      } catch (e) {
        $fb(e);
      }
      const wasUpToDate = this.g === 3;
      if (shouldReact && (this.g === 1 || wasUpToDate)) {
        this.g = 2;
        if (wasUpToDate) {
          for (const r of this.b) {
            r.handlePossibleChange(this);
          }
        }
      }
    }
  }
  readObservable(observable) {
    if (!this.x) {
      throw new $vb("The reader object cannot be used outside its compute function!");
    }
    observable.addObserver(this);
    const value = observable.get();
    this.k.add(observable);
    this.l.delete(observable);
    return value;
  }
  addObserver(observer) {
    const shouldCallBeginUpdate = !this.b.has(observer) && this.j > 0;
    super.addObserver(observer);
    if (shouldCallBeginUpdate) {
      observer.beginUpdate(this);
    }
  }
  removeObserver(observer) {
    const shouldCallEndUpdate = this.b.has(observer) && this.j > 0;
    super.removeObserver(observer);
    if (shouldCallEndUpdate) {
      observer.endUpdate(this);
    }
  }
};

// out-build/vs/base/common/observableInternal/utils.js
function $Dd(...args2) {
  let owner;
  let event;
  let getValue;
  if (args2.length === 3) {
    [owner, event, getValue] = args2;
  } else {
    [event, getValue] = args2;
  }
  return new $Fd(new $dd(owner, void 0, getValue), event, getValue, () => $Fd.globalTransaction, $md);
}
var $Fd = class extends $be {
  constructor(k, l, _getValue, n, p) {
    super();
    this.k = k;
    this.l = l;
    this._getValue = _getValue;
    this.n = n;
    this.p = p;
    this.h = false;
    this.s = (args2) => {
      const newValue = this._getValue(args2);
      const oldValue = this.g;
      const didChange = !this.h || !this.p(oldValue, newValue);
      let didRunTransaction = false;
      if (didChange) {
        this.g = newValue;
        if (this.h) {
          didRunTransaction = true;
          $fe(this.n(), (tx) => {
            $Zd()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: void 0, didChange, hadValue: this.h });
            for (const o of this.b) {
              tx.updateObserver(o, this);
              o.handleChange(this, void 0);
            }
          }, () => {
            const name = this.q();
            return "Event fired" + (name ? `: ${name}` : "");
          });
        }
        this.h = true;
      }
      if (!didRunTransaction) {
        $Zd()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: void 0, didChange, hadValue: this.h });
      }
    };
  }
  q() {
    return this.k.getDebugName(this);
  }
  get debugName() {
    const name = this.q();
    return "From Event" + (name ? `: ${name}` : "");
  }
  c() {
    this.j = this.l(this.s);
  }
  f() {
    this.j.dispose();
    this.j = void 0;
    this.h = false;
    this.g = void 0;
  }
  get() {
    if (this.j) {
      if (!this.h) {
        this.s(void 0);
      }
      return this.g;
    } else {
      const value = this._getValue(void 0);
      return value;
    }
  }
};
(function($Dd2) {
  $Dd2.Observer = $Fd;
  function batchEventsGlobally(tx, fn) {
    let didSet = false;
    if ($Fd.globalTransaction === void 0) {
      $Fd.globalTransaction = tx;
      didSet = true;
    }
    try {
      fn();
    } finally {
      if (didSet) {
        $Fd.globalTransaction = void 0;
      }
    }
  }
  $Dd2.batchEventsGlobally = batchEventsGlobally;
})($Dd || ($Dd = {}));
function $Md(observable) {
  const o = new $Od(false, void 0);
  observable.addObserver(o);
  return $1c(() => {
    observable.removeObserver(o);
  });
}
$$d($Md);
function $Nd(observable, handleValue) {
  const o = new $Od(true, handleValue);
  observable.addObserver(o);
  if (handleValue) {
    handleValue(observable.get());
  } else {
    observable.reportChanges();
  }
  return $1c(() => {
    observable.removeObserver(o);
  });
}
$0d($Nd);
var $Od = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = 0;
  }
  beginUpdate(observable) {
    this.a++;
  }
  endUpdate(observable) {
    this.a--;
    if (this.a === 0 && this.b) {
      if (this.c) {
        this.c(observable.get());
      } else {
        observable.reportChanges();
      }
    }
  }
  handlePossibleChange(observable) {
  }
  handleChange(observable, change) {
  }
};

// out-build/vs/base/common/observableInternal/index.js
var enableLogging = false;
if (enableLogging) {
  $Yd(new $1d());
}

// out-build/vs/platform/remote/common/remoteHosts.js
function $9v(authority) {
  if (!authority) {
    return void 0;
  }
  const pos = authority.indexOf("+");
  if (pos < 0) {
    return authority;
  }
  return authority.substr(0, pos);
}

// out-build/vs/platform/extensions/common/extensions.js
var $4z = [
  "AI",
  "Azure",
  "Chat",
  "Data Science",
  "Debuggers",
  "Extension Packs",
  "Education",
  "Formatters",
  "Keymaps",
  "Language Packs",
  "Linters",
  "Machine Learning",
  "Notebooks",
  "Programming Languages",
  "SCM Providers",
  "Snippets",
  "Testing",
  "Themes",
  "Visualization",
  "Other"
];
var ExtensionType;
(function(ExtensionType2) {
  ExtensionType2[ExtensionType2["System"] = 0] = "System";
  ExtensionType2[ExtensionType2["User"] = 1] = "User";
})(ExtensionType || (ExtensionType = {}));
var TargetPlatform;
(function(TargetPlatform2) {
  TargetPlatform2["WIN32_X64"] = "win32-x64";
  TargetPlatform2["WIN32_ARM64"] = "win32-arm64";
  TargetPlatform2["LINUX_X64"] = "linux-x64";
  TargetPlatform2["LINUX_ARM64"] = "linux-arm64";
  TargetPlatform2["LINUX_ARMHF"] = "linux-armhf";
  TargetPlatform2["ALPINE_X64"] = "alpine-x64";
  TargetPlatform2["ALPINE_ARM64"] = "alpine-arm64";
  TargetPlatform2["DARWIN_X64"] = "darwin-x64";
  TargetPlatform2["DARWIN_ARM64"] = "darwin-arm64";
  TargetPlatform2["WEB"] = "web";
  TargetPlatform2["UNIVERSAL"] = "universal";
  TargetPlatform2["UNKNOWN"] = "unknown";
  TargetPlatform2["UNDEFINED"] = "undefined";
})(TargetPlatform || (TargetPlatform = {}));
var $5z = class {
  constructor(value) {
    this.value = value;
    this._lower = value.toLowerCase();
  }
  static equals(a, b) {
    if (typeof a === "undefined" || a === null) {
      return typeof b === "undefined" || b === null;
    }
    if (typeof b === "undefined" || b === null) {
      return false;
    }
    if (typeof a === "string" || typeof b === "string") {
      const aValue = typeof a === "string" ? a : a.value;
      const bValue = typeof b === "string" ? b : b.value;
      return $1f(aValue, bValue);
    }
    return a._lower === b._lower;
  }
  /**
   * Gives the value by which to index (for equality).
   */
  static toKey(id2) {
    if (typeof id2 === "string") {
      return id2.toLowerCase();
    }
    return id2._lower;
  }
};
var $6z = class {
  get size() {
    return this.c.size;
  }
  constructor(iterable) {
    this.c = /* @__PURE__ */ new Set();
    if (iterable) {
      for (const value of iterable) {
        this.add(value);
      }
    }
  }
  add(id2) {
    this.c.add($5z.toKey(id2));
  }
  delete(extensionId) {
    return this.c.delete($5z.toKey(extensionId));
  }
  has(id2) {
    return this.c.has($5z.toKey(id2));
  }
};
var $7z = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
  }
  clear() {
    this.c.clear();
  }
  delete(id2) {
    this.c.delete($5z.toKey(id2));
  }
  get(id2) {
    return this.c.get($5z.toKey(id2));
  }
  has(id2) {
    return this.c.has($5z.toKey(id2));
  }
  set(id2, value) {
    this.c.set($5z.toKey(id2), value);
  }
  values() {
    return this.c.values();
  }
  forEach(callbackfn) {
    this.c.forEach(callbackfn);
  }
  [Symbol.iterator]() {
    return this.c[Symbol.iterator]();
  }
};
var $bA = $Qk("IBuiltinExtensionsScannerService");

// out-build/vs/platform/product/common/productService.js
var $Vu = $Qk("productService");
var $Wu = "vscode://schemas/vscode-product";

// out-build/vs/platform/configuration/common/configuration.js
var $kl = $Qk("configurationService");
var ConfigurationTarget;
(function(ConfigurationTarget3) {
  ConfigurationTarget3[ConfigurationTarget3["APPLICATION"] = 1] = "APPLICATION";
  ConfigurationTarget3[ConfigurationTarget3["USER"] = 2] = "USER";
  ConfigurationTarget3[ConfigurationTarget3["USER_LOCAL"] = 3] = "USER_LOCAL";
  ConfigurationTarget3[ConfigurationTarget3["USER_REMOTE"] = 4] = "USER_REMOTE";
  ConfigurationTarget3[ConfigurationTarget3["WORKSPACE"] = 5] = "WORKSPACE";
  ConfigurationTarget3[ConfigurationTarget3["WORKSPACE_FOLDER"] = 6] = "WORKSPACE_FOLDER";
  ConfigurationTarget3[ConfigurationTarget3["DEFAULT"] = 7] = "DEFAULT";
  ConfigurationTarget3[ConfigurationTarget3["MEMORY"] = 8] = "MEMORY";
})(ConfigurationTarget || (ConfigurationTarget = {}));
function $pl(properties, conflictReporter) {
  const root = /* @__PURE__ */ Object.create(null);
  for (const key in properties) {
    $ql(root, key, properties[key], conflictReporter);
  }
  return root;
}
function $ql(settingsTreeRoot, key, value, conflictReporter) {
  const segments = key.split(".");
  const last = 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":
        if (obj === null) {
          conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join(".")} is null`);
          return;
        }
        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[last] = 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 $rl(valueTree, key) {
  const segments = key.split(".");
  doRemoveFromValueTree(valueTree, segments);
}
function doRemoveFromValueTree(valueTree, segments) {
  const first = segments.shift();
  if (segments.length === 0) {
    delete valueTree[first];
    return;
  }
  if (Object.keys(valueTree).indexOf(first) !== -1) {
    const value = valueTree[first];
    if (typeof value === "object" && !Array.isArray(value)) {
      doRemoveFromValueTree(value, segments);
      if (Object.keys(value).length === 0) {
        delete valueTree[first];
      }
    }
  }
}
function $sl(config, settingPath, defaultValue) {
  function accessSetting(config2, path2) {
    let current = config2;
    for (const component of path2) {
      if (typeof current !== "object" || current === null) {
        return void 0;
      }
      current = current[component];
    }
    return current;
  }
  const path = settingPath.split(".");
  const result = accessSetting(config, path);
  return typeof result === "undefined" ? defaultValue : result;
}
function $ul(settingKey) {
  return settingKey.replace(/[\[\]]/g, "");
}

// out-build/vs/base/common/jsonSchema.js
function $rn(schema) {
  let hasDups = false;
  const equalsByString = /* @__PURE__ */ new Map();
  const nodeToEquals = /* @__PURE__ */ new Map();
  const visitSchemas = (next) => {
    if (schema === next) {
      return true;
    }
    const val = JSON.stringify(next);
    if (val.length < 30) {
      return true;
    }
    const eq2 = equalsByString.get(val);
    if (!eq2) {
      const newEq = { schemas: [next] };
      equalsByString.set(val, newEq);
      nodeToEquals.set(next, newEq);
      return true;
    }
    eq2.schemas.push(next);
    nodeToEquals.set(next, eq2);
    hasDups = true;
    return false;
  };
  traverseNodes(schema, visitSchemas);
  equalsByString.clear();
  if (!hasDups) {
    return JSON.stringify(schema);
  }
  let defNodeName = "$defs";
  while (schema.hasOwnProperty(defNodeName)) {
    defNodeName += "_";
  }
  const definitions = [];
  function stringify2(root) {
    return JSON.stringify(root, (_key, value) => {
      if (value !== root) {
        const eq2 = nodeToEquals.get(value);
        if (eq2 && eq2.schemas.length > 1) {
          if (!eq2.id) {
            eq2.id = `_${definitions.length}`;
            definitions.push(eq2.schemas[0]);
          }
          return { $ref: `#/${defNodeName}/${eq2.id}` };
        }
      }
      return value;
    });
  }
  const str = stringify2(schema);
  const defStrings = [];
  for (let i = 0; i < definitions.length; i++) {
    defStrings.push(`"_${i}":${stringify2(definitions[i])}`);
  }
  if (defStrings.length) {
    return `${str.substring(0, str.length - 1)},"${defNodeName}":{${defStrings.join(",")}}}`;
  }
  return str;
}
function isObject(thing) {
  return typeof thing === "object" && thing !== null;
}
function traverseNodes(root, visit) {
  if (!root || typeof root !== "object") {
    return;
  }
  const collectEntries = (...entries) => {
    for (const entry of entries) {
      if (isObject(entry)) {
        toWalk.push(entry);
      }
    }
  };
  const collectMapEntries = (...maps) => {
    for (const map of maps) {
      if (isObject(map)) {
        for (const key in map) {
          const entry = map[key];
          if (isObject(entry)) {
            toWalk.push(entry);
          }
        }
      }
    }
  };
  const collectArrayEntries = (...arrays) => {
    for (const array of arrays) {
      if (Array.isArray(array)) {
        for (const entry of array) {
          if (isObject(entry)) {
            toWalk.push(entry);
          }
        }
      }
    }
  };
  const collectEntryOrArrayEntries = (items) => {
    if (Array.isArray(items)) {
      for (const entry of items) {
        if (isObject(entry)) {
          toWalk.push(entry);
        }
      }
    } else if (isObject(items)) {
      toWalk.push(items);
    }
  };
  const toWalk = [root];
  let next = toWalk.pop();
  while (next) {
    const visitChildern = visit(next);
    if (visitChildern) {
      collectEntries(next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else, next.unevaluatedItems, next.unevaluatedProperties);
      collectMapEntries(next.definitions, next.$defs, next.properties, next.patternProperties, next.dependencies, next.dependentSchemas);
      collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.prefixItems);
      collectEntryOrArrayEntries(next.items);
    }
    next = toWalk.pop();
  }
}

// out-build/vs/platform/jsonschemas/common/jsonContributionRegistry.js
var $Xn = {
  JSONContribution: "base.contributions.json"
};
function normalizeId(id2) {
  if (id2.length > 0 && id2.charAt(id2.length - 1) === "#") {
    return id2.substring(0, id2.length - 1);
  }
  return id2;
}
var JSONContributionRegistry = class {
  constructor() {
    this.b = new $ze();
    this.onDidChangeSchema = this.b.event;
    this.a = {};
  }
  registerSchema(uri, unresolvedSchemaContent) {
    this.a[normalizeId(uri)] = unresolvedSchemaContent;
    this.b.fire(uri);
  }
  notifySchemaChanged(uri) {
    this.b.fire(uri);
  }
  getSchemaContributions() {
    return {
      schemas: this.a
    };
  }
  getSchemaContent(uri) {
    const schema = this.a[uri];
    return schema ? $rn(schema) : void 0;
  }
  hasSchemaContent(uri) {
    return !!this.a[uri];
  }
};
var jsonContributionRegistry = new JSONContributionRegistry();
$Wn.add($Xn.JSONContribution, jsonContributionRegistry);

// out-build/vs/platform/configuration/common/configurationRegistry.js
var EditPresentationTypes;
(function(EditPresentationTypes2) {
  EditPresentationTypes2["Multiline"] = "multilineText";
  EditPresentationTypes2["Singleline"] = "singlelineText";
})(EditPresentationTypes || (EditPresentationTypes = {}));
var $Ht = {
  Configuration: "base.contributions.configuration"
};
var ConfigurationScope;
(function(ConfigurationScope2) {
  ConfigurationScope2[ConfigurationScope2["APPLICATION"] = 1] = "APPLICATION";
  ConfigurationScope2[ConfigurationScope2["MACHINE"] = 2] = "MACHINE";
  ConfigurationScope2[ConfigurationScope2["WINDOW"] = 3] = "WINDOW";
  ConfigurationScope2[ConfigurationScope2["RESOURCE"] = 4] = "RESOURCE";
  ConfigurationScope2[ConfigurationScope2["LANGUAGE_OVERRIDABLE"] = 5] = "LANGUAGE_OVERRIDABLE";
  ConfigurationScope2[ConfigurationScope2["MACHINE_OVERRIDABLE"] = 6] = "MACHINE_OVERRIDABLE";
})(ConfigurationScope || (ConfigurationScope = {}));
var $It = { properties: {}, patternProperties: {} };
var $Jt = { properties: {}, patternProperties: {} };
var $Kt = { properties: {}, patternProperties: {} };
var $Lt = { properties: {}, patternProperties: {} };
var $Mt = { properties: {}, patternProperties: {} };
var $Nt = { properties: {}, patternProperties: {} };
var $Ot = "vscode://schemas/settings/resourceLanguage";
var contributionRegistry = $Wn.as($Xn.JSONContribution);
var ConfigurationRegistry = class {
  constructor() {
    this.a = [];
    this.i = /* @__PURE__ */ new Set();
    this.j = new $ze();
    this.onDidSchemaChange = this.j.event;
    this.k = new $ze();
    this.onDidUpdateConfiguration = this.k.event;
    this.b = /* @__PURE__ */ new Map();
    this.c = {
      id: "defaultOverrides",
      title: localize(1693, null),
      properties: {}
    };
    this.d = [this.c];
    this.h = {
      properties: {},
      patternProperties: {},
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    this.e = {};
    this.f = /* @__PURE__ */ new Map();
    this.g = {};
    contributionRegistry.registerSchema($Ot, this.h);
    this.z();
  }
  registerConfiguration(configuration, validate = true) {
    this.registerConfigurations([configuration], validate);
  }
  registerConfigurations(configurations, validate = true) {
    const properties = /* @__PURE__ */ new Set();
    this.r(configurations, validate, properties);
    contributionRegistry.registerSchema($Ot, this.h);
    this.j.fire();
    this.k.fire({ properties });
  }
  deregisterConfigurations(configurations) {
    const properties = /* @__PURE__ */ new Set();
    this.s(configurations, properties);
    contributionRegistry.registerSchema($Ot, this.h);
    this.j.fire();
    this.k.fire({ properties });
  }
  updateConfigurations({ add, remove }) {
    const properties = /* @__PURE__ */ new Set();
    this.s(remove, properties);
    this.r(add, false, properties);
    contributionRegistry.registerSchema($Ot, this.h);
    this.j.fire();
    this.k.fire({ properties });
  }
  registerDefaultConfigurations(configurationDefaults) {
    const properties = /* @__PURE__ */ new Set();
    this.l(configurationDefaults, properties);
    this.j.fire();
    this.k.fire({ properties, defaultsOverrides: true });
  }
  l(configurationDefaults, bucket) {
    this.a.push(...configurationDefaults);
    const overrideIdentifiers = [];
    for (const { overrides, source } of configurationDefaults) {
      for (const key in overrides) {
        bucket.add(key);
        const configurationDefaultOverridesForKey = this.b.get(key) ?? this.b.set(key, { configurationDefaultOverrides: [] }).get(key);
        const value = overrides[key];
        configurationDefaultOverridesForKey.configurationDefaultOverrides.push({ value, source });
        if ($Rt.test(key)) {
          const newDefaultOverride = this.o(key, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue);
          if (!newDefaultOverride) {
            continue;
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride;
          this.n(key, newDefaultOverride, source);
          overrideIdentifiers.push(...$St(key));
        } else {
          const newDefaultOverride = this.p(key, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue);
          if (!newDefaultOverride) {
            continue;
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride;
          const property = this.e[key];
          if (property) {
            this.A(key, property);
            this.w(key, property);
          }
        }
      }
    }
    this.q(overrideIdentifiers);
  }
  deregisterDefaultConfigurations(defaultConfigurations) {
    const properties = /* @__PURE__ */ new Set();
    this.m(defaultConfigurations, properties);
    this.j.fire();
    this.k.fire({ properties, defaultsOverrides: true });
  }
  m(defaultConfigurations, bucket) {
    for (const defaultConfiguration of defaultConfigurations) {
      const index = this.a.indexOf(defaultConfiguration);
      if (index !== -1) {
        this.a.splice(index, 1);
      }
    }
    for (const { overrides, source } of defaultConfigurations) {
      for (const key in overrides) {
        const configurationDefaultOverridesForKey = this.b.get(key);
        if (!configurationDefaultOverridesForKey) {
          continue;
        }
        const index = configurationDefaultOverridesForKey.configurationDefaultOverrides.findIndex((configurationDefaultOverride) => source ? configurationDefaultOverride.source?.id === source.id : configurationDefaultOverride.value === overrides[key]);
        if (index === -1) {
          continue;
        }
        configurationDefaultOverridesForKey.configurationDefaultOverrides.splice(index, 1);
        if (configurationDefaultOverridesForKey.configurationDefaultOverrides.length === 0) {
          this.b.delete(key);
        }
        if ($Rt.test(key)) {
          let configurationDefaultOverrideValue;
          for (const configurationDefaultOverride of configurationDefaultOverridesForKey.configurationDefaultOverrides) {
            configurationDefaultOverrideValue = this.o(key, configurationDefaultOverride.value, configurationDefaultOverride.source, configurationDefaultOverrideValue);
          }
          if (configurationDefaultOverrideValue && !$Mg(configurationDefaultOverrideValue.value)) {
            configurationDefaultOverridesForKey.configurationDefaultOverrideValue = configurationDefaultOverrideValue;
            this.n(key, configurationDefaultOverrideValue, source);
          } else {
            this.b.delete(key);
            delete this.e[key];
            delete this.c.properties[key];
          }
        } else {
          let configurationDefaultOverrideValue;
          for (const configurationDefaultOverride of configurationDefaultOverridesForKey.configurationDefaultOverrides) {
            configurationDefaultOverrideValue = this.p(key, configurationDefaultOverride.value, configurationDefaultOverride.source, configurationDefaultOverrideValue);
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = configurationDefaultOverrideValue;
          const property = this.e[key];
          if (property) {
            this.A(key, property);
            this.w(key, property);
          }
        }
        bucket.add(key);
      }
    }
    this.y();
  }
  n(key, newDefaultOverride, source) {
    const property = {
      type: "object",
      default: newDefaultOverride.value,
      description: localize(1694, null, $ul(key)),
      $ref: $Ot,
      defaultDefaultValue: newDefaultOverride.value,
      source,
      defaultValueSource: source
    };
    this.e[key] = property;
    this.c.properties[key] = property;
  }
  o(overrideIdentifier, configurationValueObject, valueSource, existingDefaultOverride) {
    const defaultValue = existingDefaultOverride?.value || {};
    const source = existingDefaultOverride?.source ?? /* @__PURE__ */ new Map();
    if (!(source instanceof Map)) {
      console.error("objectConfigurationSources is not a Map");
      return void 0;
    }
    for (const propertyKey of Object.keys(configurationValueObject)) {
      const propertyDefaultValue = configurationValueObject[propertyKey];
      const isObjectSetting = $Bg(propertyDefaultValue) && ($Gg(defaultValue[propertyKey]) || $Bg(defaultValue[propertyKey]));
      if (isObjectSetting) {
        defaultValue[propertyKey] = { ...defaultValue[propertyKey] ?? {}, ...propertyDefaultValue };
        if (valueSource) {
          for (const objectKey in propertyDefaultValue) {
            source.set(`${propertyKey}.${objectKey}`, valueSource);
          }
        }
      } else {
        defaultValue[propertyKey] = propertyDefaultValue;
        if (valueSource) {
          source.set(propertyKey, valueSource);
        } else {
          source.delete(propertyKey);
        }
      }
    }
    return { value: defaultValue, source };
  }
  p(propertyKey, value, valuesSource, existingDefaultOverride) {
    const property = this.e[propertyKey];
    const existingDefaultValue = existingDefaultOverride?.value ?? property?.defaultDefaultValue;
    let source = valuesSource;
    const isObjectSetting = $Bg(value) && (property !== void 0 && property.type === "object" || property === void 0 && ($Gg(existingDefaultValue) || $Bg(existingDefaultValue)));
    if (isObjectSetting) {
      source = existingDefaultOverride?.source ?? /* @__PURE__ */ new Map();
      if (!(source instanceof Map)) {
        console.error("defaultValueSource is not a Map");
        return void 0;
      }
      for (const objectKey in value) {
        if (valuesSource) {
          source.set(`${propertyKey}.${objectKey}`, valuesSource);
        }
      }
      value = { ...$Bg(existingDefaultValue) ? existingDefaultValue : {}, ...value };
    }
    return { value, source };
  }
  deltaConfiguration(delta2) {
    let defaultsOverrides = false;
    const properties = /* @__PURE__ */ new Set();
    if (delta2.removedDefaults) {
      this.m(delta2.removedDefaults, properties);
      defaultsOverrides = true;
    }
    if (delta2.addedDefaults) {
      this.l(delta2.addedDefaults, properties);
      defaultsOverrides = true;
    }
    if (delta2.removedConfigurations) {
      this.s(delta2.removedConfigurations, properties);
    }
    if (delta2.addedConfigurations) {
      this.r(delta2.addedConfigurations, false, properties);
    }
    this.j.fire();
    this.k.fire({ properties, defaultsOverrides });
  }
  notifyConfigurationSchemaUpdated(...configurations) {
    this.j.fire();
  }
  registerOverrideIdentifiers(overrideIdentifiers) {
    this.q(overrideIdentifiers);
    this.j.fire();
  }
  q(overrideIdentifiers) {
    for (const overrideIdentifier of overrideIdentifiers) {
      this.i.add(overrideIdentifier);
    }
    this.y();
  }
  r(configurations, validate, bucket) {
    configurations.forEach((configuration) => {
      this.u(configuration, validate, configuration.extensionInfo, configuration.restrictedProperties, void 0, bucket);
      this.d.push(configuration);
      this.v(configuration);
    });
  }
  s(configurations, bucket) {
    const deregisterConfiguration = (configuration) => {
      if (configuration.properties) {
        for (const key in configuration.properties) {
          bucket.add(key);
          const property = this.e[key];
          if (property?.policy?.name) {
            this.f.delete(property.policy.name);
          }
          delete this.e[key];
          this.x(key, configuration.properties[key]);
        }
      }
      configuration.allOf?.forEach((node) => deregisterConfiguration(node));
    };
    for (const configuration of configurations) {
      deregisterConfiguration(configuration);
      const index = this.d.indexOf(configuration);
      if (index !== -1) {
        this.d.splice(index, 1);
      }
    }
  }
  u(configuration, validate = true, extensionInfo, restrictedProperties, scope = 3, bucket) {
    scope = $Ig(configuration.scope) ? scope : configuration.scope;
    const properties = configuration.properties;
    if (properties) {
      for (const key in properties) {
        const property = properties[key];
        if (validate && $Vt(key, property)) {
          delete properties[key];
          continue;
        }
        property.source = extensionInfo;
        property.defaultDefaultValue = properties[key].default;
        this.A(key, property);
        if ($Rt.test(key)) {
          property.scope = void 0;
        } else {
          property.scope = $Ig(property.scope) ? scope : property.scope;
          property.restricted = $Ig(property.restricted) ? !!restrictedProperties?.includes(key) : property.restricted;
        }
        if (properties[key].hasOwnProperty("included") && !properties[key].included) {
          this.g[key] = properties[key];
          delete properties[key];
          continue;
        } else {
          this.e[key] = properties[key];
          if (properties[key].policy?.name) {
            this.f.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 node of subNodes) {
        this.u(node, validate, extensionInfo, restrictedProperties, scope, bucket);
      }
    }
  }
  // TODO: @sandy081 - Remove this method and include required info in getConfigurationProperties
  getConfigurations() {
    return this.d;
  }
  getConfigurationProperties() {
    return this.e;
  }
  getPolicyConfigurations() {
    return this.f;
  }
  getExcludedConfigurationProperties() {
    return this.g;
  }
  getRegisteredDefaultConfigurations() {
    return [...this.a];
  }
  getConfigurationDefaultsOverrides() {
    const configurationDefaultsOverrides = /* @__PURE__ */ new Map();
    for (const [key, value] of this.b) {
      if (value.configurationDefaultOverrideValue) {
        configurationDefaultsOverrides.set(key, value.configurationDefaultOverrideValue);
      }
    }
    return configurationDefaultsOverrides;
  }
  v(configuration) {
    const register2 = (configuration2) => {
      const properties = configuration2.properties;
      if (properties) {
        for (const key in properties) {
          this.w(key, properties[key]);
        }
      }
      const subNodes = configuration2.allOf;
      subNodes?.forEach(register2);
    };
    register2(configuration);
  }
  w(key, property) {
    $It.properties[key] = property;
    switch (property.scope) {
      case 1:
        $Jt.properties[key] = property;
        break;
      case 2:
        $Kt.properties[key] = property;
        break;
      case 6:
        $Lt.properties[key] = property;
        break;
      case 3:
        $Mt.properties[key] = property;
        break;
      case 4:
        $Nt.properties[key] = property;
        break;
      case 5:
        $Nt.properties[key] = property;
        this.h.properties[key] = property;
        break;
    }
  }
  x(key, property) {
    delete $It.properties[key];
    switch (property.scope) {
      case 1:
        delete $Jt.properties[key];
        break;
      case 2:
        delete $Kt.properties[key];
        break;
      case 6:
        delete $Lt.properties[key];
        break;
      case 3:
        delete $Mt.properties[key];
        break;
      case 4:
      case 5:
        delete $Nt.properties[key];
        delete this.h.properties[key];
        break;
    }
  }
  y() {
    for (const overrideIdentifier of this.i.values()) {
      const overrideIdentifierProperty = `[${overrideIdentifier}]`;
      const resourceLanguagePropertiesSchema = {
        type: "object",
        description: localize(1695, null),
        errorMessage: localize(1696, null),
        $ref: $Ot
      };
      this.A(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
      $It.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Jt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Kt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Lt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Mt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Nt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
    }
  }
  z() {
    const resourceLanguagePropertiesSchema = {
      type: "object",
      description: localize(1697, null),
      errorMessage: localize(1698, null),
      $ref: $Ot
    };
    $It.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Jt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Kt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Lt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Mt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Nt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    this.j.fire();
  }
  A(key, property) {
    const configurationdefaultOverride = this.b.get(key)?.configurationDefaultOverrideValue;
    let defaultValue = void 0;
    let defaultSource = void 0;
    if (configurationdefaultOverride && (!property.disallowConfigurationDefault || !configurationdefaultOverride.source)) {
      defaultValue = configurationdefaultOverride.value;
      defaultSource = configurationdefaultOverride.source;
    }
    if ($Gg(defaultValue)) {
      defaultValue = property.defaultDefaultValue;
      defaultSource = void 0;
    }
    if ($Gg(defaultValue)) {
      defaultValue = $Ut(property.type);
    }
    property.default = defaultValue;
    property.defaultValueSource = defaultSource;
  }
};
var OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`;
var OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, "g");
var $Qt = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`;
var $Rt = new RegExp($Qt);
function $St(key) {
  const identifiers2 = [];
  if ($Rt.test(key)) {
    let matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
    while (matches?.length) {
      const identifier = matches[1].trim();
      if (identifier) {
        identifiers2.push(identifier);
      }
      matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
    }
  }
  return $Rb(identifiers2);
}
function $Ut(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;
  }
}
var configurationRegistry = new ConfigurationRegistry();
$Wn.add($Ht.Configuration, configurationRegistry);
function $Vt(property, schema) {
  if (!property.trim()) {
    return localize(1699, null);
  }
  if ($Rt.test(property)) {
    return localize(1700, null, property);
  }
  if (configurationRegistry.getConfigurationProperties()[property] !== void 0) {
    return localize(1701, null, property);
  }
  if (schema.policy?.name && configurationRegistry.getPolicyConfigurations().get(schema.policy?.name) !== void 0) {
    return localize(1702, null, property, schema.policy?.name, configurationRegistry.getPolicyConfigurations().get(schema.policy?.name));
  }
  return null;
}

// out-build/vs/platform/request/common/request.js
var $9u = $Qk("requestService");
var LoggableHeaders = class {
  constructor(b) {
    this.b = b;
  }
  toJSON() {
    if (!this.a) {
      const headers = /* @__PURE__ */ Object.create(null);
      for (const key in this.b) {
        if (key.toLowerCase() === "authorization" || key.toLowerCase() === "proxy-authorization") {
          headers[key] = "*****";
        } else {
          headers[key] = this.b[key];
        }
      }
      this.a = headers;
    }
    return this.a;
  }
};
var $0u = class extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.a = 0;
  }
  async c(options2, request) {
    const prefix = `[network] #${++this.a}: ${options2.url}`;
    this.b.trace(`${prefix} - begin`, options2.type, new LoggableHeaders(options2.headers ?? {}));
    try {
      const result = await request();
      this.b.trace(`${prefix} - end`, options2.type, result.res.statusCode, result.res.headers);
      return result;
    } catch (error) {
      this.b.error(`${prefix} - error`, options2.type, $qb(error));
      throw error;
    }
  }
};
function $$u(context) {
  return context.res.statusCode && context.res.statusCode >= 200 && context.res.statusCode < 300 || context.res.statusCode === 1223;
}
function $_u(context) {
  return context.res.statusCode === 204;
}
async function $cv(context) {
  if (!$$u(context)) {
    throw new Error("Server returned " + context.res.statusCode);
  }
  if ($_u(context)) {
    return null;
  }
  const buffer = await $Oi(context.stream);
  const str = buffer.toString();
  try {
    return JSON.parse(str);
  } catch (err) {
    err.message += ":\n" + str;
    throw err;
  }
}
var proxyConfiguration;
function registerProxyConfigurations(scope) {
  const configurationRegistry3 = $Wn.as($Ht.Configuration);
  const oldProxyConfiguration = proxyConfiguration;
  proxyConfiguration = {
    id: "http",
    order: 15,
    title: localize(2088, null),
    type: "object",
    scope,
    properties: {
      "http.proxy": {
        type: "string",
        pattern: "^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",
        markdownDescription: localize(2089, null),
        restricted: true
      },
      "http.proxyStrictSSL": {
        type: "boolean",
        default: true,
        description: localize(2090, null),
        restricted: true
      },
      "http.proxyKerberosServicePrincipal": {
        type: "string",
        markdownDescription: localize(2091, null),
        restricted: true
      },
      "http.noProxy": {
        type: "array",
        items: { type: "string" },
        markdownDescription: localize(2092, null),
        restricted: true
      },
      "http.proxyAuthorization": {
        type: ["null", "string"],
        default: null,
        markdownDescription: localize(2093, null),
        restricted: true
      },
      "http.proxySupport": {
        type: "string",
        enum: ["off", "on", "fallback", "override"],
        enumDescriptions: [
          localize(2094, null),
          localize(2095, null),
          localize(2096, null),
          localize(2097, null)
        ],
        default: "override",
        description: localize(2098, null),
        restricted: true
      },
      "http.systemCertificates": {
        type: "boolean",
        default: true,
        description: localize(2099, null),
        restricted: true
      },
      "http.experimental.systemCertificatesV2": {
        type: "boolean",
        tags: ["experimental"],
        default: false,
        description: localize(2100, null),
        restricted: true
      },
      "http.electronFetch": {
        type: "boolean",
        default: false,
        description: localize(2101, null),
        restricted: true
      },
      "http.fetchAdditionalSupport": {
        type: "boolean",
        default: true,
        markdownDescription: localize(2102, null, "`#http.proxySupport#`", "`#http.systemCertificates#`"),
        restricted: true
      }
    }
  };
  configurationRegistry3.updateConfigurations({ add: [proxyConfiguration], remove: oldProxyConfiguration ? [oldProxyConfiguration] : [] });
}
registerProxyConfigurations(
  1
  /* ConfigurationScope.APPLICATION */
);

// out-build/vs/base/parts/storage/common/storage.js
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 = {}));
var $fv = class _$fv extends $3c {
  static {
    this.a = 100;
  }
  constructor(r, s = /* @__PURE__ */ Object.create(null)) {
    super();
    this.r = r;
    this.s = s;
    this.b = this.B(new $Ce());
    this.onDidChangeStorage = this.b.event;
    this.c = StorageState.None;
    this.f = /* @__PURE__ */ new Map();
    this.g = this.B(new $Th(_$fv.a));
    this.h = /* @__PURE__ */ new Set();
    this.j = /* @__PURE__ */ new Map();
    this.m = void 0;
    this.n = [];
    this.t();
  }
  t() {
    this.B(this.r.onDidChangeItemsExternal((e) => this.u(e)));
  }
  u(e) {
    this.b.pause();
    try {
      e.changed?.forEach((value, key) => this.w(key, value));
      e.deleted?.forEach((key) => this.w(key, void 0));
    } finally {
      this.b.resume();
    }
  }
  w(key, value) {
    if (this.c === StorageState.Closed) {
      return;
    }
    let changed = false;
    if ($Ig(value)) {
      changed = this.f.delete(key);
    } else {
      const currentValue = this.f.get(key);
      if (currentValue !== value) {
        this.f.set(key, value);
        changed = true;
      }
    }
    if (changed) {
      this.b.fire({ key, external: true });
    }
  }
  get items() {
    return this.f;
  }
  get size() {
    return this.f.size;
  }
  async init() {
    if (this.c !== StorageState.None) {
      return;
    }
    this.c = StorageState.Initialized;
    if (this.s.hint === StorageHint.STORAGE_DOES_NOT_EXIST) {
      return;
    }
    this.f = await this.r.getItems();
  }
  get(key, fallbackValue) {
    const value = this.f.get(key);
    if ($Ig(value)) {
      return fallbackValue;
    }
    return value;
  }
  getBoolean(key, fallbackValue) {
    const value = this.get(key);
    if ($Ig(value)) {
      return fallbackValue;
    }
    return value === "true";
  }
  getNumber(key, fallbackValue) {
    const value = this.get(key);
    if ($Ig(value)) {
      return fallbackValue;
    }
    return parseInt(value, 10);
  }
  getObject(key, fallbackValue) {
    const value = this.get(key);
    if ($Ig(value)) {
      return fallbackValue;
    }
    return $bu(value);
  }
  async set(key, value, external = false) {
    if (this.c === StorageState.Closed) {
      return;
    }
    if ($Ig(value)) {
      return this.delete(key, external);
    }
    const valueStr = $Bg(value) || Array.isArray(value) ? $au(value) : String(value);
    const currentValue = this.f.get(key);
    if (currentValue === valueStr) {
      return;
    }
    this.f.set(key, valueStr);
    this.j.set(key, valueStr);
    this.h.delete(key);
    this.b.fire({ key, external });
    return this.D();
  }
  async delete(key, external = false) {
    if (this.c === StorageState.Closed) {
      return;
    }
    const wasDeleted = this.f.delete(key);
    if (!wasDeleted) {
      return;
    }
    if (!this.h.has(key)) {
      this.h.add(key);
    }
    this.j.delete(key);
    this.b.fire({ key, external });
    return this.D();
  }
  async optimize() {
    if (this.c === StorageState.Closed) {
      return;
    }
    await this.flush(0);
    return this.r.optimize();
  }
  async close() {
    if (!this.m) {
      this.m = this.y();
    }
    return this.m;
  }
  async y() {
    this.c = StorageState.Closed;
    try {
      await this.D(
        0
        /* as soon as possible */
      );
    } catch (error) {
    }
    await this.r.close(() => this.f);
  }
  get z() {
    return this.j.size > 0 || this.h.size > 0;
  }
  async C() {
    if (!this.z) {
      return;
    }
    const updateRequest = { insert: this.j, delete: this.h };
    this.h = /* @__PURE__ */ new Set();
    this.j = /* @__PURE__ */ new Map();
    return this.r.updateItems(updateRequest).finally(() => {
      if (!this.z) {
        while (this.n.length) {
          this.n.pop()?.();
        }
      }
    });
  }
  async flush(delay) {
    if (this.c === StorageState.Closed || // Return early if we are already closed
    this.m) {
      return;
    }
    return this.D(delay);
  }
  async D(delay) {
    if (this.s.hint === StorageHint.STORAGE_IN_MEMORY) {
      return this.C();
    }
    return this.g.trigger(() => this.C(), delay);
  }
  async whenFlushed() {
    if (!this.z) {
      return;
    }
    return new Promise((resolve) => this.n.push(resolve));
  }
  isInMemory() {
    return this.s.hint === StorageHint.STORAGE_IN_MEMORY;
  }
};

// out-build/vs/platform/environment/common/environment.js
var $Xk = $Qk("environmentService");
var $Yk = $Rk($Xk);

// out-build/vs/platform/uriIdentity/common/uriIdentity.js
var $vl = $Qk("IUriIdentityService");

// out-build/vs/platform/userDataProfile/common/userDataProfile.js
var ProfileResourceType;
(function(ProfileResourceType2) {
  ProfileResourceType2["Settings"] = "settings";
  ProfileResourceType2["Keybindings"] = "keybindings";
  ProfileResourceType2["Snippets"] = "snippets";
  ProfileResourceType2["Tasks"] = "tasks";
  ProfileResourceType2["Extensions"] = "extensions";
  ProfileResourceType2["GlobalState"] = "globalState";
})(ProfileResourceType || (ProfileResourceType = {}));
function $qs(thing) {
  const candidate = thing;
  return !!(candidate && typeof candidate === "object" && typeof candidate.id === "string" && typeof candidate.isDefault === "boolean" && typeof candidate.name === "string" && URI.isUri(candidate.location) && URI.isUri(candidate.globalStorageHome) && URI.isUri(candidate.settingsResource) && URI.isUri(candidate.keybindingsResource) && URI.isUri(candidate.tasksResource) && URI.isUri(candidate.snippetsHome) && URI.isUri(candidate.extensionsResource));
}
var $rs = $Qk("IUserDataProfilesService");
function $ts(id2, name, location2, profilesCacheHome, options2, defaultProfile) {
  return {
    id: id2,
    name,
    location: location2,
    isDefault: false,
    icon: options2?.icon,
    globalStorageHome: defaultProfile && options2?.useDefaultFlags?.globalState ? defaultProfile.globalStorageHome : $vh(location2, "globalStorage"),
    settingsResource: defaultProfile && options2?.useDefaultFlags?.settings ? defaultProfile.settingsResource : $vh(location2, "settings.json"),
    keybindingsResource: defaultProfile && options2?.useDefaultFlags?.keybindings ? defaultProfile.keybindingsResource : $vh(location2, "keybindings.json"),
    tasksResource: defaultProfile && options2?.useDefaultFlags?.tasks ? defaultProfile.tasksResource : $vh(location2, "tasks.json"),
    snippetsHome: defaultProfile && options2?.useDefaultFlags?.snippets ? defaultProfile.snippetsHome : $vh(location2, "snippets"),
    extensionsResource: defaultProfile && options2?.useDefaultFlags?.extensions ? defaultProfile.extensionsResource : $vh(location2, "extensions.json"),
    cacheHome: $vh(profilesCacheHome, id2),
    useDefaultFlags: options2?.useDefaultFlags,
    isTransient: options2?.transient,
    workspaces: options2?.workspaces
  };
}
var $us = class $us2 extends $3c {
  static {
    this.b = "userDataProfiles";
  }
  static {
    this.c = "profileAssociations";
  }
  get defaultProfile() {
    return this.profiles[0];
  }
  get profiles() {
    return [...this.C.profiles, ...this.r.profiles];
  }
  constructor(s, t, u, y) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.y = y;
    this.g = this.B(new $ze());
    this.onDidChangeProfiles = this.g.event;
    this.h = this.B(new $ze());
    this.onWillCreateProfile = this.h.event;
    this.j = this.B(new $ze());
    this.onWillRemoveProfile = this.j.event;
    this.m = this.B(new $ze());
    this.onDidResetWorkspaces = this.m.event;
    this.n = /* @__PURE__ */ new Map();
    this.r = {
      profiles: [],
      emptyWindows: /* @__PURE__ */ new Map()
    };
    this.profilesHome = $vh(this.s.userRoamingDataHome, "profiles");
    this.f = $vh(this.s.cacheHome, "CachedProfilesData");
  }
  init() {
    this.z = void 0;
  }
  get C() {
    if (!this.z) {
      const defaultProfile = this.D();
      const profiles = [defaultProfile];
      try {
        for (const storedProfile of this.N()) {
          if (!storedProfile.name || !$zg(storedProfile.name) || !storedProfile.location) {
            this.y.warn("Skipping the invalid stored profile", storedProfile.location || storedProfile.name);
            continue;
          }
          profiles.push($ts($sh(storedProfile.location), storedProfile.name, storedProfile.location, this.f, { icon: storedProfile.icon, useDefaultFlags: storedProfile.useDefaultFlags }, defaultProfile));
        }
      } catch (error) {
        this.y.error(error);
      }
      const emptyWindows = /* @__PURE__ */ new Map();
      if (profiles.length) {
        try {
          const profileAssociaitions = this.P();
          if (profileAssociaitions.workspaces) {
            for (const [workspacePath, profileId] of Object.entries(profileAssociaitions.workspaces)) {
              const workspace = URI.parse(workspacePath);
              const profile = profiles.find((p) => p.id === profileId);
              if (profile) {
                const workspaces = profile.workspaces ? profile.workspaces.slice(0) : [];
                workspaces.push(workspace);
                profile.workspaces = workspaces;
              }
            }
          }
          if (profileAssociaitions.emptyWindows) {
            for (const [windowId, profileId] of Object.entries(profileAssociaitions.emptyWindows)) {
              const profile = profiles.find((p) => p.id === profileId);
              if (profile) {
                emptyWindows.set(windowId, profile);
              }
            }
          }
        } catch (error) {
          this.y.error(error);
        }
      }
      this.z = { profiles, emptyWindows };
    }
    return this.z;
  }
  D() {
    const defaultProfile = $ts("__default__profile__", localize(2489, null), this.s.userRoamingDataHome, this.f);
    return { ...defaultProfile, extensionsResource: this.R() ?? defaultProfile.extensionsResource, isDefault: true };
  }
  async createTransientProfile(workspaceIdentifier) {
    const namePrefix = `Temp`;
    const nameRegEx = new RegExp(`${$Af(namePrefix)}\\s(\\d+)`);
    let nameIndex = 0;
    for (const profile of this.profiles) {
      const matches = nameRegEx.exec(profile.name);
      const index = matches ? parseInt(matches[1]) : 0;
      nameIndex = index > nameIndex ? index : nameIndex;
    }
    const name = `${namePrefix} ${nameIndex + 1}`;
    return this.createProfile($Xi($ps()).toString(16), name, { transient: true }, workspaceIdentifier);
  }
  async createNamedProfile(name, options2, workspaceIdentifier) {
    return this.createProfile($Xi($ps()).toString(16), name, options2, workspaceIdentifier);
  }
  async createProfile(id2, name, options2, workspaceIdentifier) {
    const profile = await this.F(id2, name, options2, workspaceIdentifier);
    return profile;
  }
  async F(id2, name, options2, workspaceIdentifier) {
    if (!$zg(name) || !name) {
      throw new Error("Name of the profile is mandatory and must be of type `string`");
    }
    let profileCreationPromise = this.n.get(name);
    if (!profileCreationPromise) {
      profileCreationPromise = (async () => {
        try {
          const existing = this.profiles.find((p) => p.id === id2 || !p.isTransient && !options2?.transient && p.name === name);
          if (existing) {
            throw new Error(`Profile with ${name} name already exists`);
          }
          const workspace = workspaceIdentifier ? this.G(workspaceIdentifier) : void 0;
          if (URI.isUri(workspace)) {
            options2 = { ...options2, workspaces: [workspace] };
          }
          const profile = $ts(id2, name, $vh(this.profilesHome, id2), this.f, options2, this.defaultProfile);
          await this.t.createFolder(profile.location);
          const joiners = [];
          this.h.fire({
            profile,
            join(promise) {
              joiners.push(promise);
            }
          });
          await Promises.settled(joiners);
          if (workspace && !URI.isUri(workspace)) {
            this.L(workspace, profile, !!profile.isTransient);
          }
          this.I([profile], [], []);
          return profile;
        } finally {
          this.n.delete(name);
        }
      })();
      this.n.set(name, profileCreationPromise);
    }
    return profileCreationPromise;
  }
  async updateProfile(profile, options2) {
    const profilesToUpdate = [];
    for (const existing of this.profiles) {
      let profileToUpdate;
      if (profile.id === existing.id) {
        if (!existing.isDefault) {
          profileToUpdate = $ts(existing.id, options2.name ?? existing.name, existing.location, this.f, {
            icon: options2.icon === null ? void 0 : options2.icon ?? existing.icon,
            transient: options2.transient ?? existing.isTransient,
            useDefaultFlags: options2.useDefaultFlags ?? existing.useDefaultFlags,
            workspaces: options2.workspaces ?? existing.workspaces
          }, this.defaultProfile);
        } else if (options2.workspaces) {
          profileToUpdate = existing;
          profileToUpdate.workspaces = options2.workspaces;
        }
      } else if (options2.workspaces) {
        const workspaces = existing.workspaces?.filter((w1) => !options2.workspaces?.some((w2) => this.u.extUri.isEqual(w1, w2)));
        if (existing.workspaces?.length !== workspaces?.length) {
          profileToUpdate = existing;
          profileToUpdate.workspaces = workspaces;
        }
      }
      if (profileToUpdate) {
        profilesToUpdate.push(profileToUpdate);
      }
    }
    if (!profilesToUpdate.length) {
      if (profile.isDefault) {
        throw new Error("Cannot update default profile");
      }
      throw new Error(`Profile '${profile.name}' does not exist`);
    }
    this.I([], [], profilesToUpdate);
    const updatedProfile = this.profiles.find((p) => p.id === profile.id);
    if (!updatedProfile) {
      throw new Error(`Profile '${profile.name}' was not updated`);
    }
    return updatedProfile;
  }
  async removeProfile(profileToRemove) {
    if (profileToRemove.isDefault) {
      throw new Error("Cannot remove default profile");
    }
    const profile = this.profiles.find((p) => p.id === profileToRemove.id);
    if (!profile) {
      throw new Error(`Profile '${profileToRemove.name}' does not exist`);
    }
    const joiners = [];
    this.j.fire({
      profile,
      join(promise) {
        joiners.push(promise);
      }
    });
    try {
      await Promise.allSettled(joiners);
    } catch (error) {
      this.y.error(error);
    }
    this.I([], [profile], []);
    try {
      await this.t.del(profile.cacheHome, { recursive: true });
    } catch (error) {
      if ($Bm(error) !== 1) {
        this.y.error(error);
      }
    }
  }
  async setProfileForWorkspace(workspaceIdentifier, profileToSet) {
    const profile = this.profiles.find((p) => p.id === profileToSet.id);
    if (!profile) {
      throw new Error(`Profile '${profileToSet.name}' does not exist`);
    }
    const workspace = this.G(workspaceIdentifier);
    if (URI.isUri(workspace)) {
      const workspaces = profile.workspaces ? [...profile.workspaces] : [];
      if (!workspaces.some((w) => this.u.extUri.isEqual(w, workspace))) {
        workspaces.push(workspace);
        await this.updateProfile(profile, { workspaces });
      }
    } else {
      this.L(workspace, profile, false);
      this.M(this.profiles);
    }
  }
  unsetWorkspace(workspaceIdentifier, transient = false) {
    const workspace = this.G(workspaceIdentifier);
    if (URI.isUri(workspace)) {
      const currentlyAssociatedProfile = this.getProfileForWorkspace(workspaceIdentifier);
      if (currentlyAssociatedProfile) {
        this.updateProfile(currentlyAssociatedProfile, { workspaces: currentlyAssociatedProfile.workspaces?.filter((w) => !this.u.extUri.isEqual(w, workspace)) });
      }
    } else {
      this.L(workspace, void 0, transient);
      this.M(this.profiles);
    }
  }
  async resetWorkspaces() {
    this.r.emptyWindows.clear();
    this.C.emptyWindows.clear();
    for (const profile of this.profiles) {
      profile.workspaces = void 0;
    }
    this.I([], [], this.profiles);
    this.m.fire();
  }
  async cleanUp() {
    if (await this.t.exists(this.profilesHome)) {
      const stat2 = await this.t.resolve(this.profilesHome);
      await Promise.all((stat2.children || []).filter((child) => child.isDirectory && this.profiles.every((p) => !this.u.extUri.isEqual(p.location, child.resource))).map((child) => this.t.del(child.resource, { recursive: true })));
    }
  }
  async cleanUpTransientProfiles() {
    const unAssociatedTransientProfiles = this.r.profiles.filter((p) => !this.H(p));
    await Promise.allSettled(unAssociatedTransientProfiles.map((p) => this.removeProfile(p)));
  }
  getProfileForWorkspace(workspaceIdentifier) {
    const workspace = this.G(workspaceIdentifier);
    return URI.isUri(workspace) ? this.profiles.find((p) => p.workspaces?.some((w) => this.u.extUri.isEqual(w, workspace))) : this.C.emptyWindows.get(workspace) ?? this.r.emptyWindows.get(workspace);
  }
  G(workspaceIdentifier) {
    if ($1k(workspaceIdentifier)) {
      return workspaceIdentifier.uri;
    }
    if ($6k(workspaceIdentifier)) {
      return workspaceIdentifier.configPath;
    }
    return workspaceIdentifier.id;
  }
  H(profile) {
    if (profile.workspaces?.length) {
      return true;
    }
    if ([...this.C.emptyWindows.values()].some((windowProfile) => this.u.extUri.isEqual(windowProfile.location, profile.location))) {
      return true;
    }
    if ([...this.r.emptyWindows.values()].some((windowProfile) => this.u.extUri.isEqual(windowProfile.location, profile.location))) {
      return true;
    }
    return false;
  }
  I(added, removed, updated) {
    const allProfiles = [...this.profiles, ...added];
    const transientProfiles = this.r.profiles;
    this.r.profiles = [];
    const profiles = [];
    for (let profile of allProfiles) {
      if (removed.some((p) => profile.id === p.id)) {
        for (const windowId of [...this.C.emptyWindows.keys()]) {
          if (profile.id === this.C.emptyWindows.get(windowId)?.id) {
            this.C.emptyWindows.delete(windowId);
          }
        }
        continue;
      }
      if (!profile.isDefault) {
        profile = updated.find((p) => profile.id === p.id) ?? profile;
        const transientProfile = transientProfiles.find((p) => profile.id === p.id);
        if (profile.isTransient) {
          this.r.profiles.push(profile);
        } else {
          if (transientProfile) {
            for (const [windowId, p] of this.r.emptyWindows.entries()) {
              if (profile.id === p.id) {
                this.r.emptyWindows.delete(windowId);
                this.C.emptyWindows.set(windowId, profile);
                break;
              }
            }
          }
        }
      }
      if (profile.workspaces?.length === 0) {
        profile.workspaces = void 0;
      }
      profiles.push(profile);
    }
    this.M(profiles);
    this.J(added, removed, updated);
  }
  J(added, removed, updated) {
    this.g.fire({ added, removed, updated, all: this.profiles });
  }
  L(windowId, newProfile, transient) {
    transient = newProfile?.isTransient ? true : transient;
    if (transient) {
      if (newProfile) {
        this.r.emptyWindows.set(windowId, newProfile);
      } else {
        this.r.emptyWindows.delete(windowId);
      }
    } else {
      this.r.emptyWindows.delete(windowId);
      if (newProfile) {
        this.C.emptyWindows.set(windowId, newProfile);
      } else {
        this.C.emptyWindows.delete(windowId);
      }
    }
  }
  M(profiles) {
    const storedProfiles = [];
    const workspaces = {};
    const emptyWindows = {};
    for (const profile of profiles) {
      if (profile.isTransient) {
        continue;
      }
      if (!profile.isDefault) {
        storedProfiles.push({ location: profile.location, name: profile.name, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
      }
      if (profile.workspaces) {
        for (const workspace of profile.workspaces) {
          workspaces[workspace.toString()] = profile.id;
        }
      }
    }
    for (const [windowId, profile] of this.C.emptyWindows.entries()) {
      emptyWindows[windowId.toString()] = profile.id;
    }
    this.Q({ workspaces, emptyWindows });
    this.O(storedProfiles);
    this.z = void 0;
  }
  N() {
    return [];
  }
  O(storedProfiles) {
    throw new Error("not implemented");
  }
  P() {
    return {};
  }
  Q(storedProfileAssociations) {
    throw new Error("not implemented");
  }
  R() {
    return void 0;
  }
};
$us = __decorate([
  __param(0, $Xk),
  __param(1, $km),
  __param(2, $vl),
  __param(3, $wn)
], $us);

// out-build/vs/platform/storage/common/storage.js
var $hv = "__$__isNewStorageMarker";
var $iv = "__$__targetStorageMarker";
var $jv = $Qk("storageService");
var WillSaveStateReason;
(function(WillSaveStateReason2) {
  WillSaveStateReason2[WillSaveStateReason2["NONE"] = 0] = "NONE";
  WillSaveStateReason2[WillSaveStateReason2["SHUTDOWN"] = 1] = "SHUTDOWN";
})(WillSaveStateReason || (WillSaveStateReason = {}));
var StorageScope;
(function(StorageScope2) {
  StorageScope2[StorageScope2["APPLICATION"] = -1] = "APPLICATION";
  StorageScope2[StorageScope2["PROFILE"] = 0] = "PROFILE";
  StorageScope2[StorageScope2["WORKSPACE"] = 1] = "WORKSPACE";
})(StorageScope || (StorageScope = {}));
var StorageTarget;
(function(StorageTarget2) {
  StorageTarget2[StorageTarget2["USER"] = 0] = "USER";
  StorageTarget2[StorageTarget2["MACHINE"] = 1] = "MACHINE";
})(StorageTarget || (StorageTarget = {}));
function $kv(storage) {
  const keysRaw = storage.get($iv);
  if (keysRaw) {
    try {
      return JSON.parse(keysRaw);
    } catch (error) {
    }
  }
  return /* @__PURE__ */ Object.create(null);
}
var $lv = class _$lv extends $3c {
  static {
    this.a = 60 * 1e3;
  }
  // every minute
  constructor(m = { flushInterval: _$lv.a }) {
    super();
    this.m = m;
    this.b = this.B(new $Ce());
    this.c = this.B(new $Ce());
    this.onDidChangeTarget = this.c.event;
    this.f = this.B(new $ze());
    this.onWillSaveState = this.f.event;
    this.h = this.B(new $8h(() => this.n(), this.m.flushInterval));
    this.j = this.B(new $4c());
    this.C = void 0;
    this.F = void 0;
    this.H = void 0;
  }
  onDidChangeValue(scope, key, disposable) {
    return Event.filter(this.b.event, (e) => e.scope === scope && (key === void 0 || e.key === key), disposable);
  }
  n() {
    this.j.value = $_h(() => {
      if (this.r()) {
        this.flush();
      }
      this.h.schedule();
    });
  }
  r() {
    return true;
  }
  t() {
    $Xc([this.j, this.h]);
  }
  initialize() {
    if (!this.g) {
      this.g = (async () => {
        $S("code/willInitStorage");
        try {
          await this.O();
        } finally {
          $S("code/didInitStorage");
        }
        this.h.schedule();
      })();
    }
    return this.g;
  }
  u(scope, event) {
    const { key, external } = event;
    if (key === $iv) {
      switch (scope) {
        case -1:
          this.H = void 0;
          break;
        case 0:
          this.F = void 0;
          break;
        case 1:
          this.C = void 0;
          break;
      }
      this.c.fire({ scope });
    } else {
      this.b.fire({ scope, key, target: this.J(scope)[key], external });
    }
  }
  w(reason) {
    this.f.fire({ reason });
  }
  get(key, scope, fallbackValue) {
    return this.P(scope)?.get(key, fallbackValue);
  }
  getBoolean(key, scope, fallbackValue) {
    return this.P(scope)?.getBoolean(key, fallbackValue);
  }
  getNumber(key, scope, fallbackValue) {
    return this.P(scope)?.getNumber(key, fallbackValue);
  }
  getObject(key, scope, fallbackValue) {
    return this.P(scope)?.getObject(key, fallbackValue);
  }
  storeAll(entries, external) {
    this.y(() => {
      for (const entry of entries) {
        this.store(entry.key, entry.value, entry.scope, entry.target, external);
      }
    });
  }
  store(key, value, scope, target, external = false) {
    if ($Ig(value)) {
      this.remove(key, scope, external);
      return;
    }
    this.y(() => {
      this.z(key, scope, target);
      this.P(scope)?.set(key, value, external);
    });
  }
  remove(key, scope, external = false) {
    this.y(() => {
      this.z(key, scope, void 0);
      this.P(scope)?.delete(key, external);
    });
  }
  y(fn) {
    this.b.pause();
    this.c.pause();
    try {
      fn();
    } finally {
      this.b.resume();
      this.c.resume();
    }
  }
  keys(scope, target) {
    const keys = [];
    const keyTargets = this.J(scope);
    for (const key of Object.keys(keyTargets)) {
      const keyTarget = keyTargets[key];
      if (keyTarget === target) {
        keys.push(key);
      }
    }
    return keys;
  }
  z(key, scope, target, external = false) {
    const keyTargets = this.J(scope);
    if (typeof target === "number") {
      if (keyTargets[key] !== target) {
        keyTargets[key] = target;
        this.P(scope)?.set($iv, JSON.stringify(keyTargets), external);
      }
    } else {
      if (typeof keyTargets[key] === "number") {
        delete keyTargets[key];
        this.P(scope)?.set($iv, JSON.stringify(keyTargets), external);
      }
    }
  }
  get D() {
    if (!this.C) {
      this.C = this.L(
        1
        /* StorageScope.WORKSPACE */
      );
    }
    return this.C;
  }
  get G() {
    if (!this.F) {
      this.F = this.L(
        0
        /* StorageScope.PROFILE */
      );
    }
    return this.F;
  }
  get I() {
    if (!this.H) {
      this.H = this.L(
        -1
        /* StorageScope.APPLICATION */
      );
    }
    return this.H;
  }
  J(scope) {
    switch (scope) {
      case -1:
        return this.I;
      case 0:
        return this.G;
      default:
        return this.D;
    }
  }
  L(scope) {
    const storage = this.P(scope);
    return storage ? $kv(storage) : /* @__PURE__ */ Object.create(null);
  }
  isNew(scope) {
    return this.getBoolean($hv, scope) === true;
  }
  async flush(reason = WillSaveStateReason.NONE) {
    this.f.fire({ reason });
    const applicationStorage = this.P(
      -1
      /* StorageScope.APPLICATION */
    );
    const profileStorage = this.P(
      0
      /* StorageScope.PROFILE */
    );
    const workspaceStorage = this.P(
      1
      /* StorageScope.WORKSPACE */
    );
    switch (reason) {
      case WillSaveStateReason.NONE:
        await Promises.settled([
          applicationStorage?.whenFlushed() ?? Promise.resolve(),
          profileStorage?.whenFlushed() ?? Promise.resolve(),
          workspaceStorage?.whenFlushed() ?? Promise.resolve()
        ]);
        break;
      case WillSaveStateReason.SHUTDOWN:
        await Promises.settled([
          applicationStorage?.flush(0) ?? Promise.resolve(),
          profileStorage?.flush(0) ?? Promise.resolve(),
          workspaceStorage?.flush(0) ?? Promise.resolve()
        ]);
        break;
    }
  }
  async log() {
    const applicationItems = this.P(
      -1
      /* StorageScope.APPLICATION */
    )?.items ?? /* @__PURE__ */ new Map();
    const profileItems = this.P(
      0
      /* StorageScope.PROFILE */
    )?.items ?? /* @__PURE__ */ new Map();
    const workspaceItems = this.P(
      1
      /* StorageScope.WORKSPACE */
    )?.items ?? /* @__PURE__ */ new Map();
    return $ov(applicationItems, profileItems, workspaceItems, this.Q(
      -1
      /* StorageScope.APPLICATION */
    ) ?? "", this.Q(
      0
      /* StorageScope.PROFILE */
    ) ?? "", this.Q(
      1
      /* StorageScope.WORKSPACE */
    ) ?? "");
  }
  async optimize(scope) {
    await this.flush();
    return this.P(scope)?.optimize();
  }
  async switch(to, preserveData) {
    this.w(WillSaveStateReason.NONE);
    if ($qs(to)) {
      return this.R(to, preserveData);
    }
    return this.S(to, preserveData);
  }
  M(from, to) {
    if (from.id === to.id) {
      return false;
    }
    if ($mv(to) && $mv(from)) {
      return false;
    }
    return true;
  }
  N(oldStorage, newStorage, scope) {
    this.y(() => {
      const handledkeys = /* @__PURE__ */ new Set();
      for (const [key, oldValue] of oldStorage) {
        handledkeys.add(key);
        const newValue = newStorage.get(key);
        if (newValue !== oldValue) {
          this.u(scope, { key, external: true });
        }
      }
      for (const [key] of newStorage.items) {
        if (!handledkeys.has(key)) {
          this.u(scope, { key, external: true });
        }
      }
    });
  }
};
function $mv(profile) {
  return profile.isDefault || !!profile.useDefaultFlags?.globalState;
}
async function $ov(application, profile, workspace, applicationPath, profilePath, workspacePath) {
  const safeParse = (value) => {
    try {
      return JSON.parse(value);
    } catch (error) {
      return value;
    }
  };
  const applicationItems = /* @__PURE__ */ new Map();
  const applicationItemsParsed = /* @__PURE__ */ new Map();
  application.forEach((value, key) => {
    applicationItems.set(key, value);
    applicationItemsParsed.set(key, safeParse(value));
  });
  const profileItems = /* @__PURE__ */ new Map();
  const profileItemsParsed = /* @__PURE__ */ new Map();
  profile.forEach((value, key) => {
    profileItems.set(key, value);
    profileItemsParsed.set(key, safeParse(value));
  });
  const workspaceItems = /* @__PURE__ */ new Map();
  const workspaceItemsParsed = /* @__PURE__ */ new Map();
  workspace.forEach((value, key) => {
    workspaceItems.set(key, value);
    workspaceItemsParsed.set(key, safeParse(value));
  });
  if (applicationPath !== profilePath) {
    console.group(`Storage: Application (path: ${applicationPath})`);
  } else {
    console.group(`Storage: Application & Profile (path: ${applicationPath}, default profile)`);
  }
  const applicationValues = [];
  applicationItems.forEach((value, key) => {
    applicationValues.push({ key, value });
  });
  console.table(applicationValues);
  console.groupEnd();
  console.log(applicationItemsParsed);
  if (applicationPath !== profilePath) {
    console.group(`Storage: Profile (path: ${profilePath}, profile specific)`);
    const profileValues = [];
    profileItems.forEach((value, key) => {
      profileValues.push({ key, value });
    });
    console.table(profileValues);
    console.groupEnd();
    console.log(profileItemsParsed);
  }
  console.group(`Storage: Workspace (path: ${workspacePath})`);
  const workspaceValues = [];
  workspaceItems.forEach((value, key) => {
    workspaceValues.push({ key, value });
  });
  console.table(workspaceValues);
  console.groupEnd();
  console.log(workspaceItemsParsed);
}

// out-build/vs/workbench/contrib/chat/common/chatContextKeys.js
var ChatContextKeys;
(function(ChatContextKeys2) {
  ChatContextKeys2.responseVote = new $nn("chatSessionResponseVote", "", { type: "string", description: localize(5076, null) });
  ChatContextKeys2.responseDetectedAgentCommand = new $nn("chatSessionResponseDetectedAgentOrCommand", false, { type: "boolean", description: localize(5077, null) });
  ChatContextKeys2.responseSupportsIssueReporting = new $nn("chatResponseSupportsIssueReporting", false, { type: "boolean", description: localize(5078, null) });
  ChatContextKeys2.responseIsFiltered = new $nn("chatSessionResponseFiltered", false, { type: "boolean", description: localize(5079, null) });
  ChatContextKeys2.responseHasError = new $nn("chatSessionResponseError", false, { type: "boolean", description: localize(5080, null) });
  ChatContextKeys2.requestInProgress = new $nn("chatSessionRequestInProgress", false, { type: "boolean", description: localize(5081, null) });
  ChatContextKeys2.isResponse = new $nn("chatResponse", false, { type: "boolean", description: localize(5082, null) });
  ChatContextKeys2.isRequest = new $nn("chatRequest", false, { type: "boolean", description: localize(5083, null) });
  ChatContextKeys2.itemId = new $nn("chatItemId", "", { type: "string", description: localize(5084, null) });
  ChatContextKeys2.lastItemId = new $nn("chatLastItemId", [], { type: "string", description: localize(5085, null) });
  ChatContextKeys2.editApplied = new $nn("chatEditApplied", false, { type: "boolean", description: localize(5086, null) });
  ChatContextKeys2.inputHasText = new $nn("chatInputHasText", false, { type: "boolean", description: localize(5087, null) });
  ChatContextKeys2.inputHasFocus = new $nn("chatInputHasFocus", false, { type: "boolean", description: localize(5088, null) });
  ChatContextKeys2.inChatInput = new $nn("inChatInput", false, { type: "boolean", description: localize(5089, null) });
  ChatContextKeys2.inChatSession = new $nn("inChat", false, { type: "boolean", description: localize(5090, null) });
  ChatContextKeys2.enabled = new $nn("chatIsEnabled", false, { type: "boolean", description: localize(5091, null) });
  ChatContextKeys2.panelParticipantRegistered = new $nn("chatPanelParticipantRegistered", false, { type: "boolean", description: localize(5092, null) });
  ChatContextKeys2.editingParticipantRegistered = new $nn("chatEditingParticipantRegistered", false, { type: "boolean", description: localize(5093, null) });
  ChatContextKeys2.chatEditingCanUndo = new $nn("chatEditingCanUndo", false, { type: "boolean", description: localize(5094, null) });
  ChatContextKeys2.chatEditingCanRedo = new $nn("chatEditingCanRedo", false, { type: "boolean", description: localize(5095, null) });
  ChatContextKeys2.extensionInvalid = new $nn("chatExtensionInvalid", false, { type: "boolean", description: localize(5096, null) });
  ChatContextKeys2.inputCursorAtTop = new $nn("chatCursorAtTop", false);
  ChatContextKeys2.inputHasAgent = new $nn("chatInputHasAgent", false);
  ChatContextKeys2.location = new $nn("chatLocation", void 0);
  ChatContextKeys2.inQuickChat = new $nn("quickChatHasFocus", false, { type: "boolean", description: localize(5097, null) });
  ChatContextKeys2.hasFileAttachments = new $nn("chatHasFileAttachments", false, { type: "boolean", description: localize(5098, null) });
  ChatContextKeys2.languageModelsAreUserSelectable = new $nn("chatModelsAreUserSelectable", false, { type: "boolean", description: localize(5099, null) });
  ChatContextKeys2.Setup = {
    canSignUp: new $nn("chatSetupCanSignUp", false, true),
    // True when user can sign up to be a chat limited user.
    signedOut: new $nn("chatSetupSignedOut", false, true),
    // True when user is signed out.
    limited: new $nn("chatSetupLimited", false, true),
    // True when user is a chat limited user.
    triggered: new $nn("chatSetupTriggered", false, true),
    // True when chat setup is triggered.
    installed: new $nn("chatSetupInstalled", false, true)
    // True when the chat extension is installed.
  };
  ChatContextKeys2.chatQuotaExceeded = new $nn("chatQuotaExceeded", false, true);
  ChatContextKeys2.completionsQuotaExceeded = new $nn("completionsQuotaExceeded", false, true);
})(ChatContextKeys || (ChatContextKeys = {}));

// out-build/vs/workbench/contrib/chat/common/chatAgents.js
var $4O_1;
var ChatAgentLocation;
(function(ChatAgentLocation2) {
  ChatAgentLocation2["Panel"] = "panel";
  ChatAgentLocation2["Terminal"] = "terminal";
  ChatAgentLocation2["Notebook"] = "notebook";
  ChatAgentLocation2["Editor"] = "editor";
  ChatAgentLocation2["EditingSession"] = "editing-session";
})(ChatAgentLocation || (ChatAgentLocation = {}));
(function(ChatAgentLocation2) {
  function fromRaw(value) {
    switch (value) {
      case "panel":
        return ChatAgentLocation2.Panel;
      case "terminal":
        return ChatAgentLocation2.Terminal;
      case "notebook":
        return ChatAgentLocation2.Notebook;
      case "editor":
        return ChatAgentLocation2.Editor;
      case "editing-session":
        return ChatAgentLocation2.EditingSession;
    }
    return ChatAgentLocation2.Panel;
  }
  ChatAgentLocation2.fromRaw = fromRaw;
})(ChatAgentLocation || (ChatAgentLocation = {}));
var $ZO = $Qk("chatAgentService");
var $1O = class $1O2 extends $3c {
  static {
    this.AGENT_LEADER = "@";
  }
  constructor(r) {
    super();
    this.r = r;
    this.b = /* @__PURE__ */ new Map();
    this.f = new $ze();
    this.onDidChangeAgents = this.f.event;
    this.g = /* @__PURE__ */ new Set();
    this.n = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.h = ChatContextKeys.enabled.bindTo(this.r);
    this.j = ChatContextKeys.panelParticipantRegistered.bindTo(this.r);
    this.m = ChatContextKeys.editingParticipantRegistered.bindTo(this.r);
    this.B(r.onDidChangeContext((e) => {
      if (e.affectsSome(this.g)) {
        this.t();
      }
    }));
  }
  registerAgent(id2, data) {
    const existingAgent = this.getAgent(id2);
    if (existingAgent) {
      throw new Error(`Agent already registered: ${JSON.stringify(id2)}`);
    }
    const that = this;
    const commands = data.slashCommands;
    data = {
      ...data,
      get slashCommands() {
        return commands.filter((c) => !c.when || that.r.contextMatchesRules($7m.deserialize(c.when)));
      }
    };
    const entry = { data };
    this.b.set(id2, entry);
    this.s();
    this.t();
    this.f.fire(void 0);
    return $1c(() => {
      this.b.delete(id2);
      this.s();
      this.t();
      this.f.fire(void 0);
    });
  }
  s() {
    this.g.clear();
    for (const agent of this.b.values()) {
      if (agent.data.when) {
        const expr = $7m.deserialize(agent.data.when);
        for (const key of expr?.keys() || []) {
          this.g.add(key);
        }
      }
    }
  }
  t() {
    let editingAgentRegistered = false;
    let defaultAgentRegistered = false;
    for (const agent of this.getAgents()) {
      if (agent.isDefault && agent.locations.includes(ChatAgentLocation.EditingSession)) {
        editingAgentRegistered = true;
      } else if (agent.isDefault) {
        defaultAgentRegistered = true;
      }
    }
    this.m.set(editingAgentRegistered);
    this.j.set(defaultAgentRegistered);
  }
  registerAgentImplementation(id2, agentImpl) {
    const entry = this.b.get(id2);
    if (!entry) {
      throw new Error(`Unknown agent: ${JSON.stringify(id2)}`);
    }
    if (entry.impl) {
      throw new Error(`Agent already has implementation: ${JSON.stringify(id2)}`);
    }
    if (entry.data.isDefault) {
      this.h.set(true);
    }
    entry.impl = agentImpl;
    this.f.fire(new $2O(entry.data, agentImpl));
    return $1c(() => {
      entry.impl = void 0;
      this.f.fire(void 0);
      if (entry.data.isDefault) {
        this.h.set(false);
      }
    });
  }
  registerDynamicAgent(data, agentImpl) {
    data.isDynamic = true;
    const agent = { data, impl: agentImpl };
    this.b.set(data.id, agent);
    this.f.fire(new $2O(data, agentImpl));
    return $1c(() => {
      this.b.delete(data.id);
      this.f.fire(void 0);
    });
  }
  registerAgentCompletionProvider(id2, provider) {
    this.u.set(id2, provider);
    return {
      dispose: () => {
        this.u.delete(id2);
      }
    };
  }
  async getAgentCompletionItems(id2, query, token) {
    return await this.u.get(id2)?.(query, token) ?? [];
  }
  updateAgent(id2, updateMetadata) {
    const agent = this.b.get(id2);
    if (!agent?.impl) {
      throw new Error(`No activated agent with id ${JSON.stringify(id2)} registered`);
    }
    agent.data.metadata = { ...agent.data.metadata, ...updateMetadata };
    this.f.fire(new $2O(agent.data, agent.impl));
  }
  getDefaultAgent(location2) {
    return $1(this.getActivatedAgents(), (a) => !!a.isDefault && a.locations.includes(location2));
  }
  getContributedDefaultAgent(location2) {
    return this.getAgents().find((a) => !!a.isDefault && a.locations.includes(location2));
  }
  getSecondaryAgent() {
    return Iterable.find(this.b.values(), (a) => !!a.data.metadata.isSecondary)?.data;
  }
  getAgent(id2, includeDisabled = false) {
    if (!this.w(id2) && !includeDisabled) {
      return;
    }
    return this.b.get(id2)?.data;
  }
  w(id2) {
    const entry = this.b.get(id2);
    return !entry?.data.when || this.r.contextMatchesRules($7m.deserialize(entry.data.when));
  }
  getAgentByFullyQualifiedId(id2) {
    const agent = Iterable.find(this.b.values(), (a) => $5O(a.data) === id2)?.data;
    if (agent && !this.w(agent.id)) {
      return;
    }
    return agent;
  }
  /**
   * Returns all agent datas that exist- static registered and dynamic ones.
   */
  getAgents() {
    return Array.from(this.b.values()).map((entry) => entry.data).filter((a) => this.w(a.id));
  }
  getActivatedAgents() {
    return Array.from(this.b.values()).filter((a) => !!a.impl).filter((a) => this.w(a.data.id)).map((a) => new $2O(a.data, a.impl));
  }
  getAgentsByName(name) {
    return this.getAgents().filter((a) => a.name === name);
  }
  agentHasDupeName(id2) {
    const agent = this.getAgent(id2);
    if (!agent) {
      return false;
    }
    return this.getAgentsByName(agent.name).filter((a) => a.extensionId.value !== agent.extensionId.value).length > 0;
  }
  async invokeAgent(id2, request, progress, history, token) {
    const data = this.b.get(id2);
    if (!data?.impl) {
      throw new Error(`No activated agent with id "${id2}"`);
    }
    return await data.impl.invoke(request, progress, history, token);
  }
  async getFollowups(id2, request, result, history, token) {
    const data = this.b.get(id2);
    if (!data?.impl) {
      throw new Error(`No activated agent with id "${id2}"`);
    }
    if (!data.impl?.provideFollowups) {
      return [];
    }
    return data.impl.provideFollowups(request, result, history, token);
  }
  async getChatTitle(id2, history, token) {
    const data = this.b.get(id2);
    if (!data?.impl) {
      throw new Error(`No activated agent with id "${id2}"`);
    }
    if (!data.impl?.provideChatTitle) {
      return void 0;
    }
    return data.impl.provideChatTitle(history, token);
  }
  registerChatParticipantDetectionProvider(handle, provider) {
    this.n.set(handle, provider);
    return $1c(() => {
      this.n.delete(handle);
    });
  }
  hasChatParticipantDetectionProviders() {
    return this.n.size > 0;
  }
  async detectAgentOrCommand(request, history, options2, token) {
    const provider = Iterable.first(this.n.values());
    if (!provider) {
      return;
    }
    const participants = this.getAgents().reduce((acc, a) => {
      if (a.locations.includes(options2.location)) {
        acc.push({ participant: a.id, disambiguation: a.disambiguation ?? [] });
        for (const command2 of a.slashCommands) {
          acc.push({ participant: a.id, command: command2.name, disambiguation: command2.disambiguation ?? [] });
        }
      }
      return acc;
    }, []);
    const result = await provider.provideParticipantDetection(request, history, { ...options2, participants }, token);
    if (!result) {
      return;
    }
    const agent = this.getAgent(result.participant);
    if (!agent) {
      return;
    }
    if (!result.command) {
      return { agent };
    }
    const command = agent?.slashCommands.find((c) => c.name === result.command);
    if (!command) {
      return;
    }
    return { agent, command };
  }
};
$1O = __decorate([
  __param(0, $on)
], $1O);
var $2O = class {
  constructor(b, d) {
    this.b = b;
    this.d = d;
  }
  get id() {
    return this.b.id;
  }
  get name() {
    return this.b.name ?? "";
  }
  get fullName() {
    return this.b.fullName ?? "";
  }
  get description() {
    return this.b.description ?? "";
  }
  get extensionId() {
    return this.b.extensionId;
  }
  get extensionPublisherId() {
    return this.b.extensionPublisherId;
  }
  get extensionPublisherDisplayName() {
    return this.b.publisherDisplayName;
  }
  get extensionDisplayName() {
    return this.b.extensionDisplayName;
  }
  get isDefault() {
    return this.b.isDefault;
  }
  get metadata() {
    return this.b.metadata;
  }
  get slashCommands() {
    return this.b.slashCommands;
  }
  get locations() {
    return this.b.locations;
  }
  get disambiguation() {
    return this.b.disambiguation;
  }
  async invoke(request, progress, history, token) {
    return this.d.invoke(request, progress, history, token);
  }
  async provideFollowups(request, result, history, token) {
    if (this.d.provideFollowups) {
      return this.d.provideFollowups(request, result, history, token);
    }
    return [];
  }
  provideWelcomeMessage(token) {
    if (this.d.provideWelcomeMessage) {
      return this.d.provideWelcomeMessage(token);
    }
    return void 0;
  }
  provideSampleQuestions(location2, token) {
    if (this.d.provideSampleQuestions) {
      return this.d.provideSampleQuestions(location2, token);
    }
    return void 0;
  }
  toJSON() {
    return this.b;
  }
};
var $3O = $Qk("chatAgentNameService");
var $4O = class $4O2 {
  static {
    $4O_1 = this;
  }
  static {
    this.b = "chat.participantNameRegistry";
  }
  constructor(productService, h, i, j) {
    this.h = h;
    this.i = i;
    this.j = j;
    this.f = $he(this, /* @__PURE__ */ Object.create(null));
    this.g = false;
    if (!productService.chatParticipantRegistry) {
      return;
    }
    this.d = productService.chatParticipantRegistry;
    const raw = j.get(
      $4O_1.b,
      -1
      /* StorageScope.APPLICATION */
    );
    try {
      this.f.set(JSON.parse(raw ?? "{}"), void 0);
    } catch (err) {
      j.remove(
        $4O_1.b,
        -1
        /* StorageScope.APPLICATION */
      );
    }
    this.k();
  }
  k() {
    if (this.g) {
      return;
    }
    this.l().catch((err) => this.i.warn("Failed to fetch chat participant registry", err)).then(() => $Wh(5 * 60 * 1e3)).then(() => this.k());
  }
  async l() {
    const context = await this.h.request({ type: "GET", url: this.d }, CancellationToken.None);
    if (context.res.statusCode !== 200) {
      throw new Error("Could not get extensions report.");
    }
    const result = await $cv(context);
    if (!result || result.version !== 1) {
      throw new Error("Unexpected chat participant registry response.");
    }
    const registry = result.restrictedChatParticipants;
    this.f.set(registry, void 0);
    this.j.store(
      $4O_1.b,
      JSON.stringify(registry),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  /**
   * Returns true if the agent is allowed to use this name
   */
  getAgentNameRestriction(chatAgentData) {
    const nameAllowed = this.m(chatAgentData.name, chatAgentData).get();
    const fullNameAllowed = !chatAgentData.fullName || this.m(chatAgentData.fullName.replace(/\s/g, ""), chatAgentData).get();
    return nameAllowed && fullNameAllowed;
  }
  m(name, chatAgentData) {
    const allowList = this.f.map((registry) => registry[name.toLowerCase()]);
    return allowList.map((allowList2) => {
      if (!allowList2) {
        return true;
      }
      return allowList2.some((id2) => $1f(id2, id2.includes(".") ? chatAgentData.extensionId.value : chatAgentData.extensionPublisherId));
    });
  }
  dispose() {
    this.g = true;
  }
};
$4O = $4O_1 = __decorate([
  __param(0, $Vu),
  __param(1, $9u),
  __param(2, $wn),
  __param(3, $jv)
], $4O);
function $5O(chatAgentData) {
  return `${chatAgentData.extensionId.value}.${chatAgentData.id}`;
}

// out-build/vs/base/common/glob.js
function $yl() {
  return /* @__PURE__ */ Object.create(null);
}
var $zl = "**";
var $Al = "/";
var PATH_REGEX = "[/\\\\]";
var NO_PATH_REGEX = "[^/\\\\]";
var 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 $Bl(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 = $Bl(pattern, $Al);
  if (segments.every((segment) => segment === $zl)) {
    regEx = ".*";
  } else {
    let previousSegmentWasGlobStar = false;
    segments.forEach((segment, index) => {
      if (segment === $zl) {
        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 === $Al) {
              res = "";
            } else {
              res = $Af(char);
            }
            bracketVal += res;
            continue;
          }
          switch (char) {
            case "{":
              inBraces = true;
              continue;
            case "[":
              inBrackets = true;
              continue;
            case "}": {
              const choices = $Bl(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 += $Af(char);
          }
        }
        if (index < segments.length - 1 && // more segments to come after this
        (segments[index + 1] !== $zl || // next segment is not **, or...
        index + 2 < segments.length)) {
          regEx += PATH_REGEX;
        }
      }
      previousSegmentWasGlobStar = segment === $zl;
    });
  }
  return regEx;
}
var T1 = /^\*\*\/\*\.[\w\.-]+$/;
var T2 = /^\*\*\/([\w\.-]+)\/?$/;
var T3 = /^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/;
var T3_2 = /^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/;
var T4 = /^\*\*((\/[\w\.-]+)+)\/?$/;
var T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/;
var CACHE = new $Hc(1e4);
var FALSE = function() {
  return false;
};
var NULL = function() {
  return null;
};
function parsePattern(arg1, options2) {
  if (!arg1) {
    return NULL;
  }
  let pattern;
  if (typeof arg1 !== "string") {
    pattern = arg1.pattern;
  } else {
    pattern = arg1;
  }
  pattern = pattern.trim();
  const patternKey = `${pattern}_${!!options2.trimForExclusions}`;
  let parsedPattern = CACHE.get(patternKey);
  if (parsedPattern) {
    return wrapRelativePattern(parsedPattern, arg1);
  }
  let match;
  if (T1.test(pattern)) {
    parsedPattern = trivia1(pattern.substr(4), pattern);
  } else if (match = T2.exec(trimForExclusions(pattern, options2))) {
    parsedPattern = trivia2(match[1], pattern);
  } else if ((options2.trimForExclusions ? T3_2 : T3).test(pattern)) {
    parsedPattern = trivia3(pattern, options2);
  } else if (match = T4.exec(trimForExclusions(pattern, options2))) {
    parsedPattern = trivia4and5(match[1].substr(1), pattern, true);
  } else if (match = T5.exec(trimForExclusions(pattern, options2))) {
    parsedPattern = trivia4and5(match[1], pattern, false);
  } else {
    parsedPattern = toRegExp(pattern);
  }
  CACHE.set(patternKey, parsedPattern);
  return wrapRelativePattern(parsedPattern, arg1);
}
function wrapRelativePattern(parsedPattern, arg2) {
  if (typeof arg2 === "string") {
    return parsedPattern;
  }
  const wrappedPattern = function(path, basename) {
    if (!$Zg(path, arg2.base, !$n)) {
      return null;
    }
    return parsedPattern($Ff(path.substr(arg2.base.length), sep), basename);
  };
  wrappedPattern.allBasenames = parsedPattern.allBasenames;
  wrappedPattern.allPaths = parsedPattern.allPaths;
  wrappedPattern.basenames = parsedPattern.basenames;
  wrappedPattern.patterns = parsedPattern.patterns;
  return wrappedPattern;
}
function trimForExclusions(pattern, options2) {
  return options2.trimForExclusions && pattern.endsWith("/**") ? pattern.substr(0, pattern.length - 2) : pattern;
}
function trivia1(base, pattern) {
  return function(path, basename) {
    return typeof path === "string" && path.endsWith(base) ? pattern : null;
  };
}
function trivia2(base, pattern) {
  const slashBase = `/${base}`;
  const backslashBase = `\\${base}`;
  const parsedPattern = function(path, basename) {
    if (typeof path !== "string") {
      return null;
    }
    if (basename) {
      return basename === base ? pattern : null;
    }
    return path === base || path.endsWith(slashBase) || path.endsWith(backslashBase) ? pattern : null;
  };
  const basenames = [base];
  parsedPattern.basenames = basenames;
  parsedPattern.patterns = [pattern];
  parsedPattern.allBasenames = basenames;
  return parsedPattern;
}
function trivia3(pattern, options2) {
  const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(",").map((pattern2) => parsePattern(pattern2, options2)).filter((pattern2) => pattern2 !== NULL), pattern);
  const patternsLength = parsedPatterns.length;
  if (!patternsLength) {
    return NULL;
  }
  if (patternsLength === 1) {
    return parsedPatterns[0];
  }
  const parsedPattern = function(path, basename) {
    for (let i = 0, n = parsedPatterns.length; i < n; i++) {
      if (parsedPatterns[i](path, basename)) {
        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 === $kc.sep;
  const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, sep);
  const nativePathEnd = sep + nativePath;
  const targetPathEnd = $kc.sep + targetPath;
  let parsedPattern;
  if (matchPathEnds) {
    parsedPattern = function(path, basename) {
      return typeof path === "string" && (path === nativePath || path.endsWith(nativePathEnd) || !usingPosixSep && (path === targetPath || path.endsWith(targetPathEnd))) ? pattern : null;
    };
  } else {
    parsedPattern = function(path, basename) {
      return typeof path === "string" && (path === nativePath || !usingPosixSep && path === targetPath) ? pattern : null;
    };
  }
  parsedPattern.allPaths = [(matchPathEnds ? "*/" : "./") + targetPath];
  return parsedPattern;
}
function toRegExp(pattern) {
  try {
    const regExp = new RegExp(`^${parseRegExp(pattern)}$`);
    return function(path) {
      regExp.lastIndex = 0;
      return typeof path === "string" && regExp.test(path) ? pattern : null;
    };
  } catch (error) {
    return NULL;
  }
}
function $Cl(arg1, path, hasSibling) {
  if (!arg1 || typeof path !== "string") {
    return false;
  }
  return $Dl(arg1)(path, void 0, hasSibling);
}
function $Dl(arg1, options2 = {}) {
  if (!arg1) {
    return FALSE;
  }
  if (typeof arg1 === "string" || $El(arg1)) {
    const parsedPattern = parsePattern(arg1, options2);
    if (parsedPattern === NULL) {
      return FALSE;
    }
    const resultPattern = function(path, basename) {
      return !!parsedPattern(path, basename);
    };
    if (parsedPattern.allBasenames) {
      resultPattern.allBasenames = parsedPattern.allBasenames;
    }
    if (parsedPattern.allPaths) {
      resultPattern.allPaths = parsedPattern.allPaths;
    }
    return resultPattern;
  }
  return parsedExpression(arg1, options2);
}
function $El(obj) {
  const rp = obj;
  if (!rp) {
    return false;
  }
  return typeof rp.base === "string" && typeof rp.pattern === "string";
}
function $Fl(patternOrExpression) {
  return patternOrExpression.allBasenames || [];
}
function $Gl(patternOrExpression) {
  return patternOrExpression.allPaths || [];
}
function parsedExpression(expression, options2) {
  const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression).map((pattern) => parseExpressionPattern(pattern, expression[pattern], options2)).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(path, basename) {
      let resultPromises = void 0;
      for (let i = 0, n = parsedPatterns.length; i < n; i++) {
        const result = parsedPatterns[i](path, basename);
        if (typeof result === "string") {
          return result;
        }
        if ($Gh(result)) {
          if (!resultPromises) {
            resultPromises = [];
          }
          resultPromises.push(result);
        }
      }
      if (resultPromises) {
        return (async () => {
          for (const resultPromise of resultPromises) {
            const result = await resultPromise;
            if (typeof result === "string") {
              return result;
            }
          }
          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(path, base, hasSibling) {
    let name = void 0;
    let resultPromises = void 0;
    for (let i = 0, n = parsedPatterns.length; i < n; i++) {
      const parsedPattern = parsedPatterns[i];
      if (parsedPattern.requiresSiblings && hasSibling) {
        if (!base) {
          base = $rc(path);
        }
        if (!name) {
          name = base.substr(0, base.length - $sc(path).length);
        }
      }
      const result = parsedPattern(path, base, name, hasSibling);
      if (typeof result === "string") {
        return result;
      }
      if ($Gh(result)) {
        if (!resultPromises) {
          resultPromises = [];
        }
        resultPromises.push(result);
      }
    }
    if (resultPromises) {
      return (async () => {
        for (const resultPromise of resultPromises) {
          const result = await resultPromise;
          if (typeof result === "string") {
            return result;
          }
        }
        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, options2) {
  if (value === false) {
    return NULL;
  }
  const parsedPattern = parsePattern(pattern, options2);
  if (parsedPattern === NULL) {
    return NULL;
  }
  if (typeof value === "boolean") {
    return parsedPattern;
  }
  if (value) {
    const when = value.when;
    if (typeof when === "string") {
      const result = (path, basename, name, hasSibling) => {
        if (!hasSibling || !parsedPattern(path, basename)) {
          return null;
        }
        const clausePattern = when.replace("$(basename)", () => name);
        const matched = hasSibling(clausePattern);
        return $Gh(matched) ? matched.then((match) => match ? pattern : null) : matched ? pattern : null;
      };
      result.requiresSiblings = true;
      return result;
    }
  }
  return parsedPattern;
}
function aggregateBasenameMatches(parsedPatterns, result) {
  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 (result) {
    patterns = [];
    for (let i = 0, n = basenames.length; i < n; i++) {
      patterns.push(result);
    }
  } else {
    patterns = basenamePatterns.reduce((all, current) => {
      const patterns2 = current.patterns;
      return patterns2 ? all.concat(patterns2) : all;
    }, []);
  }
  const aggregate = function(path, basename) {
    if (typeof path !== "string") {
      return null;
    }
    if (!basename) {
      let i;
      for (i = path.length; i > 0; i--) {
        const ch = path.charCodeAt(i - 1);
        if (ch === 47 || ch === 92) {
          break;
        }
      }
      basename = path.substr(i);
    }
    const index = basenames.indexOf(basename);
    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 $Hl(patternsA, patternsB) {
  return $zb(patternsA, patternsB, (a, b) => {
    if (typeof a === "string" && typeof b === "string") {
      return a === b;
    }
    if (typeof a !== "string" && typeof b !== "string") {
      return a.base === b.base && a.pattern === b.pattern;
    }
    return false;
  });
}

// out-build/vs/workbench/services/notebook/common/notebookDocumentService.js
var $8L = $Qk("notebookDocumentService");
var _lengths = ["W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f"];
var _padRegexp = new RegExp(`^[${_lengths.join("")}]+`);
var _radix = 7;
function $9L(cell) {
  if (cell.scheme !== Schemas.vscodeNotebookCell) {
    return void 0;
  }
  const idx = cell.fragment.indexOf("s");
  if (idx < 0) {
    return void 0;
  }
  const handle = parseInt(cell.fragment.substring(0, idx).replace(_padRegexp, ""), _radix);
  const _scheme = $Vi(cell.fragment.substring(idx + 1)).toString();
  if (isNaN(handle)) {
    return void 0;
  }
  return {
    handle,
    notebook: cell.with({ scheme: _scheme, fragment: null })
  };
}
function $0L(notebook, handle) {
  const s = handle.toString(_radix);
  const p = s.length < _lengths.length ? _lengths[s.length - 1] : "z";
  const fragment = `${p}${s}s${$Wi($Ci.fromString(notebook.scheme), true, true)}`;
  return notebook.with({ scheme: Schemas.vscodeNotebookCell, fragment });
}
function $$L(metadata) {
  if (metadata.scheme !== Schemas.vscodeNotebookMetadata) {
    return void 0;
  }
  const _scheme = $Vi(metadata.fragment).toString();
  return metadata.with({ scheme: _scheme, fragment: null });
}
function $_L(notebook) {
  const fragment = `${$Wi($Ci.fromString(notebook.scheme), true, true)}`;
  return notebook.with({ scheme: Schemas.vscodeNotebookMetadata, fragment });
}
var $aM = class {
  constructor() {
    this.a = new $Ec();
  }
  getNotebook(uri) {
    if (uri.scheme === Schemas.vscodeNotebookCell) {
      const cellUri = $9L(uri);
      if (cellUri) {
        const document2 = this.a.get(cellUri.notebook);
        if (document2) {
          return document2;
        }
      }
    }
    return this.a.get(uri);
  }
  addNotebookDocument(document2) {
    this.a.set(document2.uri, document2);
  }
  removeNotebookDocument(document2) {
    this.a.delete(document2.uri);
  }
};
$SC(
  $8L,
  $aM,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/notebook/common/notebookCommon.js
var CellKind;
(function(CellKind2) {
  CellKind2[CellKind2["Markup"] = 1] = "Markup";
  CellKind2[CellKind2["Code"] = 2] = "Code";
})(CellKind || (CellKind = {}));
var $hM = [
  "application/json",
  "application/javascript",
  "text/html",
  "image/svg+xml",
  $YC.latex,
  $YC.markdown,
  "image/png",
  "image/jpeg",
  $YC.text
];
var $iM = [
  $YC.latex,
  $YC.markdown,
  "application/json",
  "text/html",
  "image/svg+xml",
  "image/png",
  "image/jpeg",
  $YC.text
];
var NotebookRunState;
(function(NotebookRunState2) {
  NotebookRunState2[NotebookRunState2["Running"] = 1] = "Running";
  NotebookRunState2[NotebookRunState2["Idle"] = 2] = "Idle";
})(NotebookRunState || (NotebookRunState = {}));
var NotebookCellExecutionState;
(function(NotebookCellExecutionState4) {
  NotebookCellExecutionState4[NotebookCellExecutionState4["Unconfirmed"] = 1] = "Unconfirmed";
  NotebookCellExecutionState4[NotebookCellExecutionState4["Pending"] = 2] = "Pending";
  NotebookCellExecutionState4[NotebookCellExecutionState4["Executing"] = 3] = "Executing";
})(NotebookCellExecutionState || (NotebookCellExecutionState = {}));
var NotebookExecutionState;
(function(NotebookExecutionState2) {
  NotebookExecutionState2[NotebookExecutionState2["Unconfirmed"] = 1] = "Unconfirmed";
  NotebookExecutionState2[NotebookExecutionState2["Pending"] = 2] = "Pending";
  NotebookExecutionState2[NotebookExecutionState2["Executing"] = 3] = "Executing";
})(NotebookExecutionState || (NotebookExecutionState = {}));
var NotebookRendererMatch;
(function(NotebookRendererMatch2) {
  NotebookRendererMatch2[NotebookRendererMatch2["WithHardKernelDependency"] = 0] = "WithHardKernelDependency";
  NotebookRendererMatch2[NotebookRendererMatch2["WithOptionalKernelDependency"] = 1] = "WithOptionalKernelDependency";
  NotebookRendererMatch2[NotebookRendererMatch2["Pure"] = 2] = "Pure";
  NotebookRendererMatch2[NotebookRendererMatch2["Never"] = 3] = "Never";
})(NotebookRendererMatch || (NotebookRendererMatch = {}));
var RendererMessagingSpec;
(function(RendererMessagingSpec2) {
  RendererMessagingSpec2["Always"] = "always";
  RendererMessagingSpec2["Never"] = "never";
  RendererMessagingSpec2["Optional"] = "optional";
})(RendererMessagingSpec || (RendererMessagingSpec = {}));
var NotebookCellsChangeType;
(function(NotebookCellsChangeType2) {
  NotebookCellsChangeType2[NotebookCellsChangeType2["ModelChange"] = 1] = "ModelChange";
  NotebookCellsChangeType2[NotebookCellsChangeType2["Move"] = 2] = "Move";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellLanguage"] = 5] = "ChangeCellLanguage";
  NotebookCellsChangeType2[NotebookCellsChangeType2["Initialize"] = 6] = "Initialize";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellMetadata"] = 7] = "ChangeCellMetadata";
  NotebookCellsChangeType2[NotebookCellsChangeType2["Output"] = 8] = "Output";
  NotebookCellsChangeType2[NotebookCellsChangeType2["OutputItem"] = 9] = "OutputItem";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellContent"] = 10] = "ChangeCellContent";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeDocumentMetadata"] = 11] = "ChangeDocumentMetadata";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellInternalMetadata"] = 12] = "ChangeCellInternalMetadata";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellMime"] = 13] = "ChangeCellMime";
  NotebookCellsChangeType2[NotebookCellsChangeType2["Unknown"] = 100] = "Unknown";
})(NotebookCellsChangeType || (NotebookCellsChangeType = {}));
var SelectionStateType;
(function(SelectionStateType2) {
  SelectionStateType2[SelectionStateType2["Handle"] = 0] = "Handle";
  SelectionStateType2[SelectionStateType2["Index"] = 1] = "Index";
})(SelectionStateType || (SelectionStateType = {}));
var CellEditType;
(function(CellEditType2) {
  CellEditType2[CellEditType2["Replace"] = 1] = "Replace";
  CellEditType2[CellEditType2["Output"] = 2] = "Output";
  CellEditType2[CellEditType2["Metadata"] = 3] = "Metadata";
  CellEditType2[CellEditType2["CellLanguage"] = 4] = "CellLanguage";
  CellEditType2[CellEditType2["DocumentMetadata"] = 5] = "DocumentMetadata";
  CellEditType2[CellEditType2["Move"] = 6] = "Move";
  CellEditType2[CellEditType2["OutputItems"] = 7] = "OutputItems";
  CellEditType2[CellEditType2["PartialMetadata"] = 8] = "PartialMetadata";
  CellEditType2[CellEditType2["PartialInternalMetadata"] = 9] = "PartialInternalMetadata";
})(CellEditType || (CellEditType = {}));
var NotebookMetadataUri;
(function(NotebookMetadataUri2) {
  NotebookMetadataUri2.scheme = Schemas.vscodeNotebookMetadata;
  function generate(notebook) {
    return $_L(notebook);
  }
  NotebookMetadataUri2.generate = generate;
  function parse2(metadata) {
    return $$L(metadata);
  }
  NotebookMetadataUri2.parse = parse2;
})(NotebookMetadataUri || (NotebookMetadataUri = {}));
var CellUri;
(function(CellUri2) {
  CellUri2.scheme = Schemas.vscodeNotebookCell;
  function generate(notebook, handle) {
    return $0L(notebook, handle);
  }
  CellUri2.generate = generate;
  function parse2(cell) {
    return $9L(cell);
  }
  CellUri2.parse = parse2;
  function generateCellOutputUri(notebook, outputId) {
    return notebook.with({
      scheme: Schemas.vscodeNotebookCellOutput,
      fragment: `op${outputId ?? ""},${notebook.scheme !== Schemas.file ? notebook.scheme : ""}`
    });
  }
  CellUri2.generateCellOutputUri = generateCellOutputUri;
  function parseCellOutputUri(uri) {
    if (uri.scheme !== Schemas.vscodeNotebookCellOutput) {
      return;
    }
    const match = /^op([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})?\,(.*)$/i.exec(uri.fragment);
    if (!match) {
      return void 0;
    }
    const outputId = match[1] && match[1] !== "" ? match[1] : void 0;
    const scheme = match[2];
    return {
      outputId,
      notebook: uri.with({
        scheme: scheme || Schemas.file,
        fragment: null
      })
    };
  }
  CellUri2.parseCellOutputUri = parseCellOutputUri;
  function generateCellPropertyUri(notebook, handle, scheme) {
    return CellUri2.generate(notebook, handle).with({ scheme });
  }
  CellUri2.generateCellPropertyUri = generateCellPropertyUri;
  function parseCellPropertyUri(uri, propertyScheme) {
    if (uri.scheme !== propertyScheme) {
      return void 0;
    }
    return CellUri2.parse(uri.with({ scheme: CellUri2.scheme }));
  }
  CellUri2.parseCellPropertyUri = parseCellPropertyUri;
})(CellUri || (CellUri = {}));
var $nM = new $nn("notebookEditorCursorAtBoundary", "none");
var $oM = new $nn("notebookEditorCursorAtLineBoundary", "none");
var NotebookEditorPriority;
(function(NotebookEditorPriority2) {
  NotebookEditorPriority2["default"] = "default";
  NotebookEditorPriority2["option"] = "option";
})(NotebookEditorPriority || (NotebookEditorPriority = {}));
var NotebookFindScopeType;
(function(NotebookFindScopeType2) {
  NotebookFindScopeType2["Cells"] = "cells";
  NotebookFindScopeType2["Text"] = "text";
  NotebookFindScopeType2["None"] = "none";
})(NotebookFindScopeType || (NotebookFindScopeType = {}));
var CellStatusbarAlignment;
(function(CellStatusbarAlignment2) {
  CellStatusbarAlignment2[CellStatusbarAlignment2["Left"] = 1] = "Left";
  CellStatusbarAlignment2[CellStatusbarAlignment2["Right"] = 2] = "Right";
})(CellStatusbarAlignment || (CellStatusbarAlignment = {}));
var $sM = class _$sM {
  static {
    this.d = "notebook/";
  }
  static create(notebookType, viewType) {
    return `${_$sM.d}${notebookType}/${viewType ?? notebookType}`;
  }
  static parse(candidate) {
    if (candidate.startsWith(_$sM.d)) {
      const split = candidate.substring(_$sM.d.length).split("/");
      if (split.length === 2) {
        return { notebookType: split[0], viewType: split[1] };
      }
    }
    return void 0;
  }
};
function $tM(mimeType) {
  return ["application/vnd.code.notebook.stdout", "application/vnd.code.notebook.stderr"].includes(mimeType);
}
var textDecoder2 = new TextDecoder();
function $uM(outputs) {
  const buffers = [];
  let startAppending = false;
  for (const output of outputs) {
    if (buffers.length === 0 || startAppending) {
      buffers.push(output);
      startAppending = true;
    }
  }
  let didCompression = compressStreamBuffer(buffers);
  const concatenated = $Ci.concat(buffers.map((buffer) => $Ci.wrap(buffer)));
  const data = formatStreamText(concatenated);
  didCompression = didCompression || data.byteLength !== concatenated.byteLength;
  return { data, didCompression };
}
var $vM = `${String.fromCharCode(27)}[A`;
var MOVE_CURSOR_1_LINE_COMMAND_BYTES = $vM.split("").map((c) => c.charCodeAt(0));
var LINE_FEED = 10;
function compressStreamBuffer(streams) {
  let didCompress = false;
  streams.forEach((stream, index) => {
    if (index === 0 || stream.length < $vM.length) {
      return;
    }
    const previousStream = streams[index - 1];
    const command = stream.subarray(0, $vM.length);
    if (command[0] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[0] && command[1] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[1] && command[2] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[2]) {
      const lastIndexOfLineFeed = previousStream.lastIndexOf(LINE_FEED);
      if (lastIndexOfLineFeed === -1) {
        return;
      }
      didCompress = true;
      streams[index - 1] = previousStream.subarray(0, lastIndexOfLineFeed);
      streams[index] = stream.subarray($vM.length);
    }
  });
  return didCompress;
}
function fixBackspace(txt) {
  let tmp = txt;
  do {
    txt = tmp;
    tmp = txt.replace(/[^\n]\x08/gm, "");
  } while (tmp.length < txt.length);
  return txt;
}
function fixCarriageReturn(txt) {
  txt = txt.replace(/\r+\n/gm, "\n");
  while (txt.search(/\r[^$]/g) > -1) {
    const base = txt.match(/^(.*)\r+/m)[1];
    let insert = txt.match(/\r+(.*)$/m)[1];
    insert = insert + base.slice(insert.length, base.length);
    txt = txt.replace(/\r+.*$/m, "\r").replace(/^.*\r/m, insert);
  }
  return txt;
}
var BACKSPACE_CHARACTER = "\b".charCodeAt(0);
var CARRIAGE_RETURN_CHARACTER = "\r".charCodeAt(0);
function formatStreamText(buffer) {
  if (!buffer.buffer.includes(BACKSPACE_CHARACTER) && !buffer.buffer.includes(CARRIAGE_RETURN_CHARACTER)) {
    return buffer;
  }
  return $Ci.fromString(fixCarriageReturn(fixBackspace(textDecoder2.decode(buffer.buffer))));
}

// out-build/vs/workbench/contrib/testing/common/testId.js
var TestIdPathParts;
(function(TestIdPathParts2) {
  TestIdPathParts2["Delimiter"] = "\0";
})(TestIdPathParts || (TestIdPathParts = {}));
var TestPosition;
(function(TestPosition2) {
  TestPosition2[TestPosition2["IsSame"] = 0] = "IsSame";
  TestPosition2[TestPosition2["Disconnected"] = 1] = "Disconnected";
  TestPosition2[TestPosition2["IsChild"] = 2] = "IsChild";
  TestPosition2[TestPosition2["IsParent"] = 3] = "IsParent";
})(TestPosition || (TestPosition = {}));
var $mQ = class _$mQ {
  /**
   * Creates a test ID from an ext host test item.
   */
  static fromExtHostTestItem(item, rootId, parent = item.parent) {
    if (item._isRoot) {
      return new _$mQ([rootId]);
    }
    const path = [item.id];
    for (let i = parent; i && i.id !== rootId; i = i.parent) {
      path.push(i.id);
    }
    path.push(rootId);
    return new _$mQ(path.reverse());
  }
  /**
   * Cheaply ets whether the ID refers to the root .
   */
  static isRoot(idString) {
    return !idString.includes(
      "\0"
      /* TestIdPathParts.Delimiter */
    );
  }
  /**
   * Cheaply gets whether the ID refers to the root .
   */
  static root(idString) {
    const idx = idString.indexOf(
      "\0"
      /* TestIdPathParts.Delimiter */
    );
    return idx === -1 ? idString : idString.slice(0, idx);
  }
  /**
   * Creates a test ID from a serialized TestId instance.
   */
  static fromString(idString) {
    return new _$mQ(idString.split(
      "\0"
      /* TestIdPathParts.Delimiter */
    ));
  }
  /**
   * Gets the ID resulting from adding b to the base ID.
   */
  static join(base, b) {
    return new _$mQ([...base.path, b]);
  }
  /**
   * Gets the string ID resulting from adding b to the base ID.
   */
  static joinToString(base, b) {
    return base.toString() + "\0" + b;
  }
  /**
   * Cheaply gets the parent ID of a test identified with the string.
   */
  static parentId(idString) {
    const idx = idString.lastIndexOf(
      "\0"
      /* TestIdPathParts.Delimiter */
    );
    return idx === -1 ? void 0 : idString.slice(0, idx);
  }
  /**
   * Cheaply gets the local ID of a test identified with the string.
   */
  static localId(idString) {
    const idx = idString.lastIndexOf(
      "\0"
      /* TestIdPathParts.Delimiter */
    );
    return idx === -1 ? idString : idString.slice(idx + "\0".length);
  }
  /**
   * Gets whether maybeChild is a child of maybeParent.
   * todo@connor4312: review usages of this to see if using the WellDefinedPrefixTree is better
   */
  static isChild(maybeParent, maybeChild) {
    return maybeChild[maybeParent.length] === "\0" && maybeChild.startsWith(maybeParent);
  }
  /**
   * Compares the position of the two ID strings.
   * todo@connor4312: review usages of this to see if using the WellDefinedPrefixTree is better
   */
  static compare(a, b) {
    if (a === b) {
      return 0;
    }
    if (_$mQ.isChild(a, b)) {
      return 2;
    }
    if (_$mQ.isChild(b, a)) {
      return 3;
    }
    return 1;
  }
  static getLengthOfCommonPrefix(length, getId) {
    if (length === 0) {
      return 0;
    }
    let commonPrefix = 0;
    while (commonPrefix < length - 1) {
      for (let i = 1; i < length; i++) {
        const a = getId(i - 1);
        const b = getId(i);
        if (a.path[commonPrefix] !== b.path[commonPrefix]) {
          return commonPrefix;
        }
      }
      commonPrefix++;
    }
    return commonPrefix;
  }
  constructor(path, d = path.length) {
    this.path = path;
    this.d = d;
    if (path.length === 0 || d < 1) {
      throw new Error("cannot create test with empty path");
    }
  }
  /**
   * Gets the ID of the parent test.
   */
  get rootId() {
    return new _$mQ(this.path, 1);
  }
  /**
   * Gets the ID of the parent test.
   */
  get parentId() {
    return this.d > 1 ? new _$mQ(this.path, this.d - 1) : void 0;
  }
  /**
   * Gets the local ID of the current full test ID.
   */
  get localId() {
    return this.path[this.d - 1];
  }
  /**
   * Gets whether this ID refers to the root.
   */
  get controllerId() {
    return this.path[0];
  }
  /**
   * Gets whether this ID refers to the root.
   */
  get isRoot() {
    return this.d === 1;
  }
  /**
   * Returns an iterable that yields IDs of all parent items down to and
   * including the current item.
   */
  *idsFromRoot() {
    for (let i = 1; i <= this.d; i++) {
      yield new _$mQ(this.path, i);
    }
  }
  /**
   * Returns an iterable that yields IDs of the current item up to the root
   * item.
   */
  *idsToRoot() {
    for (let i = this.d; i > 0; i--) {
      yield new _$mQ(this.path, i);
    }
  }
  /**
   * Compares the other test ID with this one.
   */
  compare(other) {
    if (typeof other === "string") {
      return _$mQ.compare(this.toString(), other);
    }
    for (let i = 0; i < other.d && i < this.d; i++) {
      if (other.path[i] !== this.path[i]) {
        return 1;
      }
    }
    if (other.d > this.d) {
      return 2;
    }
    if (other.d < this.d) {
      return 3;
    }
    return 0;
  }
  /**
   * Serializes the ID.
   */
  toJSON() {
    return this.toString();
  }
  /**
   * Serializes the ID to a string.
   */
  toString() {
    if (!this.c) {
      this.c = this.path[0];
      for (let i = 1; i < this.d; i++) {
        this.c += "\0";
        this.c += this.path[i];
      }
    }
    return this.c;
  }
};

// out-build/vs/workbench/contrib/testing/common/testTypes.js
var TestResultState;
(function(TestResultState3) {
  TestResultState3[TestResultState3["Unset"] = 0] = "Unset";
  TestResultState3[TestResultState3["Queued"] = 1] = "Queued";
  TestResultState3[TestResultState3["Running"] = 2] = "Running";
  TestResultState3[TestResultState3["Passed"] = 3] = "Passed";
  TestResultState3[TestResultState3["Failed"] = 4] = "Failed";
  TestResultState3[TestResultState3["Skipped"] = 5] = "Skipped";
  TestResultState3[TestResultState3["Errored"] = 6] = "Errored";
})(TestResultState || (TestResultState = {}));
var ExtTestRunProfileKind;
(function(ExtTestRunProfileKind2) {
  ExtTestRunProfileKind2[ExtTestRunProfileKind2["Run"] = 1] = "Run";
  ExtTestRunProfileKind2[ExtTestRunProfileKind2["Debug"] = 2] = "Debug";
  ExtTestRunProfileKind2[ExtTestRunProfileKind2["Coverage"] = 3] = "Coverage";
})(ExtTestRunProfileKind || (ExtTestRunProfileKind = {}));
var TestControllerCapability;
(function(TestControllerCapability2) {
  TestControllerCapability2[TestControllerCapability2["Refresh"] = 2] = "Refresh";
  TestControllerCapability2[TestControllerCapability2["CodeRelatedToTest"] = 4] = "CodeRelatedToTest";
  TestControllerCapability2[TestControllerCapability2["TestRelatedToCode"] = 8] = "TestRelatedToCode";
})(TestControllerCapability || (TestControllerCapability = {}));
var TestRunProfileBitset;
(function(TestRunProfileBitset2) {
  TestRunProfileBitset2[TestRunProfileBitset2["Run"] = 2] = "Run";
  TestRunProfileBitset2[TestRunProfileBitset2["Debug"] = 4] = "Debug";
  TestRunProfileBitset2[TestRunProfileBitset2["Coverage"] = 8] = "Coverage";
  TestRunProfileBitset2[TestRunProfileBitset2["HasNonDefaultProfile"] = 16] = "HasNonDefaultProfile";
  TestRunProfileBitset2[TestRunProfileBitset2["HasConfigurable"] = 32] = "HasConfigurable";
  TestRunProfileBitset2[TestRunProfileBitset2["SupportsContinuousRun"] = 64] = "SupportsContinuousRun";
})(TestRunProfileBitset || (TestRunProfileBitset = {}));
var $oQ = {
  [
    2
    /* TestRunProfileBitset.Run */
  ]: localize(11359, null),
  [
    4
    /* TestRunProfileBitset.Debug */
  ]: localize(11360, null),
  [
    8
    /* TestRunProfileBitset.Coverage */
  ]: localize(11361, null)
};
var $qQ = (t) => "runId" in t;
var IRichLocation;
(function(IRichLocation2) {
  IRichLocation2.serialize = (location2) => ({
    range: location2.range.toJSON(),
    uri: location2.uri.toJSON()
  });
  IRichLocation2.deserialize = (uriIdentity, location2) => ({
    range: $9C.lift(location2.range),
    uri: uriIdentity.asCanonicalUri(URI.revive(location2.uri))
  });
})(IRichLocation || (IRichLocation = {}));
var TestMessageType;
(function(TestMessageType2) {
  TestMessageType2[TestMessageType2["Error"] = 0] = "Error";
  TestMessageType2[TestMessageType2["Output"] = 1] = "Output";
})(TestMessageType || (TestMessageType = {}));
var ITestMessageStackFrame;
(function(ITestMessageStackFrame2) {
  ITestMessageStackFrame2.serialize = (stack) => ({
    label: stack.label,
    uri: stack.uri?.toJSON(),
    position: stack.position?.toJSON()
  });
  ITestMessageStackFrame2.deserialize = (uriIdentity, stack) => ({
    label: stack.label,
    uri: stack.uri ? uriIdentity.asCanonicalUri(URI.revive(stack.uri)) : void 0,
    position: stack.position ? $8C.lift(stack.position) : void 0
  });
})(ITestMessageStackFrame || (ITestMessageStackFrame = {}));
var ITestErrorMessage;
(function(ITestErrorMessage2) {
  ITestErrorMessage2.serialize = (message) => ({
    message: message.message,
    type: 0,
    expected: message.expected,
    actual: message.actual,
    contextValue: message.contextValue,
    location: message.location && IRichLocation.serialize(message.location),
    stackTrace: message.stackTrace?.map(ITestMessageStackFrame.serialize)
  });
  ITestErrorMessage2.deserialize = (uriIdentity, message) => ({
    message: message.message,
    type: 0,
    expected: message.expected,
    actual: message.actual,
    contextValue: message.contextValue,
    location: message.location && IRichLocation.deserialize(uriIdentity, message.location),
    stackTrace: message.stackTrace && message.stackTrace.map((s) => ITestMessageStackFrame.deserialize(uriIdentity, s))
  });
})(ITestErrorMessage || (ITestErrorMessage = {}));
var ITestOutputMessage;
(function(ITestOutputMessage2) {
  ITestOutputMessage2.serialize = (message) => ({
    message: message.message,
    type: 1,
    offset: message.offset,
    length: message.length,
    location: message.location && IRichLocation.serialize(message.location)
  });
  ITestOutputMessage2.deserialize = (uriIdentity, message) => ({
    message: message.message,
    type: 1,
    offset: message.offset,
    length: message.length,
    location: message.location && IRichLocation.deserialize(uriIdentity, message.location)
  });
})(ITestOutputMessage || (ITestOutputMessage = {}));
var ITestMessage;
(function(ITestMessage2) {
  ITestMessage2.serialize = (message) => message.type === 0 ? ITestErrorMessage.serialize(message) : ITestOutputMessage.serialize(message);
  ITestMessage2.deserialize = (uriIdentity, message) => message.type === 0 ? ITestErrorMessage.deserialize(uriIdentity, message) : ITestOutputMessage.deserialize(uriIdentity, message);
  ITestMessage2.isDiffable = (message) => message.type === 0 && message.actual !== void 0 && message.expected !== void 0;
})(ITestMessage || (ITestMessage = {}));
var ITestTaskState;
(function(ITestTaskState2) {
  ITestTaskState2.serializeWithoutMessages = (state) => ({
    state: state.state,
    duration: state.duration,
    messages: []
  });
  ITestTaskState2.serialize = (state) => ({
    state: state.state,
    duration: state.duration,
    messages: state.messages.map(ITestMessage.serialize)
  });
  ITestTaskState2.deserialize = (uriIdentity, state) => ({
    state: state.state,
    duration: state.duration,
    messages: state.messages.map((m) => ITestMessage.deserialize(uriIdentity, m))
  });
})(ITestTaskState || (ITestTaskState = {}));
var testTagDelimiter = "\0";
var $sQ = (ctrlId, tagId) => ctrlId + testTagDelimiter + tagId;
var $tQ = (namespaced) => {
  const index = namespaced.indexOf(testTagDelimiter);
  return { ctrlId: namespaced.slice(0, index), tagId: namespaced.slice(index + 1) };
};
var ITestItem;
(function(ITestItem2) {
  ITestItem2.serialize = (item) => ({
    extId: item.extId,
    label: item.label,
    tags: item.tags,
    busy: item.busy,
    children: void 0,
    uri: item.uri?.toJSON(),
    range: item.range?.toJSON() || null,
    description: item.description,
    error: item.error,
    sortText: item.sortText
  });
  ITestItem2.deserialize = (uriIdentity, serialized) => ({
    extId: serialized.extId,
    label: serialized.label,
    tags: serialized.tags,
    busy: serialized.busy,
    children: void 0,
    uri: serialized.uri ? uriIdentity.asCanonicalUri(URI.revive(serialized.uri)) : void 0,
    range: serialized.range ? $9C.lift(serialized.range) : null,
    description: serialized.description,
    error: serialized.error,
    sortText: serialized.sortText
  });
})(ITestItem || (ITestItem = {}));
var TestItemExpandState;
(function(TestItemExpandState2) {
  TestItemExpandState2[TestItemExpandState2["NotExpandable"] = 0] = "NotExpandable";
  TestItemExpandState2[TestItemExpandState2["Expandable"] = 1] = "Expandable";
  TestItemExpandState2[TestItemExpandState2["BusyExpanding"] = 2] = "BusyExpanding";
  TestItemExpandState2[TestItemExpandState2["Expanded"] = 3] = "Expanded";
})(TestItemExpandState || (TestItemExpandState = {}));
var InternalTestItem;
(function(InternalTestItem2) {
  InternalTestItem2.serialize = (item) => ({
    expand: item.expand,
    item: ITestItem.serialize(item.item)
  });
  InternalTestItem2.deserialize = (uriIdentity, serialized) => ({
    // the `controllerId` is derived from the test.item.extId. It's redundant
    // in the non-serialized InternalTestItem too, but there just because it's
    // checked against in many hot paths.
    controllerId: $mQ.root(serialized.item.extId),
    expand: serialized.expand,
    item: ITestItem.deserialize(uriIdentity, serialized.item)
  });
})(InternalTestItem || (InternalTestItem = {}));
var ITestItemUpdate;
(function(ITestItemUpdate2) {
  ITestItemUpdate2.serialize = (u) => {
    let item;
    if (u.item) {
      item = {};
      if (u.item.label !== void 0) {
        item.label = u.item.label;
      }
      if (u.item.tags !== void 0) {
        item.tags = u.item.tags;
      }
      if (u.item.busy !== void 0) {
        item.busy = u.item.busy;
      }
      if (u.item.uri !== void 0) {
        item.uri = u.item.uri?.toJSON();
      }
      if (u.item.range !== void 0) {
        item.range = u.item.range?.toJSON();
      }
      if (u.item.description !== void 0) {
        item.description = u.item.description;
      }
      if (u.item.error !== void 0) {
        item.error = u.item.error;
      }
      if (u.item.sortText !== void 0) {
        item.sortText = u.item.sortText;
      }
    }
    return { extId: u.extId, expand: u.expand, item };
  };
  ITestItemUpdate2.deserialize = (u) => {
    let item;
    if (u.item) {
      item = {};
      if (u.item.label !== void 0) {
        item.label = u.item.label;
      }
      if (u.item.tags !== void 0) {
        item.tags = u.item.tags;
      }
      if (u.item.busy !== void 0) {
        item.busy = u.item.busy;
      }
      if (u.item.range !== void 0) {
        item.range = u.item.range ? $9C.lift(u.item.range) : null;
      }
      if (u.item.description !== void 0) {
        item.description = u.item.description;
      }
      if (u.item.error !== void 0) {
        item.error = u.item.error;
      }
      if (u.item.sortText !== void 0) {
        item.sortText = u.item.sortText;
      }
    }
    return { extId: u.extId, expand: u.expand, item };
  };
})(ITestItemUpdate || (ITestItemUpdate = {}));
var $uQ = (internal, patch2) => {
  if (patch2.expand !== void 0) {
    internal.expand = patch2.expand;
  }
  if (patch2.item !== void 0) {
    internal.item = internal.item ? Object.assign(internal.item, patch2.item) : patch2.item;
  }
};
var TestResultItem;
(function(TestResultItem2) {
  TestResultItem2.serializeWithoutMessages = (original) => ({
    ...InternalTestItem.serialize(original),
    ownComputedState: original.ownComputedState,
    computedState: original.computedState,
    tasks: original.tasks.map(ITestTaskState.serializeWithoutMessages)
  });
  TestResultItem2.serialize = (original) => ({
    ...InternalTestItem.serialize(original),
    ownComputedState: original.ownComputedState,
    computedState: original.computedState,
    tasks: original.tasks.map(ITestTaskState.serialize)
  });
  TestResultItem2.deserialize = (uriIdentity, serialized) => ({
    ...InternalTestItem.deserialize(uriIdentity, serialized),
    ownComputedState: serialized.ownComputedState,
    computedState: serialized.computedState,
    tasks: serialized.tasks.map((m) => ITestTaskState.deserialize(uriIdentity, m)),
    retired: true
  });
})(TestResultItem || (TestResultItem = {}));
var ICoverageCount;
(function(ICoverageCount2) {
  ICoverageCount2.empty = () => ({ covered: 0, total: 0 });
  ICoverageCount2.sum = (target, src) => {
    target.covered += src.covered;
    target.total += src.total;
  };
})(ICoverageCount || (ICoverageCount = {}));
var IFileCoverage;
(function(IFileCoverage2) {
  IFileCoverage2.serialize = (original) => ({
    id: original.id,
    statement: original.statement,
    branch: original.branch,
    declaration: original.declaration,
    testIds: original.testIds,
    uri: original.uri.toJSON()
  });
  IFileCoverage2.deserialize = (uriIdentity, serialized) => ({
    id: serialized.id,
    statement: serialized.statement,
    branch: serialized.branch,
    declaration: serialized.declaration,
    testIds: serialized.testIds,
    uri: uriIdentity.asCanonicalUri(URI.revive(serialized.uri))
  });
  IFileCoverage2.empty = (id2, uri) => ({
    id: id2,
    uri,
    statement: ICoverageCount.empty()
  });
})(IFileCoverage || (IFileCoverage = {}));
function serializeThingWithLocation(serialized) {
  return {
    ...serialized,
    location: serialized.location?.toJSON()
  };
}
function deserializeThingWithLocation(serialized) {
  serialized.location = serialized.location ? $8C.isIPosition(serialized.location) ? $8C.lift(serialized.location) : $9C.lift(serialized.location) : void 0;
  return serialized;
}
var DetailType;
(function(DetailType2) {
  DetailType2[DetailType2["Declaration"] = 0] = "Declaration";
  DetailType2[DetailType2["Statement"] = 1] = "Statement";
  DetailType2[DetailType2["Branch"] = 2] = "Branch";
})(DetailType || (DetailType = {}));
var CoverageDetails;
(function(CoverageDetails2) {
  CoverageDetails2.serialize = (original) => original.type === 0 ? IDeclarationCoverage.serialize(original) : IStatementCoverage.serialize(original);
  CoverageDetails2.deserialize = (serialized) => serialized.type === 0 ? IDeclarationCoverage.deserialize(serialized) : IStatementCoverage.deserialize(serialized);
})(CoverageDetails || (CoverageDetails = {}));
var IBranchCoverage;
(function(IBranchCoverage2) {
  IBranchCoverage2.serialize = serializeThingWithLocation;
  IBranchCoverage2.deserialize = deserializeThingWithLocation;
})(IBranchCoverage || (IBranchCoverage = {}));
var IDeclarationCoverage;
(function(IDeclarationCoverage2) {
  IDeclarationCoverage2.serialize = serializeThingWithLocation;
  IDeclarationCoverage2.deserialize = deserializeThingWithLocation;
})(IDeclarationCoverage || (IDeclarationCoverage = {}));
var IStatementCoverage;
(function(IStatementCoverage2) {
  IStatementCoverage2.serialize = (original) => ({
    ...serializeThingWithLocation(original),
    branches: original.branches?.map(IBranchCoverage.serialize)
  });
  IStatementCoverage2.deserialize = (serialized) => ({
    ...deserializeThingWithLocation(serialized),
    branches: serialized.branches?.map(IBranchCoverage.deserialize)
  });
})(IStatementCoverage || (IStatementCoverage = {}));
var TestDiffOpType;
(function(TestDiffOpType2) {
  TestDiffOpType2[TestDiffOpType2["Add"] = 0] = "Add";
  TestDiffOpType2[TestDiffOpType2["Update"] = 1] = "Update";
  TestDiffOpType2[TestDiffOpType2["DocumentSynced"] = 2] = "DocumentSynced";
  TestDiffOpType2[TestDiffOpType2["Remove"] = 3] = "Remove";
  TestDiffOpType2[TestDiffOpType2["IncrementPendingExtHosts"] = 4] = "IncrementPendingExtHosts";
  TestDiffOpType2[TestDiffOpType2["Retire"] = 5] = "Retire";
  TestDiffOpType2[TestDiffOpType2["AddTag"] = 6] = "AddTag";
  TestDiffOpType2[TestDiffOpType2["RemoveTag"] = 7] = "RemoveTag";
})(TestDiffOpType || (TestDiffOpType = {}));
var TestsDiffOp;
(function(TestsDiffOp2) {
  TestsDiffOp2.deserialize = (uriIdentity, u) => {
    if (u.op === 0) {
      return { op: u.op, item: InternalTestItem.deserialize(uriIdentity, u.item) };
    } else if (u.op === 1) {
      return { op: u.op, item: ITestItemUpdate.deserialize(u.item) };
    } else if (u.op === 2) {
      return { op: u.op, uri: uriIdentity.asCanonicalUri(URI.revive(u.uri)), docv: u.docv };
    } else {
      return u;
    }
  };
  TestsDiffOp2.serialize = (u) => {
    if (u.op === 0) {
      return { op: u.op, item: InternalTestItem.serialize(u.item) };
    } else if (u.op === 1) {
      return { op: u.op, item: ITestItemUpdate.serialize(u.item) };
    } else {
      return u;
    }
  };
})(TestsDiffOp || (TestsDiffOp = {}));
var $wQ = class {
  constructor(l) {
    this.l = l;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Set();
    this.j = 0;
    this.k = 0;
    this.tags = this.f;
  }
  /**
   * Applies the diff to the collection.
   */
  apply(diff2) {
    const changes = this.x();
    for (const op of diff2) {
      switch (op.op) {
        case 0:
          this.p(InternalTestItem.deserialize(this.l, op.item), changes);
          break;
        case 1:
          this.q(ITestItemUpdate.deserialize(op.item), changes);
          break;
        case 3:
          this.v(op.itemId, changes);
          break;
        case 5:
          this.w(op.itemId);
          break;
        case 4:
          this.updatePendingRoots(op.amount);
          break;
        case 6:
          this.f.set(op.tag.id, op.tag);
          break;
        case 7:
          this.f.delete(op.id);
          break;
      }
    }
    changes.complete?.();
  }
  p(item, changes) {
    const parentId = $mQ.parentId(item.item.extId)?.toString();
    let created;
    if (!parentId) {
      created = this.y(item);
      this.h.add(created);
      this.g.set(item.item.extId, created);
    } else if (this.g.has(parentId)) {
      const parent = this.g.get(parentId);
      parent.children.add(item.item.extId);
      created = this.y(item, parent);
      this.g.set(item.item.extId, created);
    } else {
      console.error(`Test with unknown parent ID: ${JSON.stringify(item)}`);
      return;
    }
    changes.add?.(created);
    if (item.expand === 2) {
      this.j++;
    }
    return created;
  }
  q(patch2, changes) {
    const existing = this.g.get(patch2.extId);
    if (!existing) {
      return;
    }
    if (patch2.expand !== void 0) {
      if (existing.expand === 2) {
        this.j--;
      }
      if (patch2.expand === 2) {
        this.j++;
      }
    }
    $uQ(existing, patch2);
    changes.update?.(existing);
    return existing;
  }
  v(itemId, changes) {
    const toRemove = this.g.get(itemId);
    if (!toRemove) {
      return;
    }
    const parentId = $mQ.parentId(toRemove.item.extId)?.toString();
    if (parentId) {
      const parent = this.g.get(parentId);
      parent.children.delete(toRemove.item.extId);
    } else {
      this.h.delete(toRemove);
    }
    const queue = [[itemId]];
    while (queue.length) {
      for (const itemId2 of queue.pop()) {
        const existing = this.g.get(itemId2);
        if (existing) {
          queue.push(existing.children);
          this.g.delete(itemId2);
          changes.remove?.(existing, existing !== toRemove);
          if (existing.expand === 2) {
            this.j--;
          }
        }
      }
    }
  }
  /**
   * Called when the extension signals a test result should be retired.
   */
  w(testId) {
  }
  /**
   * Updates the number of test root sources who are yet to report. When
   * the total pending test roots reaches 0, the roots for all controllers
   * will exist in the collection.
   */
  updatePendingRoots(delta2) {
    this.k += delta2;
  }
  /**
   * Called before a diff is applied to create a new change collector.
   */
  x() {
    return {};
  }
};

// out-build/vs/workbench/services/editor/common/editorGroupsService.js
var $iJ = $Qk("editorGroupsService");
var GroupDirection;
(function(GroupDirection2) {
  GroupDirection2[GroupDirection2["UP"] = 0] = "UP";
  GroupDirection2[GroupDirection2["DOWN"] = 1] = "DOWN";
  GroupDirection2[GroupDirection2["LEFT"] = 2] = "LEFT";
  GroupDirection2[GroupDirection2["RIGHT"] = 3] = "RIGHT";
})(GroupDirection || (GroupDirection = {}));
var GroupOrientation;
(function(GroupOrientation2) {
  GroupOrientation2[GroupOrientation2["HORIZONTAL"] = 0] = "HORIZONTAL";
  GroupOrientation2[GroupOrientation2["VERTICAL"] = 1] = "VERTICAL";
})(GroupOrientation || (GroupOrientation = {}));
var GroupLocation;
(function(GroupLocation2) {
  GroupLocation2[GroupLocation2["FIRST"] = 0] = "FIRST";
  GroupLocation2[GroupLocation2["LAST"] = 1] = "LAST";
  GroupLocation2[GroupLocation2["NEXT"] = 2] = "NEXT";
  GroupLocation2[GroupLocation2["PREVIOUS"] = 3] = "PREVIOUS";
})(GroupLocation || (GroupLocation = {}));
var GroupsArrangement;
(function(GroupsArrangement2) {
  GroupsArrangement2[GroupsArrangement2["MAXIMIZE"] = 0] = "MAXIMIZE";
  GroupsArrangement2[GroupsArrangement2["EXPAND"] = 1] = "EXPAND";
  GroupsArrangement2[GroupsArrangement2["EVEN"] = 2] = "EVEN";
})(GroupsArrangement || (GroupsArrangement = {}));
var MergeGroupMode;
(function(MergeGroupMode2) {
  MergeGroupMode2[MergeGroupMode2["COPY_EDITORS"] = 0] = "COPY_EDITORS";
  MergeGroupMode2[MergeGroupMode2["MOVE_EDITORS"] = 1] = "MOVE_EDITORS";
})(MergeGroupMode || (MergeGroupMode = {}));
var GroupsOrder;
(function(GroupsOrder2) {
  GroupsOrder2[GroupsOrder2["CREATION_TIME"] = 0] = "CREATION_TIME";
  GroupsOrder2[GroupsOrder2["MOST_RECENTLY_ACTIVE"] = 1] = "MOST_RECENTLY_ACTIVE";
  GroupsOrder2[GroupsOrder2["GRID_APPEARANCE"] = 2] = "GRID_APPEARANCE";
})(GroupsOrder || (GroupsOrder = {}));
var OpenEditorContext;
(function(OpenEditorContext2) {
  OpenEditorContext2[OpenEditorContext2["NEW_EDITOR"] = 1] = "NEW_EDITOR";
  OpenEditorContext2[OpenEditorContext2["MOVE_EDITOR"] = 2] = "MOVE_EDITOR";
  OpenEditorContext2[OpenEditorContext2["COPY_EDITOR"] = 3] = "COPY_EDITOR";
})(OpenEditorContext || (OpenEditorContext = {}));

// out-build/vs/workbench/services/editor/common/editorService.js
var $mJ = $Qk("editorService");
var $nJ = -1;
var $oJ = -2;

// out-build/vs/workbench/contrib/testing/common/testItemCollection.js
var TestItemEventOp;
(function(TestItemEventOp2) {
  TestItemEventOp2[TestItemEventOp2["Upsert"] = 0] = "Upsert";
  TestItemEventOp2[TestItemEventOp2["SetTags"] = 1] = "SetTags";
  TestItemEventOp2[TestItemEventOp2["UpdateCanResolveChildren"] = 2] = "UpdateCanResolveChildren";
  TestItemEventOp2[TestItemEventOp2["RemoveChild"] = 3] = "RemoveChild";
  TestItemEventOp2[TestItemEventOp2["SetProp"] = 4] = "SetProp";
  TestItemEventOp2[TestItemEventOp2["Bulk"] = 5] = "Bulk";
  TestItemEventOp2[TestItemEventOp2["DocumentSynced"] = 6] = "DocumentSynced";
})(TestItemEventOp || (TestItemEventOp = {}));
var strictEqualComparator = (a, b) => a === b;
var diffableProps = {
  range: (a, b) => {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.equalsRange(b);
  },
  busy: strictEqualComparator,
  label: strictEqualComparator,
  description: strictEqualComparator,
  error: strictEqualComparator,
  sortText: strictEqualComparator,
  tags: (a, b) => {
    if (a.length !== b.length) {
      return false;
    }
    if (a.some((t1) => !b.includes(t1))) {
      return false;
    }
    return true;
  }
};
var diffableEntries = Object.entries(diffableProps);
var diffTestItems = (a, b) => {
  let output;
  for (const [key, cmp4] of diffableEntries) {
    if (!cmp4(a[key], b[key])) {
      if (output) {
        output[key] = b[key];
      } else {
        output = { [key]: b[key] };
      }
    }
  }
  return output;
};
var $9V = class extends $3c {
  get root() {
    return this.s.root;
  }
  constructor(s) {
    super();
    this.s = s;
    this.f = this.B(new $8h(() => this.flushDiff(), 200));
    this.g = this.B(new $ze());
    this.tree = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.m = [];
    this.onDidGenerateDiff = this.g.event;
    this.root.canResolveChildren = true;
    this.z(this.root, void 0);
  }
  /**
   * Handler used for expanding test items.
   */
  set resolveHandler(handler) {
    this.h = handler;
    for (const test of this.tree.values()) {
      this.J(test);
    }
  }
  get resolveHandler() {
    return this.h;
  }
  /**
   * Gets a diff of all changes that have been made, and clears the diff queue.
   */
  collectDiff() {
    const diff2 = this.m;
    this.m = [];
    return diff2;
  }
  /**
   * Pushes a new diff entry onto the collected diff list.
   */
  pushDiff(diff2) {
    switch (diff2.op) {
      case 2: {
        for (const existing of this.m) {
          if (existing.op === 2 && existing.uri === diff2.uri) {
            existing.docv = diff2.docv;
            return;
          }
        }
        break;
      }
      case 1: {
        const last = this.m[this.m.length - 1];
        if (last) {
          if (last.op === 1 && last.item.extId === diff2.item.extId) {
            $uQ(last.item, diff2.item);
            return;
          }
          if (last.op === 0 && last.item.item.extId === diff2.item.extId) {
            $uQ(last.item, diff2.item);
            return;
          }
        }
        break;
      }
    }
    this.m.push(diff2);
    if (!this.f.isScheduled()) {
      this.f.schedule();
    }
  }
  /**
   * Expands the test and the given number of `levels` of children. If levels
   * is < 0, then all children will be expanded. If it's 0, then only this
   * item will be expanded.
   */
  expand(testId, levels) {
    const internal = this.tree.get(testId);
    if (!internal) {
      return;
    }
    if (internal.expandLevels === void 0 || levels > internal.expandLevels) {
      internal.expandLevels = levels;
    }
    if (internal.expand === 1) {
      const r = this.M(internal);
      return !r.isOpen() ? r.wait().then(() => this.L(internal, levels - 1)) : this.L(internal, levels - 1);
    } else if (internal.expand === 3) {
      return internal.resolveBarrier?.isOpen() === false ? internal.resolveBarrier.wait().then(() => this.L(internal, levels - 1)) : this.L(internal, levels - 1);
    }
  }
  dispose() {
    for (const item of this.tree.values()) {
      this.s.getApiFor(item.actual).listener = void 0;
    }
    this.tree.clear();
    this.m = [];
    super.dispose();
  }
  w(internal, evt) {
    switch (evt.op) {
      case 3:
        this.O($mQ.joinToString(internal.fullId, evt.id));
        break;
      case 0:
        this.z(evt.item, internal);
        break;
      case 5:
        for (const op of evt.ops) {
          this.w(internal, op);
        }
        break;
      case 1:
        this.C(evt.new, evt.old, internal.fullId.toString());
        break;
      case 2:
        this.J(internal);
        break;
      case 4:
        this.pushDiff({
          op: 1,
          item: {
            extId: internal.fullId.toString(),
            item: evt.update
          }
        });
        break;
      case 6:
        this.y(internal.actual.uri);
        break;
      default:
        $hd(evt);
    }
  }
  y(uri) {
    if (uri) {
      this.pushDiff({
        op: 2,
        uri,
        docv: this.s.getDocumentVersion(uri)
      });
    }
  }
  z(actual, parent) {
    const fullId = $mQ.fromExtHostTestItem(actual, this.root.id, parent?.actual);
    const privateApi = this.s.getApiFor(actual);
    if (privateApi.parent && privateApi.parent !== parent?.actual) {
      this.s.getChildren(privateApi.parent).delete(actual.id);
    }
    let internal = this.tree.get(fullId.toString());
    if (!internal) {
      internal = {
        fullId,
        actual,
        expandLevels: parent?.expandLevels ? parent.expandLevels - 1 : void 0,
        expand: 0
        // updated by `connectItemAndChildren`
      };
      actual.tags.forEach(this.D, this);
      this.tree.set(internal.fullId.toString(), internal);
      this.G(actual, parent);
      this.pushDiff({
        op: 0,
        item: {
          controllerId: this.s.controllerId,
          expand: internal.expand,
          item: this.s.toITestItem(actual)
        }
      });
      this.I(actual, internal, parent);
      return;
    }
    if (internal.actual === actual) {
      this.H(actual, internal, parent);
      return;
    }
    if (internal.actual.uri?.toString() !== actual.uri?.toString()) {
      this.O(fullId.toString());
      return this.z(actual, parent);
    }
    const oldChildren = this.s.getChildren(internal.actual);
    const oldActual = internal.actual;
    const update = diffTestItems(this.s.toITestItem(oldActual), this.s.toITestItem(actual));
    this.s.getApiFor(oldActual).listener = void 0;
    internal.actual = actual;
    internal.resolveBarrier = void 0;
    internal.expand = 0;
    if (update) {
      if (update.hasOwnProperty("tags")) {
        this.C(actual.tags, oldActual.tags, fullId.toString());
        delete update.tags;
      }
      this.w(internal, { op: 4, update });
    }
    this.I(actual, internal, parent);
    for (const [_, child] of oldChildren) {
      if (!this.s.getChildren(actual).get(child.id)) {
        this.O($mQ.joinToString(fullId, child.id));
      }
    }
    const expandLevels = internal.expandLevels;
    if (expandLevels !== void 0) {
      queueMicrotask(() => {
        if (internal.expand === 1) {
          internal.expandLevels = void 0;
          this.expand(fullId.toString(), expandLevels);
        }
      });
    }
    this.y(internal.actual.uri);
  }
  C(newTags, oldTags, extId) {
    const toDelete = new Set(oldTags.map((t) => t.id));
    for (const tag2 of newTags) {
      if (!toDelete.delete(tag2.id)) {
        this.D(tag2);
      }
    }
    this.pushDiff({
      op: 1,
      item: { extId, item: { tags: newTags.map((v) => $sQ(this.s.controllerId, v.id)) } }
    });
    toDelete.forEach(this.F, this);
  }
  D(tag2) {
    const existing = this.j.get(tag2.id);
    if (existing) {
      existing.refCount++;
    } else {
      this.j.set(tag2.id, { refCount: 1 });
      this.pushDiff({
        op: 6,
        tag: {
          id: $sQ(this.s.controllerId, tag2.id)
        }
      });
    }
  }
  F(tagId) {
    const existing = this.j.get(tagId);
    if (existing && !--existing.refCount) {
      this.j.delete(tagId);
      this.pushDiff({ op: 7, id: $sQ(this.s.controllerId, tagId) });
    }
  }
  G(actual, parent) {
    this.s.getApiFor(actual).parent = parent && parent.actual !== this.root ? parent.actual : void 0;
  }
  H(actual, internal, parent) {
    this.G(actual, parent);
    const api = this.s.getApiFor(actual);
    api.parent = parent?.actual;
    api.listener = (evt) => this.w(internal, evt);
    this.J(internal);
  }
  I(actual, internal, parent) {
    this.H(actual, internal, parent);
    for (const [_, child] of this.s.getChildren(actual)) {
      this.z(child, internal);
    }
  }
  /**
   * Updates the `expand` state of the item. Should be called whenever the
   * resolved state of the item changes. Can automatically expand the item
   * if requested by a consumer.
   */
  J(internal) {
    let newState;
    if (!this.h) {
      newState = 0;
    } else if (internal.resolveBarrier) {
      newState = internal.resolveBarrier.isOpen() ? 3 : 2;
    } else {
      newState = internal.actual.canResolveChildren ? 1 : 0;
    }
    if (newState === internal.expand) {
      return;
    }
    internal.expand = newState;
    this.pushDiff({ op: 1, item: { extId: internal.fullId.toString(), expand: newState } });
    if (newState === 1 && internal.expandLevels !== void 0) {
      this.M(internal);
    }
  }
  /**
   * Expands all children of the item, "levels" deep. If levels is 0, only
   * the children will be expanded. If it's 1, the children and their children
   * will be expanded. If it's <0, it's a no-op.
   */
  L(internal, levels) {
    if (levels < 0) {
      return;
    }
    const expandRequests = [];
    for (const [_, child] of this.s.getChildren(internal.actual)) {
      const promise = this.expand($mQ.joinToString(internal.fullId, child.id), levels);
      if ($Gh(promise)) {
        expandRequests.push(promise);
      }
    }
    if (expandRequests.length) {
      return Promise.all(expandRequests).then(() => {
      });
    }
  }
  /**
   * Calls `discoverChildren` on the item, refreshing all its tests.
   */
  M(internal) {
    if (internal.resolveBarrier) {
      return internal.resolveBarrier;
    }
    if (!this.h) {
      const b = new $Uh();
      b.open();
      return b;
    }
    internal.expand = 2;
    this.N(internal);
    const barrier = internal.resolveBarrier = new $Uh();
    const applyError = (err) => {
      console.error(`Unhandled error in resolveHandler of test controller "${this.s.controllerId}"`, err);
    };
    let r;
    try {
      r = this.h(internal.actual === this.root ? void 0 : internal.actual);
    } catch (err) {
      applyError(err);
    }
    if ($Gh(r)) {
      r.catch(applyError).then(() => {
        barrier.open();
        this.J(internal);
      });
    } else {
      barrier.open();
      this.J(internal);
    }
    return internal.resolveBarrier;
  }
  N(internal) {
    this.pushDiff({ op: 1, item: { extId: internal.fullId.toString(), expand: internal.expand } });
  }
  O(childId) {
    const childItem = this.tree.get(childId);
    if (!childItem) {
      throw new Error("attempting to remove non-existent child");
    }
    this.pushDiff({ op: 3, itemId: childId });
    const queue = [childItem];
    while (queue.length) {
      const item = queue.pop();
      if (!item) {
        continue;
      }
      this.s.getApiFor(item.actual).listener = void 0;
      for (const tag2 of item.actual.tags) {
        this.F(tag2.id);
      }
      this.tree.delete(item.fullId.toString());
      for (const [_, child] of this.s.getChildren(item.actual)) {
        queue.push(this.tree.get($mQ.joinToString(item.fullId, child.id)));
      }
    }
  }
  /**
   * Immediately emits any pending diffs on the collection.
   */
  flushDiff() {
    const diff2 = this.collectDiff();
    if (diff2.length) {
      this.g.fire(diff2);
    }
  }
};
var $0V = class extends Error {
  constructor(id2) {
    super(`Attempted to insert a duplicate test item ID ${id2}`);
  }
};
var $$V = class extends Error {
  constructor(id2) {
    super(`TestItem with ID "${id2}" is invalid. Make sure to create it from the createTestItem method.`);
  }
};
var $_V = class extends Error {
  constructor(id2, ctrlA, ctrlB) {
    super(`TestItem with ID "${id2}" is from controller "${ctrlA}" and cannot be added as a child of an item from controller "${ctrlB}".`);
  }
};
var $aW = (api, getApi, checkCtor) => {
  let mapped = /* @__PURE__ */ new Map();
  return {
    /** @inheritdoc */
    get size() {
      return mapped.size;
    },
    /** @inheritdoc */
    forEach(callback, thisArg) {
      for (const item of mapped.values()) {
        callback.call(thisArg, item, this);
      }
    },
    /** @inheritdoc */
    [Symbol.iterator]() {
      return mapped.entries();
    },
    /** @inheritdoc */
    replace(items) {
      const newMapped = /* @__PURE__ */ new Map();
      const toDelete = new Set(mapped.keys());
      const bulk = { op: 5, ops: [] };
      for (const item of items) {
        if (!(item instanceof checkCtor)) {
          throw new $$V(item.id);
        }
        const itemController = getApi(item).controllerId;
        if (itemController !== api.controllerId) {
          throw new $_V(item.id, itemController, api.controllerId);
        }
        if (newMapped.has(item.id)) {
          throw new $0V(item.id);
        }
        newMapped.set(item.id, item);
        toDelete.delete(item.id);
        bulk.ops.push({ op: 0, item });
      }
      for (const id2 of toDelete.keys()) {
        bulk.ops.push({ op: 3, id: id2 });
      }
      api.listener?.(bulk);
      mapped = newMapped;
    },
    /** @inheritdoc */
    add(item) {
      if (!(item instanceof checkCtor)) {
        throw new $$V(item.id);
      }
      mapped.set(item.id, item);
      api.listener?.({ op: 0, item });
    },
    /** @inheritdoc */
    delete(id2) {
      if (mapped.delete(id2)) {
        api.listener?.({ op: 3, id: id2 });
      }
    },
    /** @inheritdoc */
    get(itemId) {
      return mapped.get(itemId);
    },
    /** JSON serialization function. */
    toJSON() {
      return Array.from(mapped.values());
    }
  };
};

// out-build/vs/workbench/api/common/extHostTestingPrivateApi.js
var eventPrivateApis = /* @__PURE__ */ new WeakMap();
var $bW = (impl, controllerId) => {
  const api = { controllerId };
  eventPrivateApis.set(impl, api);
  return api;
};
var $cW = (impl) => {
  const api = eventPrivateApis.get(impl);
  if (!api) {
    throw new $$V(impl?.id || "<unknown>");
  }
  return api;
};

// out-build/vs/platform/remote/common/remoteAuthorityResolver.js
var $bC = $Qk("remoteAuthorityResolverService");
var RemoteConnectionType;
(function(RemoteConnectionType2) {
  RemoteConnectionType2[RemoteConnectionType2["WebSocket"] = 0] = "WebSocket";
  RemoteConnectionType2[RemoteConnectionType2["Managed"] = 1] = "Managed";
})(RemoteConnectionType || (RemoteConnectionType = {}));
var $cC = class {
  constructor(id2) {
    this.id = id2;
    this.type = 1;
  }
  toString() {
    return `Managed(${this.id})`;
  }
};
var $dC = class {
  constructor(host, port) {
    this.host = host;
    this.port = port;
    this.type = 0;
  }
  toString() {
    return `WebSocket(${this.host}:${this.port})`;
  }
};
var RemoteAuthorityResolverErrorCode;
(function(RemoteAuthorityResolverErrorCode2) {
  RemoteAuthorityResolverErrorCode2["Unknown"] = "Unknown";
  RemoteAuthorityResolverErrorCode2["NotAvailable"] = "NotAvailable";
  RemoteAuthorityResolverErrorCode2["TemporarilyNotAvailable"] = "TemporarilyNotAvailable";
  RemoteAuthorityResolverErrorCode2["NoResolverFound"] = "NoResolverFound";
  RemoteAuthorityResolverErrorCode2["InvalidAuthority"] = "InvalidAuthority";
})(RemoteAuthorityResolverErrorCode || (RemoteAuthorityResolverErrorCode = {}));
var $eC = class _$eC extends $ub {
  static isNotAvailable(err) {
    return err instanceof _$eC && err._code === RemoteAuthorityResolverErrorCode.NotAvailable;
  }
  static isTemporarilyNotAvailable(err) {
    return err instanceof _$eC && err._code === RemoteAuthorityResolverErrorCode.TemporarilyNotAvailable;
  }
  static isNoResolverFound(err) {
    return err instanceof _$eC && err._code === RemoteAuthorityResolverErrorCode.NoResolverFound;
  }
  static isInvalidAuthority(err) {
    return err instanceof _$eC && err._code === RemoteAuthorityResolverErrorCode.InvalidAuthority;
  }
  static isHandled(err) {
    return err instanceof _$eC && err.isHandled;
  }
  constructor(message, code = RemoteAuthorityResolverErrorCode.Unknown, detail) {
    super(message);
    this._message = message;
    this._code = code;
    this._detail = detail;
    this.isHandled = code === RemoteAuthorityResolverErrorCode.NotAvailable && detail === true;
    Object.setPrototypeOf(this, _$eC.prototype);
  }
};
function $fC(remoteAuthority) {
  const plusIndex = remoteAuthority.indexOf("+");
  if (plusIndex === -1) {
    return remoteAuthority;
  }
  return remoteAuthority.substring(0, plusIndex);
}

// out-build/vs/workbench/api/common/extHostTypes.js
var $zT_1;
var $AT_1;
var $BT_1;
var $CT_1;
var $IT_1;
var $JT_1;
var $MT_1;
var $NT_1;
var $UT_1;
var $VT_1;
var $XT_1;
var $4T_1;
var $mU_1;
var $qU_1;
var $rU_1;
var $UU_1;
var $hV_1;
function es5ClassCompat(target) {
  const interceptFunctions = {
    apply: function(...args2) {
      if (args2.length === 0) {
        return Reflect.construct(target, []);
      } else {
        const argsList = args2.length === 1 ? [] : args2[1];
        return Reflect.construct(target, argsList, args2[0].constructor);
      }
    },
    call: function(...args2) {
      if (args2.length === 0) {
        return Reflect.construct(target, []);
      } else {
        const [thisArg, ...restArgs] = args2;
        return Reflect.construct(target, restArgs, thisArg.constructor);
      }
    }
  };
  return Object.assign(target, interceptFunctions);
}
var TerminalOutputAnchor;
(function(TerminalOutputAnchor2) {
  TerminalOutputAnchor2[TerminalOutputAnchor2["Top"] = 0] = "Top";
  TerminalOutputAnchor2[TerminalOutputAnchor2["Bottom"] = 1] = "Bottom";
})(TerminalOutputAnchor || (TerminalOutputAnchor = {}));
var TerminalQuickFixType;
(function(TerminalQuickFixType2) {
  TerminalQuickFixType2[TerminalQuickFixType2["TerminalCommand"] = 0] = "TerminalCommand";
  TerminalQuickFixType2[TerminalQuickFixType2["Opener"] = 1] = "Opener";
  TerminalQuickFixType2[TerminalQuickFixType2["Command"] = 3] = "Command";
})(TerminalQuickFixType || (TerminalQuickFixType = {}));
var $zT = $zT_1 = class $zT2 {
  static from(...inDisposables) {
    let disposables = inDisposables;
    return new $zT_1(function() {
      if (disposables) {
        for (const disposable of disposables) {
          if (disposable && typeof disposable.dispose === "function") {
            disposable.dispose();
          }
        }
        disposables = void 0;
      }
    });
  }
  #callOnDispose;
  constructor(callOnDispose) {
    this.#callOnDispose = callOnDispose;
  }
  dispose() {
    if (typeof this.#callOnDispose === "function") {
      this.#callOnDispose();
      this.#callOnDispose = void 0;
    }
  }
};
$zT = $zT_1 = __decorate([
  es5ClassCompat
], $zT);
var $AT = $AT_1 = class $AT2 {
  static Min(...positions) {
    if (positions.length === 0) {
      throw new TypeError();
    }
    let result = positions[0];
    for (let i = 1; i < positions.length; i++) {
      const p = positions[i];
      if (p.isBefore(result)) {
        result = p;
      }
    }
    return result;
  }
  static Max(...positions) {
    if (positions.length === 0) {
      throw new TypeError();
    }
    let result = positions[0];
    for (let i = 1; i < positions.length; i++) {
      const p = positions[i];
      if (p.isAfter(result)) {
        result = p;
      }
    }
    return result;
  }
  static isPosition(other) {
    if (!other) {
      return false;
    }
    if (other instanceof $AT_1) {
      return true;
    }
    const { line, character } = other;
    if (typeof line === "number" && typeof character === "number") {
      return true;
    }
    return false;
  }
  static of(obj) {
    if (obj instanceof $AT_1) {
      return obj;
    } else if (this.isPosition(obj)) {
      return new $AT_1(obj.line, obj.character);
    }
    throw new Error("Invalid argument, is NOT a position-like object");
  }
  get line() {
    return this.c;
  }
  get character() {
    return this.e;
  }
  constructor(line, character) {
    if (line < 0) {
      throw $nb("line must be non-negative");
    }
    if (character < 0) {
      throw $nb("character must be non-negative");
    }
    this.c = line;
    this.e = character;
  }
  isBefore(other) {
    if (this.c < other.c) {
      return true;
    }
    if (other.c < this.c) {
      return false;
    }
    return this.e < other.e;
  }
  isBeforeOrEqual(other) {
    if (this.c < other.c) {
      return true;
    }
    if (other.c < this.c) {
      return false;
    }
    return this.e <= other.e;
  }
  isAfter(other) {
    return !this.isBeforeOrEqual(other);
  }
  isAfterOrEqual(other) {
    return !this.isBefore(other);
  }
  isEqual(other) {
    return this.c === other.c && this.e === other.e;
  }
  compareTo(other) {
    if (this.c < other.c) {
      return -1;
    } else if (this.c > other.line) {
      return 1;
    } else {
      if (this.e < other.e) {
        return -1;
      } else if (this.e > other.e) {
        return 1;
      } else {
        return 0;
      }
    }
  }
  translate(lineDeltaOrChange, characterDelta = 0) {
    if (lineDeltaOrChange === null || characterDelta === null) {
      throw $nb();
    }
    let lineDelta;
    if (typeof lineDeltaOrChange === "undefined") {
      lineDelta = 0;
    } else if (typeof lineDeltaOrChange === "number") {
      lineDelta = lineDeltaOrChange;
    } else {
      lineDelta = typeof lineDeltaOrChange.lineDelta === "number" ? lineDeltaOrChange.lineDelta : 0;
      characterDelta = typeof lineDeltaOrChange.characterDelta === "number" ? lineDeltaOrChange.characterDelta : 0;
    }
    if (lineDelta === 0 && characterDelta === 0) {
      return this;
    }
    return new $AT_1(this.line + lineDelta, this.character + characterDelta);
  }
  with(lineOrChange, character = this.character) {
    if (lineOrChange === null || character === null) {
      throw $nb();
    }
    let line;
    if (typeof lineOrChange === "undefined") {
      line = this.line;
    } else if (typeof lineOrChange === "number") {
      line = lineOrChange;
    } else {
      line = typeof lineOrChange.line === "number" ? lineOrChange.line : this.line;
      character = typeof lineOrChange.character === "number" ? lineOrChange.character : this.character;
    }
    if (line === this.line && character === this.character) {
      return this;
    }
    return new $AT_1(line, character);
  }
  toJSON() {
    return { line: this.line, character: this.character };
  }
  [Symbol.for("debug.description")]() {
    return `(${this.line}:${this.character})`;
  }
};
$AT = $AT_1 = __decorate([
  es5ClassCompat
], $AT);
var $BT = $BT_1 = class $BT2 {
  static isRange(thing) {
    if (thing instanceof $BT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $AT.isPosition(thing.start) && $AT.isPosition(thing.end);
  }
  static of(obj) {
    if (obj instanceof $BT_1) {
      return obj;
    }
    if (this.isRange(obj)) {
      return new $BT_1(obj.start, obj.end);
    }
    throw new Error("Invalid argument, is NOT a range-like object");
  }
  get start() {
    return this.c;
  }
  get end() {
    return this.e;
  }
  constructor(startLineOrStart, startColumnOrEnd, endLine, endColumn) {
    let start;
    let end;
    if (typeof startLineOrStart === "number" && typeof startColumnOrEnd === "number" && typeof endLine === "number" && typeof endColumn === "number") {
      start = new $AT(startLineOrStart, startColumnOrEnd);
      end = new $AT(endLine, endColumn);
    } else if ($AT.isPosition(startLineOrStart) && $AT.isPosition(startColumnOrEnd)) {
      start = $AT.of(startLineOrStart);
      end = $AT.of(startColumnOrEnd);
    }
    if (!start || !end) {
      throw new Error("Invalid arguments");
    }
    if (start.isBefore(end)) {
      this.c = start;
      this.e = end;
    } else {
      this.c = end;
      this.e = start;
    }
  }
  contains(positionOrRange) {
    if ($BT_1.isRange(positionOrRange)) {
      return this.contains(positionOrRange.start) && this.contains(positionOrRange.end);
    } else if ($AT.isPosition(positionOrRange)) {
      if ($AT.of(positionOrRange).isBefore(this.c)) {
        return false;
      }
      if (this.e.isBefore(positionOrRange)) {
        return false;
      }
      return true;
    }
    return false;
  }
  isEqual(other) {
    return this.c.isEqual(other.c) && this.e.isEqual(other.e);
  }
  intersection(other) {
    const start = $AT.Max(other.start, this.c);
    const end = $AT.Min(other.end, this.e);
    if (start.isAfter(end)) {
      return void 0;
    }
    return new $BT_1(start, end);
  }
  union(other) {
    if (this.contains(other)) {
      return this;
    } else if (other.contains(this)) {
      return other;
    }
    const start = $AT.Min(other.start, this.c);
    const end = $AT.Max(other.end, this.end);
    return new $BT_1(start, end);
  }
  get isEmpty() {
    return this.c.isEqual(this.e);
  }
  get isSingleLine() {
    return this.c.line === this.e.line;
  }
  with(startOrChange, end = this.end) {
    if (startOrChange === null || end === null) {
      throw $nb();
    }
    let start;
    if (!startOrChange) {
      start = this.start;
    } else if ($AT.isPosition(startOrChange)) {
      start = startOrChange;
    } else {
      start = startOrChange.start || this.start;
      end = startOrChange.end || this.end;
    }
    if (start.isEqual(this.c) && end.isEqual(this.end)) {
      return this;
    }
    return new $BT_1(start, end);
  }
  toJSON() {
    return [this.start, this.end];
  }
  [Symbol.for("debug.description")]() {
    return $DT(this);
  }
};
$BT = $BT_1 = __decorate([
  es5ClassCompat
], $BT);
var $CT = $CT_1 = class $CT2 extends $BT {
  static isSelection(thing) {
    if (thing instanceof $CT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $BT.isRange(thing) && $AT.isPosition(thing.anchor) && $AT.isPosition(thing.active) && typeof thing.isReversed === "boolean";
  }
  get anchor() {
    return this.f;
  }
  get active() {
    return this.g;
  }
  constructor(anchorLineOrAnchor, anchorColumnOrActive, activeLine, activeColumn) {
    let anchor;
    let active;
    if (typeof anchorLineOrAnchor === "number" && typeof anchorColumnOrActive === "number" && typeof activeLine === "number" && typeof activeColumn === "number") {
      anchor = new $AT(anchorLineOrAnchor, anchorColumnOrActive);
      active = new $AT(activeLine, activeColumn);
    } else if ($AT.isPosition(anchorLineOrAnchor) && $AT.isPosition(anchorColumnOrActive)) {
      anchor = $AT.of(anchorLineOrAnchor);
      active = $AT.of(anchorColumnOrActive);
    }
    if (!anchor || !active) {
      throw new Error("Invalid arguments");
    }
    super(anchor, active);
    this.f = anchor;
    this.g = active;
  }
  get isReversed() {
    return this.f === this.e;
  }
  toJSON() {
    return {
      start: this.start,
      end: this.end,
      active: this.active,
      anchor: this.anchor
    };
  }
  [Symbol.for("debug.description")]() {
    return $ET(this);
  }
};
$CT = $CT_1 = __decorate([
  es5ClassCompat
], $CT);
function $DT(range) {
  return range.isEmpty ? `[${range.start.line}:${range.start.character})` : `[${range.start.line}:${range.start.character} -> ${range.end.line}:${range.end.character})`;
}
function $ET(selection) {
  let rangeStr = $DT(selection);
  if (!selection.isEmpty) {
    if (selection.active.isEqual(selection.start)) {
      rangeStr = `|${rangeStr}`;
    } else {
      rangeStr = `${rangeStr}|`;
    }
  }
  return rangeStr;
}
var validateConnectionToken = (connectionToken) => {
  if (typeof connectionToken !== "string" || connectionToken.length === 0 || !/^[0-9A-Za-z_\-]+$/.test(connectionToken)) {
    throw $nb("connectionToken");
  }
};
var $FT = class {
  static isResolvedAuthority(resolvedAuthority) {
    return resolvedAuthority && typeof resolvedAuthority === "object" && typeof resolvedAuthority.host === "string" && typeof resolvedAuthority.port === "number" && (resolvedAuthority.connectionToken === void 0 || typeof resolvedAuthority.connectionToken === "string");
  }
  constructor(host, port, connectionToken) {
    if (typeof host !== "string" || host.length === 0) {
      throw $nb("host");
    }
    if (typeof port !== "number" || port === 0 || Math.round(port) !== port) {
      throw $nb("port");
    }
    if (typeof connectionToken !== "undefined") {
      validateConnectionToken(connectionToken);
    }
    this.host = host;
    this.port = Math.round(port);
    this.connectionToken = connectionToken;
  }
};
var $GT = class {
  static isManagedResolvedAuthority(resolvedAuthority) {
    return resolvedAuthority && typeof resolvedAuthority === "object" && typeof resolvedAuthority.makeConnection === "function" && (resolvedAuthority.connectionToken === void 0 || typeof resolvedAuthority.connectionToken === "string");
  }
  constructor(makeConnection, connectionToken) {
    this.makeConnection = makeConnection;
    this.connectionToken = connectionToken;
    if (typeof connectionToken !== "undefined") {
      validateConnectionToken(connectionToken);
    }
  }
};
var $HT = class _$HT extends Error {
  static NotAvailable(message, handled) {
    return new _$HT(message, RemoteAuthorityResolverErrorCode.NotAvailable, handled);
  }
  static TemporarilyNotAvailable(message) {
    return new _$HT(message, RemoteAuthorityResolverErrorCode.TemporarilyNotAvailable);
  }
  constructor(message, code = RemoteAuthorityResolverErrorCode.Unknown, detail) {
    super(message);
    this._message = message;
    this._code = code;
    this._detail = detail;
    Object.setPrototypeOf(this, _$HT.prototype);
  }
};
var EndOfLine;
(function(EndOfLine3) {
  EndOfLine3[EndOfLine3["LF"] = 1] = "LF";
  EndOfLine3[EndOfLine3["CRLF"] = 2] = "CRLF";
})(EndOfLine || (EndOfLine = {}));
var EnvironmentVariableMutatorType;
(function(EnvironmentVariableMutatorType2) {
  EnvironmentVariableMutatorType2[EnvironmentVariableMutatorType2["Replace"] = 1] = "Replace";
  EnvironmentVariableMutatorType2[EnvironmentVariableMutatorType2["Append"] = 2] = "Append";
  EnvironmentVariableMutatorType2[EnvironmentVariableMutatorType2["Prepend"] = 3] = "Prepend";
})(EnvironmentVariableMutatorType || (EnvironmentVariableMutatorType = {}));
var $IT = $IT_1 = class $IT2 {
  static isTextEdit(thing) {
    if (thing instanceof $IT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $BT.isRange(thing) && typeof thing.newText === "string";
  }
  static replace(range, newText) {
    return new $IT_1(range, newText);
  }
  static insert(position, newText) {
    return $IT_1.replace(new $BT(position, position), newText);
  }
  static delete(range) {
    return $IT_1.replace(range, "");
  }
  static setEndOfLine(eol) {
    const ret = new $IT_1(new $BT(new $AT(0, 0), new $AT(0, 0)), "");
    ret.newEol = eol;
    return ret;
  }
  get range() {
    return this.c;
  }
  set range(value) {
    if (value && !$BT.isRange(value)) {
      throw $nb("range");
    }
    this.c = value;
  }
  get newText() {
    return this.e || "";
  }
  set newText(value) {
    if (value && typeof value !== "string") {
      throw $nb("newText");
    }
    this.e = value;
  }
  get newEol() {
    return this.f;
  }
  set newEol(value) {
    if (value && typeof value !== "number") {
      throw $nb("newEol");
    }
    this.f = value;
  }
  constructor(range, newText) {
    this.c = range;
    this.e = newText;
  }
  toJSON() {
    return {
      range: this.range,
      newText: this.newText,
      newEol: this.f
    };
  }
};
$IT = $IT_1 = __decorate([
  es5ClassCompat
], $IT);
var $JT = $JT_1 = class $JT2 {
  static isNotebookCellEdit(thing) {
    if (thing instanceof $JT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $6U.isNotebookRange(thing) && Array.isArray(thing.newCells);
  }
  static replaceCells(range, newCells) {
    return new $JT_1(range, newCells);
  }
  static insertCells(index, newCells) {
    return new $JT_1(new $6U(index, index), newCells);
  }
  static deleteCells(range) {
    return new $JT_1(range, []);
  }
  static updateCellMetadata(index, newMetadata) {
    const edit2 = new $JT_1(new $6U(index, index), []);
    edit2.newCellMetadata = newMetadata;
    return edit2;
  }
  static updateNotebookMetadata(newMetadata) {
    const edit2 = new $JT_1(new $6U(0, 0), []);
    edit2.newNotebookMetadata = newMetadata;
    return edit2;
  }
  constructor(range, newCells) {
    this.range = range;
    this.newCells = newCells;
  }
};
$JT = $JT_1 = __decorate([
  es5ClassCompat
], $JT);
var $KT = class _$KT {
  static isSnippetTextEdit(thing) {
    if (thing instanceof _$KT) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $BT.isRange(thing.range) && $MT.isSnippetString(thing.snippet);
  }
  static replace(range, snippet) {
    return new _$KT(range, snippet);
  }
  static insert(position, snippet) {
    return _$KT.replace(new $BT(position, position), snippet);
  }
  constructor(range, snippet) {
    this.range = range;
    this.snippet = snippet;
  }
};
var FileEditType;
(function(FileEditType2) {
  FileEditType2[FileEditType2["File"] = 1] = "File";
  FileEditType2[FileEditType2["Text"] = 2] = "Text";
  FileEditType2[FileEditType2["Cell"] = 3] = "Cell";
  FileEditType2[FileEditType2["CellReplace"] = 5] = "CellReplace";
  FileEditType2[FileEditType2["Snippet"] = 6] = "Snippet";
})(FileEditType || (FileEditType = {}));
var $LT = class $LT2 {
  constructor() {
    this.c = [];
  }
  _allEntries() {
    return this.c;
  }
  // --- file
  renameFile(from, to, options2, metadata) {
    this.c.push({ _type: 1, from, to, options: options2, metadata });
  }
  createFile(uri, options2, metadata) {
    this.c.push({ _type: 1, from: void 0, to: uri, options: options2, metadata });
  }
  deleteFile(uri, options2, metadata) {
    this.c.push({ _type: 1, from: uri, to: void 0, options: options2, metadata });
  }
  // --- notebook
  e(uri, value, metadata) {
    this.c.push({ _type: 3, metadata, uri, edit: { editType: 5, metadata: value } });
  }
  f(uri, startOrRange, cellData, metadata) {
    const start = startOrRange.start;
    const end = startOrRange.end;
    if (start !== end || cellData.length > 0) {
      this.c.push({ _type: 5, uri, index: start, count: end - start, cells: cellData, metadata });
    }
  }
  g(uri, index, cellMetadata, metadata) {
    this.c.push({ _type: 3, metadata, uri, edit: { editType: 3, index, metadata: cellMetadata } });
  }
  // --- text
  replace(uri, range, newText, metadata) {
    this.c.push({ _type: 2, uri, edit: new $IT(range, newText), metadata });
  }
  insert(resource, position, newText, metadata) {
    this.replace(resource, new $BT(position, position), newText, metadata);
  }
  delete(resource, range, metadata) {
    this.replace(resource, range, "", metadata);
  }
  // --- text (Maplike)
  has(uri) {
    return this.c.some((edit2) => edit2._type === 2 && edit2.uri.toString() === uri.toString());
  }
  set(uri, edits) {
    if (!edits) {
      for (let i = 0; i < this.c.length; i++) {
        const element = this.c[i];
        switch (element._type) {
          case 2:
          case 6:
          case 3:
          case 5:
            if (element.uri.toString() === uri.toString()) {
              this.c[i] = void 0;
            }
            break;
        }
      }
      $Nb(this.c);
    } else {
      for (const editOrTuple of edits) {
        if (!editOrTuple) {
          continue;
        }
        let edit2;
        let metadata;
        if (Array.isArray(editOrTuple)) {
          edit2 = editOrTuple[0];
          metadata = editOrTuple[1];
        } else {
          edit2 = editOrTuple;
        }
        if ($JT.isNotebookCellEdit(edit2)) {
          if (edit2.newCellMetadata) {
            this.g(uri, edit2.range.start, edit2.newCellMetadata, metadata);
          } else if (edit2.newNotebookMetadata) {
            this.e(uri, edit2.newNotebookMetadata, metadata);
          } else {
            this.f(uri, edit2.range, edit2.newCells, metadata);
          }
        } else if ($KT.isSnippetTextEdit(edit2)) {
          this.c.push({ _type: 6, uri, range: edit2.range, edit: edit2.snippet, metadata });
        } else {
          this.c.push({ _type: 2, uri, edit: edit2, metadata });
        }
      }
    }
  }
  get(uri) {
    const res = [];
    for (const candidate of this.c) {
      if (candidate._type === 2 && candidate.uri.toString() === uri.toString()) {
        res.push(candidate.edit);
      }
    }
    return res;
  }
  entries() {
    const textEdits = new $Ec();
    for (const candidate of this.c) {
      if (candidate._type === 2) {
        let textEdit = textEdits.get(candidate.uri);
        if (!textEdit) {
          textEdit = [candidate.uri, []];
          textEdits.set(candidate.uri, textEdit);
        }
        textEdit[1].push(candidate.edit);
      }
    }
    return [...textEdits.values()];
  }
  get size() {
    return this.entries().length;
  }
  toJSON() {
    return this.entries();
  }
};
$LT = __decorate([
  es5ClassCompat
], $LT);
var $MT = $MT_1 = class $MT2 {
  static isSnippetString(thing) {
    if (thing instanceof $MT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return typeof thing.value === "string";
  }
  static c(value) {
    return value.replace(/\$|}|\\/g, "\\$&");
  }
  constructor(value) {
    this.e = 1;
    this.value = value || "";
  }
  appendText(string) {
    this.value += $MT_1.c(string);
    return this;
  }
  appendTabstop(number = this.e++) {
    this.value += "$";
    this.value += number;
    return this;
  }
  appendPlaceholder(value, number = this.e++) {
    if (typeof value === "function") {
      const nested = new $MT_1();
      nested.e = this.e;
      value(nested);
      this.e = nested.e;
      value = nested.value;
    } else {
      value = $MT_1.c(value);
    }
    this.value += "${";
    this.value += number;
    this.value += ":";
    this.value += value;
    this.value += "}";
    return this;
  }
  appendChoice(values, number = this.e++) {
    const value = values.map((s) => s.replaceAll(/[|\\,]/g, "\\$&")).join(",");
    this.value += "${";
    this.value += number;
    this.value += "|";
    this.value += value;
    this.value += "|}";
    return this;
  }
  appendVariable(name, defaultValue) {
    if (typeof defaultValue === "function") {
      const nested = new $MT_1();
      nested.e = this.e;
      defaultValue(nested);
      this.e = nested.e;
      defaultValue = nested.value;
    } else if (typeof defaultValue === "string") {
      defaultValue = defaultValue.replace(/\$|}/g, "\\$&");
    }
    this.value += "${";
    this.value += name;
    if (defaultValue) {
      this.value += ":";
      this.value += defaultValue;
    }
    this.value += "}";
    return this;
  }
};
$MT = $MT_1 = __decorate([
  es5ClassCompat
], $MT);
var DiagnosticTag;
(function(DiagnosticTag3) {
  DiagnosticTag3[DiagnosticTag3["Unnecessary"] = 1] = "Unnecessary";
  DiagnosticTag3[DiagnosticTag3["Deprecated"] = 2] = "Deprecated";
})(DiagnosticTag || (DiagnosticTag = {}));
var DiagnosticSeverity;
(function(DiagnosticSeverity3) {
  DiagnosticSeverity3[DiagnosticSeverity3["Hint"] = 3] = "Hint";
  DiagnosticSeverity3[DiagnosticSeverity3["Information"] = 2] = "Information";
  DiagnosticSeverity3[DiagnosticSeverity3["Warning"] = 1] = "Warning";
  DiagnosticSeverity3[DiagnosticSeverity3["Error"] = 0] = "Error";
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
var $NT = $NT_1 = class $NT2 {
  static isLocation(thing) {
    if (thing instanceof $NT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $BT.isRange(thing.range) && URI.isUri(thing.uri);
  }
  constructor(uri, rangeOrPosition) {
    this.uri = uri;
    if (!rangeOrPosition) {
    } else if ($BT.isRange(rangeOrPosition)) {
      this.range = $BT.of(rangeOrPosition);
    } else if ($AT.isPosition(rangeOrPosition)) {
      this.range = new $BT(rangeOrPosition, rangeOrPosition);
    } else {
      throw new Error("Illegal argument");
    }
  }
  toJSON() {
    return {
      uri: this.uri,
      range: this.range
    };
  }
};
$NT = $NT_1 = __decorate([
  es5ClassCompat
], $NT);
var $OT = class $OT2 {
  static is(thing) {
    if (!thing) {
      return false;
    }
    return typeof thing.message === "string" && thing.location && $BT.isRange(thing.location.range) && URI.isUri(thing.location.uri);
  }
  constructor(location2, message) {
    this.location = location2;
    this.message = message;
  }
  static isEqual(a, b) {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.message === b.message && a.location.range.isEqual(b.location.range) && a.location.uri.toString() === b.location.uri.toString();
  }
};
$OT = __decorate([
  es5ClassCompat
], $OT);
var $PT = class $PT2 {
  constructor(range, message, severity = DiagnosticSeverity.Error) {
    if (!$BT.isRange(range)) {
      throw new TypeError("range must be set");
    }
    if (!message) {
      throw new TypeError("message must be set");
    }
    this.range = range;
    this.message = message;
    this.severity = severity;
  }
  toJSON() {
    return {
      severity: DiagnosticSeverity[this.severity],
      message: this.message,
      range: this.range,
      source: this.source,
      code: this.code
    };
  }
  static isEqual(a, b) {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.message === b.message && a.severity === b.severity && a.code === b.code && a.severity === b.severity && a.source === b.source && a.range.isEqual(b.range) && $zb(a.tags, b.tags) && $zb(a.relatedInformation, b.relatedInformation, $OT.isEqual);
  }
};
$PT = __decorate([
  es5ClassCompat
], $PT);
var $QT = class $QT2 {
  constructor(contents, range) {
    if (!contents) {
      throw new Error("Illegal argument, contents must be defined");
    }
    if (Array.isArray(contents)) {
      this.contents = contents;
    } else {
      this.contents = [contents];
    }
    this.range = range;
  }
};
$QT = __decorate([
  es5ClassCompat
], $QT);
var $RT = class $RT2 extends $QT {
  constructor(contents, range, canIncreaseVerbosity, canDecreaseVerbosity) {
    super(contents, range);
    this.canIncreaseVerbosity = canIncreaseVerbosity;
    this.canDecreaseVerbosity = canDecreaseVerbosity;
  }
};
$RT = __decorate([
  es5ClassCompat
], $RT);
var HoverVerbosityAction2;
(function(HoverVerbosityAction3) {
  HoverVerbosityAction3[HoverVerbosityAction3["Increase"] = 0] = "Increase";
  HoverVerbosityAction3[HoverVerbosityAction3["Decrease"] = 1] = "Decrease";
})(HoverVerbosityAction2 || (HoverVerbosityAction2 = {}));
var DocumentHighlightKind2;
(function(DocumentHighlightKind3) {
  DocumentHighlightKind3[DocumentHighlightKind3["Text"] = 0] = "Text";
  DocumentHighlightKind3[DocumentHighlightKind3["Read"] = 1] = "Read";
  DocumentHighlightKind3[DocumentHighlightKind3["Write"] = 2] = "Write";
})(DocumentHighlightKind2 || (DocumentHighlightKind2 = {}));
var $ST = class $ST2 {
  constructor(range, kind = DocumentHighlightKind2.Text) {
    this.range = range;
    this.kind = kind;
  }
  toJSON() {
    return {
      range: this.range,
      kind: DocumentHighlightKind2[this.kind]
    };
  }
};
$ST = __decorate([
  es5ClassCompat
], $ST);
var $TT = class $TT2 {
  constructor(uri, highlights) {
    this.uri = uri;
    this.highlights = highlights;
  }
  toJSON() {
    return {
      uri: this.uri,
      highlights: this.highlights.map((h) => h.toJSON())
    };
  }
};
$TT = __decorate([
  es5ClassCompat
], $TT);
var SymbolKind2;
(function(SymbolKind4) {
  SymbolKind4[SymbolKind4["File"] = 0] = "File";
  SymbolKind4[SymbolKind4["Module"] = 1] = "Module";
  SymbolKind4[SymbolKind4["Namespace"] = 2] = "Namespace";
  SymbolKind4[SymbolKind4["Package"] = 3] = "Package";
  SymbolKind4[SymbolKind4["Class"] = 4] = "Class";
  SymbolKind4[SymbolKind4["Method"] = 5] = "Method";
  SymbolKind4[SymbolKind4["Property"] = 6] = "Property";
  SymbolKind4[SymbolKind4["Field"] = 7] = "Field";
  SymbolKind4[SymbolKind4["Constructor"] = 8] = "Constructor";
  SymbolKind4[SymbolKind4["Enum"] = 9] = "Enum";
  SymbolKind4[SymbolKind4["Interface"] = 10] = "Interface";
  SymbolKind4[SymbolKind4["Function"] = 11] = "Function";
  SymbolKind4[SymbolKind4["Variable"] = 12] = "Variable";
  SymbolKind4[SymbolKind4["Constant"] = 13] = "Constant";
  SymbolKind4[SymbolKind4["String"] = 14] = "String";
  SymbolKind4[SymbolKind4["Number"] = 15] = "Number";
  SymbolKind4[SymbolKind4["Boolean"] = 16] = "Boolean";
  SymbolKind4[SymbolKind4["Array"] = 17] = "Array";
  SymbolKind4[SymbolKind4["Object"] = 18] = "Object";
  SymbolKind4[SymbolKind4["Key"] = 19] = "Key";
  SymbolKind4[SymbolKind4["Null"] = 20] = "Null";
  SymbolKind4[SymbolKind4["EnumMember"] = 21] = "EnumMember";
  SymbolKind4[SymbolKind4["Struct"] = 22] = "Struct";
  SymbolKind4[SymbolKind4["Event"] = 23] = "Event";
  SymbolKind4[SymbolKind4["Operator"] = 24] = "Operator";
  SymbolKind4[SymbolKind4["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind2 || (SymbolKind2 = {}));
var SymbolTag2;
(function(SymbolTag4) {
  SymbolTag4[SymbolTag4["Deprecated"] = 1] = "Deprecated";
})(SymbolTag2 || (SymbolTag2 = {}));
var $UT = $UT_1 = class $UT2 {
  static validate(candidate) {
    if (!candidate.name) {
      throw new Error("name must not be falsy");
    }
  }
  constructor(name, kind, rangeOrContainer, locationOrUri, containerName) {
    this.name = name;
    this.kind = kind;
    this.containerName = containerName;
    if (typeof rangeOrContainer === "string") {
      this.containerName = rangeOrContainer;
    }
    if (locationOrUri instanceof $NT) {
      this.location = locationOrUri;
    } else if (rangeOrContainer instanceof $BT) {
      this.location = new $NT(locationOrUri, rangeOrContainer);
    }
    $UT_1.validate(this);
  }
  toJSON() {
    return {
      name: this.name,
      kind: SymbolKind2[this.kind],
      location: this.location,
      containerName: this.containerName
    };
  }
};
$UT = $UT_1 = __decorate([
  es5ClassCompat
], $UT);
var $VT = $VT_1 = class $VT2 {
  static validate(candidate) {
    if (!candidate.name) {
      throw new Error("name must not be falsy");
    }
    if (!candidate.range.contains(candidate.selectionRange)) {
      throw new Error("selectionRange must be contained in fullRange");
    }
    candidate.children?.forEach($VT_1.validate);
  }
  constructor(name, detail, kind, range, selectionRange) {
    this.name = name;
    this.detail = detail;
    this.kind = kind;
    this.range = range;
    this.selectionRange = selectionRange;
    this.children = [];
    $VT_1.validate(this);
  }
};
$VT = $VT_1 = __decorate([
  es5ClassCompat
], $VT);
var CodeActionTriggerKind;
(function(CodeActionTriggerKind3) {
  CodeActionTriggerKind3[CodeActionTriggerKind3["Invoke"] = 1] = "Invoke";
  CodeActionTriggerKind3[CodeActionTriggerKind3["Automatic"] = 2] = "Automatic";
})(CodeActionTriggerKind || (CodeActionTriggerKind = {}));
var $WT = class $WT2 {
  constructor(title, kind) {
    this.title = title;
    this.kind = kind;
  }
};
$WT = __decorate([
  es5ClassCompat
], $WT);
var $XT = class $XT2 {
  static {
    $XT_1 = this;
  }
  static {
    this.c = ".";
  }
  constructor(value) {
    this.value = value;
  }
  append(parts) {
    return new $XT_1(this.value ? this.value + $XT_1.c + parts : parts);
  }
  intersects(other) {
    return this.contains(other) || other.contains(this);
  }
  contains(other) {
    return this.value === other.value || other.value.startsWith(this.value + $XT_1.c);
  }
};
$XT = $XT_1 = __decorate([
  es5ClassCompat
], $XT);
$XT.Empty = new $XT("");
$XT.QuickFix = $XT.Empty.append("quickfix");
$XT.Refactor = $XT.Empty.append("refactor");
$XT.RefactorExtract = $XT.Refactor.append("extract");
$XT.RefactorInline = $XT.Refactor.append("inline");
$XT.RefactorMove = $XT.Refactor.append("move");
$XT.RefactorRewrite = $XT.Refactor.append("rewrite");
$XT.Source = $XT.Empty.append("source");
$XT.SourceOrganizeImports = $XT.Source.append("organizeImports");
$XT.SourceFixAll = $XT.Source.append("fixAll");
$XT.Notebook = $XT.Empty.append("notebook");
var $YT = class $YT2 {
  constructor(range, parent) {
    this.range = range;
    this.parent = parent;
    if (parent && !parent.range.contains(this.range)) {
      throw new Error("Invalid argument: parent must contain this range");
    }
  }
};
$YT = __decorate([
  es5ClassCompat
], $YT);
var $ZT = class {
  constructor(kind, name, detail, uri, range, selectionRange) {
    this.kind = kind;
    this.name = name;
    this.detail = detail;
    this.uri = uri;
    this.range = range;
    this.selectionRange = selectionRange;
  }
};
var $1T = class {
  constructor(item, fromRanges) {
    this.fromRanges = fromRanges;
    this.from = item;
  }
};
var $2T = class {
  constructor(item, fromRanges) {
    this.fromRanges = fromRanges;
    this.to = item;
  }
};
var LanguageStatusSeverity;
(function(LanguageStatusSeverity2) {
  LanguageStatusSeverity2[LanguageStatusSeverity2["Information"] = 0] = "Information";
  LanguageStatusSeverity2[LanguageStatusSeverity2["Warning"] = 1] = "Warning";
  LanguageStatusSeverity2[LanguageStatusSeverity2["Error"] = 2] = "Error";
})(LanguageStatusSeverity || (LanguageStatusSeverity = {}));
var $3T = class $3T2 {
  constructor(range, command) {
    this.range = range;
    this.command = command;
  }
  get isResolved() {
    return !!this.command;
  }
};
$3T = __decorate([
  es5ClassCompat
], $3T);
var $4T = $4T_1 = class $4T2 {
  #delegate;
  static isMarkdownString(thing) {
    if (thing instanceof $4T_1) {
      return true;
    }
    return thing && thing.appendCodeblock && thing.appendMarkdown && thing.appendText && thing.value !== void 0;
  }
  constructor(value, supportThemeIcons = false) {
    this.#delegate = new $bm(value, { supportThemeIcons });
  }
  get value() {
    return this.#delegate.value;
  }
  set value(value) {
    this.#delegate.value = value;
  }
  get isTrusted() {
    return this.#delegate.isTrusted;
  }
  set isTrusted(value) {
    this.#delegate.isTrusted = value;
  }
  get supportThemeIcons() {
    return this.#delegate.supportThemeIcons;
  }
  set supportThemeIcons(value) {
    this.#delegate.supportThemeIcons = value;
  }
  get supportHtml() {
    return this.#delegate.supportHtml;
  }
  set supportHtml(value) {
    this.#delegate.supportHtml = value;
  }
  get baseUri() {
    return this.#delegate.baseUri;
  }
  set baseUri(value) {
    this.#delegate.baseUri = value;
  }
  appendText(value) {
    this.#delegate.appendText(value);
    return this;
  }
  appendMarkdown(value) {
    this.#delegate.appendMarkdown(value);
    return this;
  }
  appendCodeblock(value, language) {
    this.#delegate.appendCodeblock(language ?? "", value);
    return this;
  }
};
$4T = $4T_1 = __decorate([
  es5ClassCompat
], $4T);
var $5T = class $5T2 {
  constructor(label, documentation) {
    this.label = label;
    this.documentation = documentation;
  }
};
$5T = __decorate([
  es5ClassCompat
], $5T);
var $6T = class $6T2 {
  constructor(label, documentation) {
    this.label = label;
    this.documentation = documentation;
    this.parameters = [];
  }
};
$6T = __decorate([
  es5ClassCompat
], $6T);
var $7T = class $7T2 {
  constructor() {
    this.activeSignature = 0;
    this.activeParameter = 0;
    this.signatures = [];
  }
};
$7T = __decorate([
  es5ClassCompat
], $7T);
var SignatureHelpTriggerKind2;
(function(SignatureHelpTriggerKind3) {
  SignatureHelpTriggerKind3[SignatureHelpTriggerKind3["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind3[SignatureHelpTriggerKind3["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind3[SignatureHelpTriggerKind3["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind2 || (SignatureHelpTriggerKind2 = {}));
var InlayHintKind2;
(function(InlayHintKind4) {
  InlayHintKind4[InlayHintKind4["Type"] = 1] = "Type";
  InlayHintKind4[InlayHintKind4["Parameter"] = 2] = "Parameter";
})(InlayHintKind2 || (InlayHintKind2 = {}));
var $8T = class $8T2 {
  constructor(value) {
    this.value = value;
  }
};
$8T = __decorate([
  es5ClassCompat
], $8T);
var $9T = class $9T2 {
  constructor(position, label, kind) {
    this.position = position;
    this.label = label;
    this.kind = kind;
  }
};
$9T = __decorate([
  es5ClassCompat
], $9T);
var CompletionTriggerKind2;
(function(CompletionTriggerKind4) {
  CompletionTriggerKind4[CompletionTriggerKind4["Invoke"] = 0] = "Invoke";
  CompletionTriggerKind4[CompletionTriggerKind4["TriggerCharacter"] = 1] = "TriggerCharacter";
  CompletionTriggerKind4[CompletionTriggerKind4["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind2 || (CompletionTriggerKind2 = {}));
var CompletionItemKind2;
(function(CompletionItemKind4) {
  CompletionItemKind4[CompletionItemKind4["Text"] = 0] = "Text";
  CompletionItemKind4[CompletionItemKind4["Method"] = 1] = "Method";
  CompletionItemKind4[CompletionItemKind4["Function"] = 2] = "Function";
  CompletionItemKind4[CompletionItemKind4["Constructor"] = 3] = "Constructor";
  CompletionItemKind4[CompletionItemKind4["Field"] = 4] = "Field";
  CompletionItemKind4[CompletionItemKind4["Variable"] = 5] = "Variable";
  CompletionItemKind4[CompletionItemKind4["Class"] = 6] = "Class";
  CompletionItemKind4[CompletionItemKind4["Interface"] = 7] = "Interface";
  CompletionItemKind4[CompletionItemKind4["Module"] = 8] = "Module";
  CompletionItemKind4[CompletionItemKind4["Property"] = 9] = "Property";
  CompletionItemKind4[CompletionItemKind4["Unit"] = 10] = "Unit";
  CompletionItemKind4[CompletionItemKind4["Value"] = 11] = "Value";
  CompletionItemKind4[CompletionItemKind4["Enum"] = 12] = "Enum";
  CompletionItemKind4[CompletionItemKind4["Keyword"] = 13] = "Keyword";
  CompletionItemKind4[CompletionItemKind4["Snippet"] = 14] = "Snippet";
  CompletionItemKind4[CompletionItemKind4["Color"] = 15] = "Color";
  CompletionItemKind4[CompletionItemKind4["File"] = 16] = "File";
  CompletionItemKind4[CompletionItemKind4["Reference"] = 17] = "Reference";
  CompletionItemKind4[CompletionItemKind4["Folder"] = 18] = "Folder";
  CompletionItemKind4[CompletionItemKind4["EnumMember"] = 19] = "EnumMember";
  CompletionItemKind4[CompletionItemKind4["Constant"] = 20] = "Constant";
  CompletionItemKind4[CompletionItemKind4["Struct"] = 21] = "Struct";
  CompletionItemKind4[CompletionItemKind4["Event"] = 22] = "Event";
  CompletionItemKind4[CompletionItemKind4["Operator"] = 23] = "Operator";
  CompletionItemKind4[CompletionItemKind4["TypeParameter"] = 24] = "TypeParameter";
  CompletionItemKind4[CompletionItemKind4["User"] = 25] = "User";
  CompletionItemKind4[CompletionItemKind4["Issue"] = 26] = "Issue";
})(CompletionItemKind2 || (CompletionItemKind2 = {}));
var CompletionItemTag2;
(function(CompletionItemTag4) {
  CompletionItemTag4[CompletionItemTag4["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag2 || (CompletionItemTag2 = {}));
var $0T = class $0T2 {
  constructor(label, kind) {
    this.label = label;
    this.kind = kind;
  }
  toJSON() {
    return {
      label: this.label,
      kind: this.kind && CompletionItemKind2[this.kind],
      detail: this.detail,
      documentation: this.documentation,
      sortText: this.sortText,
      filterText: this.filterText,
      preselect: this.preselect,
      insertText: this.insertText,
      textEdit: this.textEdit
    };
  }
};
$0T = __decorate([
  es5ClassCompat
], $0T);
var $$T = class $$T2 {
  constructor(items = [], isIncomplete = false) {
    this.items = items;
    this.isIncomplete = isIncomplete;
  }
};
$$T = __decorate([
  es5ClassCompat
], $$T);
var $_T = class $_T2 {
  constructor(insertText, range, command) {
    this.insertText = insertText;
    this.range = range;
    this.command = command;
  }
};
$_T = __decorate([
  es5ClassCompat
], $_T);
var $aU = class $aU2 {
  constructor(items) {
    this.commands = void 0;
    this.suppressSuggestions = void 0;
    this.items = items;
  }
};
$aU = __decorate([
  es5ClassCompat
], $aU);
var PartialAcceptTriggerKind2;
(function(PartialAcceptTriggerKind4) {
  PartialAcceptTriggerKind4[PartialAcceptTriggerKind4["Unknown"] = 0] = "Unknown";
  PartialAcceptTriggerKind4[PartialAcceptTriggerKind4["Word"] = 1] = "Word";
  PartialAcceptTriggerKind4[PartialAcceptTriggerKind4["Line"] = 2] = "Line";
  PartialAcceptTriggerKind4[PartialAcceptTriggerKind4["Suggest"] = 3] = "Suggest";
})(PartialAcceptTriggerKind2 || (PartialAcceptTriggerKind2 = {}));
var ViewColumn;
(function(ViewColumn3) {
  ViewColumn3[ViewColumn3["Active"] = -1] = "Active";
  ViewColumn3[ViewColumn3["Beside"] = -2] = "Beside";
  ViewColumn3[ViewColumn3["One"] = 1] = "One";
  ViewColumn3[ViewColumn3["Two"] = 2] = "Two";
  ViewColumn3[ViewColumn3["Three"] = 3] = "Three";
  ViewColumn3[ViewColumn3["Four"] = 4] = "Four";
  ViewColumn3[ViewColumn3["Five"] = 5] = "Five";
  ViewColumn3[ViewColumn3["Six"] = 6] = "Six";
  ViewColumn3[ViewColumn3["Seven"] = 7] = "Seven";
  ViewColumn3[ViewColumn3["Eight"] = 8] = "Eight";
  ViewColumn3[ViewColumn3["Nine"] = 9] = "Nine";
})(ViewColumn || (ViewColumn = {}));
var StatusBarAlignment;
(function(StatusBarAlignment2) {
  StatusBarAlignment2[StatusBarAlignment2["Left"] = 1] = "Left";
  StatusBarAlignment2[StatusBarAlignment2["Right"] = 2] = "Right";
})(StatusBarAlignment || (StatusBarAlignment = {}));
function $bU(extension, id2) {
  return `${$5z.toKey(extension)}.${id2}`;
}
var TextEditorLineNumbersStyle;
(function(TextEditorLineNumbersStyle3) {
  TextEditorLineNumbersStyle3[TextEditorLineNumbersStyle3["Off"] = 0] = "Off";
  TextEditorLineNumbersStyle3[TextEditorLineNumbersStyle3["On"] = 1] = "On";
  TextEditorLineNumbersStyle3[TextEditorLineNumbersStyle3["Relative"] = 2] = "Relative";
  TextEditorLineNumbersStyle3[TextEditorLineNumbersStyle3["Interval"] = 3] = "Interval";
})(TextEditorLineNumbersStyle || (TextEditorLineNumbersStyle = {}));
var TextDocumentSaveReason;
(function(TextDocumentSaveReason3) {
  TextDocumentSaveReason3[TextDocumentSaveReason3["Manual"] = 1] = "Manual";
  TextDocumentSaveReason3[TextDocumentSaveReason3["AfterDelay"] = 2] = "AfterDelay";
  TextDocumentSaveReason3[TextDocumentSaveReason3["FocusOut"] = 3] = "FocusOut";
})(TextDocumentSaveReason || (TextDocumentSaveReason = {}));
var TextEditorRevealType2;
(function(TextEditorRevealType3) {
  TextEditorRevealType3[TextEditorRevealType3["Default"] = 0] = "Default";
  TextEditorRevealType3[TextEditorRevealType3["InCenter"] = 1] = "InCenter";
  TextEditorRevealType3[TextEditorRevealType3["InCenterIfOutsideViewport"] = 2] = "InCenterIfOutsideViewport";
  TextEditorRevealType3[TextEditorRevealType3["AtTop"] = 3] = "AtTop";
})(TextEditorRevealType2 || (TextEditorRevealType2 = {}));
var TextEditorSelectionChangeKind;
(function(TextEditorSelectionChangeKind2) {
  TextEditorSelectionChangeKind2[TextEditorSelectionChangeKind2["Keyboard"] = 1] = "Keyboard";
  TextEditorSelectionChangeKind2[TextEditorSelectionChangeKind2["Mouse"] = 2] = "Mouse";
  TextEditorSelectionChangeKind2[TextEditorSelectionChangeKind2["Command"] = 3] = "Command";
})(TextEditorSelectionChangeKind || (TextEditorSelectionChangeKind = {}));
var TextEditorChangeKind;
(function(TextEditorChangeKind2) {
  TextEditorChangeKind2[TextEditorChangeKind2["Addition"] = 1] = "Addition";
  TextEditorChangeKind2[TextEditorChangeKind2["Deletion"] = 2] = "Deletion";
  TextEditorChangeKind2[TextEditorChangeKind2["Modification"] = 3] = "Modification";
})(TextEditorChangeKind || (TextEditorChangeKind = {}));
var TextDocumentChangeReason;
(function(TextDocumentChangeReason2) {
  TextDocumentChangeReason2[TextDocumentChangeReason2["Undo"] = 1] = "Undo";
  TextDocumentChangeReason2[TextDocumentChangeReason2["Redo"] = 2] = "Redo";
})(TextDocumentChangeReason || (TextDocumentChangeReason = {}));
var DecorationRangeBehavior;
(function(DecorationRangeBehavior3) {
  DecorationRangeBehavior3[DecorationRangeBehavior3["OpenOpen"] = 0] = "OpenOpen";
  DecorationRangeBehavior3[DecorationRangeBehavior3["ClosedClosed"] = 1] = "ClosedClosed";
  DecorationRangeBehavior3[DecorationRangeBehavior3["OpenClosed"] = 2] = "OpenClosed";
  DecorationRangeBehavior3[DecorationRangeBehavior3["ClosedOpen"] = 3] = "ClosedOpen";
})(DecorationRangeBehavior || (DecorationRangeBehavior = {}));
(function(TextEditorSelectionChangeKind2) {
  function fromValue(s) {
    switch (s) {
      case "keyboard":
        return TextEditorSelectionChangeKind2.Keyboard;
      case "mouse":
        return TextEditorSelectionChangeKind2.Mouse;
      case "api":
        return TextEditorSelectionChangeKind2.Command;
    }
    return void 0;
  }
  TextEditorSelectionChangeKind2.fromValue = fromValue;
})(TextEditorSelectionChangeKind || (TextEditorSelectionChangeKind = {}));
var SyntaxTokenType;
(function(SyntaxTokenType2) {
  SyntaxTokenType2[SyntaxTokenType2["Other"] = 0] = "Other";
  SyntaxTokenType2[SyntaxTokenType2["Comment"] = 1] = "Comment";
  SyntaxTokenType2[SyntaxTokenType2["String"] = 2] = "String";
  SyntaxTokenType2[SyntaxTokenType2["RegEx"] = 3] = "RegEx";
})(SyntaxTokenType || (SyntaxTokenType = {}));
(function(SyntaxTokenType2) {
  function toString(v) {
    switch (v) {
      case SyntaxTokenType2.Other:
        return "other";
      case SyntaxTokenType2.Comment:
        return "comment";
      case SyntaxTokenType2.String:
        return "string";
      case SyntaxTokenType2.RegEx:
        return "regex";
    }
    return "other";
  }
  SyntaxTokenType2.toString = toString;
})(SyntaxTokenType || (SyntaxTokenType = {}));
var $cU = class $cU2 {
  constructor(range, target) {
    if (target && !URI.isUri(target)) {
      throw $nb("target");
    }
    if (!$BT.isRange(range) || range.isEmpty) {
      throw $nb("range");
    }
    this.range = range;
    this.target = target;
  }
};
$cU = __decorate([
  es5ClassCompat
], $cU);
var $dU = class $dU2 {
  constructor(red, green, blue, alpha) {
    this.red = red;
    this.green = green;
    this.blue = blue;
    this.alpha = alpha;
  }
};
$dU = __decorate([
  es5ClassCompat
], $dU);
var $eU = class $eU2 {
  constructor(range, color2) {
    if (color2 && !(color2 instanceof $dU)) {
      throw $nb("color");
    }
    if (!$BT.isRange(range) || range.isEmpty) {
      throw $nb("range");
    }
    this.range = range;
    this.color = color2;
  }
};
$eU = __decorate([
  es5ClassCompat
], $eU);
var $fU = class $fU2 {
  constructor(label) {
    if (!label || typeof label !== "string") {
      throw $nb("label");
    }
    this.label = label;
  }
};
$fU = __decorate([
  es5ClassCompat
], $fU);
var ColorFormat;
(function(ColorFormat2) {
  ColorFormat2[ColorFormat2["RGB"] = 0] = "RGB";
  ColorFormat2[ColorFormat2["HEX"] = 1] = "HEX";
  ColorFormat2[ColorFormat2["HSL"] = 2] = "HSL";
})(ColorFormat || (ColorFormat = {}));
var SourceControlInputBoxValidationType;
(function(SourceControlInputBoxValidationType2) {
  SourceControlInputBoxValidationType2[SourceControlInputBoxValidationType2["Error"] = 0] = "Error";
  SourceControlInputBoxValidationType2[SourceControlInputBoxValidationType2["Warning"] = 1] = "Warning";
  SourceControlInputBoxValidationType2[SourceControlInputBoxValidationType2["Information"] = 2] = "Information";
})(SourceControlInputBoxValidationType || (SourceControlInputBoxValidationType = {}));
var TerminalExitReason;
(function(TerminalExitReason2) {
  TerminalExitReason2[TerminalExitReason2["Unknown"] = 0] = "Unknown";
  TerminalExitReason2[TerminalExitReason2["Shutdown"] = 1] = "Shutdown";
  TerminalExitReason2[TerminalExitReason2["Process"] = 2] = "Process";
  TerminalExitReason2[TerminalExitReason2["User"] = 3] = "User";
  TerminalExitReason2[TerminalExitReason2["Extension"] = 4] = "Extension";
})(TerminalExitReason || (TerminalExitReason = {}));
var TerminalShellExecutionCommandLineConfidence;
(function(TerminalShellExecutionCommandLineConfidence2) {
  TerminalShellExecutionCommandLineConfidence2[TerminalShellExecutionCommandLineConfidence2["Low"] = 0] = "Low";
  TerminalShellExecutionCommandLineConfidence2[TerminalShellExecutionCommandLineConfidence2["Medium"] = 1] = "Medium";
  TerminalShellExecutionCommandLineConfidence2[TerminalShellExecutionCommandLineConfidence2["High"] = 2] = "High";
})(TerminalShellExecutionCommandLineConfidence || (TerminalShellExecutionCommandLineConfidence = {}));
var $gU = class {
  constructor(startIndex, length, tooltip) {
    this.startIndex = startIndex;
    this.length = length;
    this.tooltip = tooltip;
    if (typeof startIndex !== "number" || startIndex < 0) {
      throw $nb("startIndex");
    }
    if (typeof length !== "number" || length < 1) {
      throw $nb("length");
    }
    if (tooltip !== void 0 && typeof tooltip !== "string") {
      throw $nb("tooltip");
    }
  }
};
var $hU = class {
  constructor(uri) {
    this.uri = uri;
  }
};
var $iU = class {
  constructor(terminalCommand) {
    this.terminalCommand = terminalCommand;
  }
};
var TerminalLocation;
(function(TerminalLocation2) {
  TerminalLocation2[TerminalLocation2["Panel"] = 1] = "Panel";
  TerminalLocation2[TerminalLocation2["Editor"] = 2] = "Editor";
})(TerminalLocation || (TerminalLocation = {}));
var $jU = class {
  constructor(options2) {
    this.options = options2;
    if (typeof options2 !== "object") {
      throw $nb("options");
    }
  }
};
var TerminalCompletionItemKind;
(function(TerminalCompletionItemKind2) {
  TerminalCompletionItemKind2[TerminalCompletionItemKind2["File"] = 0] = "File";
  TerminalCompletionItemKind2[TerminalCompletionItemKind2["Folder"] = 1] = "Folder";
  TerminalCompletionItemKind2[TerminalCompletionItemKind2["Flag"] = 2] = "Flag";
  TerminalCompletionItemKind2[TerminalCompletionItemKind2["Method"] = 3] = "Method";
  TerminalCompletionItemKind2[TerminalCompletionItemKind2["Argument"] = 4] = "Argument";
})(TerminalCompletionItemKind || (TerminalCompletionItemKind = {}));
var $kU = class {
  constructor(label, icon, detail, isFile, isDirectory, isKeyword, replacementIndex, replacementLength) {
    this.label = label;
    this.icon = icon;
    this.detail = detail;
    this.isFile = isFile;
    this.isDirectory = isDirectory;
    this.isKeyword = isKeyword;
    this.replacementIndex = replacementIndex ?? 0;
    this.replacementLength = replacementLength ?? 0;
  }
};
var $lU = class {
  /**
   * Creates a new completion list.
   *
   * @param items The completion items.
   * @param isIncomplete The list is not complete.
   */
  constructor(items, resourceRequestConfig) {
    this.items = items ?? [];
    this.resourceRequestConfig = resourceRequestConfig;
  }
};
var TaskRevealKind;
(function(TaskRevealKind2) {
  TaskRevealKind2[TaskRevealKind2["Always"] = 1] = "Always";
  TaskRevealKind2[TaskRevealKind2["Silent"] = 2] = "Silent";
  TaskRevealKind2[TaskRevealKind2["Never"] = 3] = "Never";
})(TaskRevealKind || (TaskRevealKind = {}));
var TaskPanelKind;
(function(TaskPanelKind2) {
  TaskPanelKind2[TaskPanelKind2["Shared"] = 1] = "Shared";
  TaskPanelKind2[TaskPanelKind2["Dedicated"] = 2] = "Dedicated";
  TaskPanelKind2[TaskPanelKind2["New"] = 3] = "New";
})(TaskPanelKind || (TaskPanelKind = {}));
var $mU = class $mU2 {
  static {
    $mU_1 = this;
  }
  static {
    this.Clean = new $mU_1("clean", "Clean");
  }
  static {
    this.Build = new $mU_1("build", "Build");
  }
  static {
    this.Rebuild = new $mU_1("rebuild", "Rebuild");
  }
  static {
    this.Test = new $mU_1("test", "Test");
  }
  static from(value) {
    switch (value) {
      case "clean":
        return $mU_1.Clean;
      case "build":
        return $mU_1.Build;
      case "rebuild":
        return $mU_1.Rebuild;
      case "test":
        return $mU_1.Test;
      default:
        return void 0;
    }
  }
  constructor(id2, label) {
    this.label = label;
    if (typeof id2 !== "string") {
      throw $nb("name");
    }
    if (typeof label !== "string") {
      throw $nb("name");
    }
    this.c = id2;
  }
  get id() {
    return this.c;
  }
};
$mU = $mU_1 = __decorate([
  es5ClassCompat
], $mU);
function computeTaskExecutionId(values) {
  let id2 = "";
  for (let i = 0; i < values.length; i++) {
    id2 += values[i].replace(/,/g, ",,") + ",";
  }
  return id2;
}
var $nU = class $nU2 {
  constructor(process2, varg1, varg2) {
    if (typeof process2 !== "string") {
      throw $nb("process");
    }
    this.e = [];
    this.c = process2;
    if (varg1 !== void 0) {
      if (Array.isArray(varg1)) {
        this.e = varg1;
        this.f = varg2;
      } else {
        this.f = varg1;
      }
    }
  }
  get process() {
    return this.c;
  }
  set process(value) {
    if (typeof value !== "string") {
      throw $nb("process");
    }
    this.c = value;
  }
  get args() {
    return this.e;
  }
  set args(value) {
    if (!Array.isArray(value)) {
      value = [];
    }
    this.e = value;
  }
  get options() {
    return this.f;
  }
  set options(value) {
    this.f = value;
  }
  computeId() {
    const props = [];
    props.push("process");
    if (this.c !== void 0) {
      props.push(this.c);
    }
    if (this.e && this.e.length > 0) {
      for (const arg of this.e) {
        props.push(arg);
      }
    }
    return computeTaskExecutionId(props);
  }
};
$nU = __decorate([
  es5ClassCompat
], $nU);
var $oU = class $oU2 {
  constructor(arg0, arg1, arg2) {
    this.f = [];
    if (Array.isArray(arg1)) {
      if (!arg0) {
        throw $nb("command can't be undefined or null");
      }
      if (typeof arg0 !== "string" && typeof arg0.value !== "string") {
        throw $nb("command");
      }
      this.e = arg0;
      this.f = arg1;
      this.g = arg2;
    } else {
      if (typeof arg0 !== "string") {
        throw $nb("commandLine");
      }
      this.c = arg0;
      this.g = arg1;
    }
  }
  get commandLine() {
    return this.c;
  }
  set commandLine(value) {
    if (typeof value !== "string") {
      throw $nb("commandLine");
    }
    this.c = value;
  }
  get command() {
    return this.e ? this.e : "";
  }
  set command(value) {
    if (typeof value !== "string" && typeof value.value !== "string") {
      throw $nb("command");
    }
    this.e = value;
  }
  get args() {
    return this.f;
  }
  set args(value) {
    this.f = value || [];
  }
  get options() {
    return this.g;
  }
  set options(value) {
    this.g = value;
  }
  computeId() {
    const props = [];
    props.push("shell");
    if (this.c !== void 0) {
      props.push(this.c);
    }
    if (this.e !== void 0) {
      props.push(typeof this.e === "string" ? this.e : this.e.value);
    }
    if (this.f && this.f.length > 0) {
      for (const arg of this.f) {
        props.push(typeof arg === "string" ? arg : arg.value);
      }
    }
    return computeTaskExecutionId(props);
  }
};
$oU = __decorate([
  es5ClassCompat
], $oU);
var ShellQuoting;
(function(ShellQuoting3) {
  ShellQuoting3[ShellQuoting3["Escape"] = 1] = "Escape";
  ShellQuoting3[ShellQuoting3["Strong"] = 2] = "Strong";
  ShellQuoting3[ShellQuoting3["Weak"] = 3] = "Weak";
})(ShellQuoting || (ShellQuoting = {}));
var TaskScope;
(function(TaskScope3) {
  TaskScope3[TaskScope3["Global"] = 1] = "Global";
  TaskScope3[TaskScope3["Workspace"] = 2] = "Workspace";
})(TaskScope || (TaskScope = {}));
var $pU = class {
  constructor(callback) {
    this.c = callback;
  }
  computeId() {
    return "customExecution" + $ps();
  }
  set callback(value) {
    this.c = value;
  }
  get callback() {
    return this.c;
  }
};
var $qU = class $qU2 {
  static {
    $qU_1 = this;
  }
  static {
    this.c = "customExecution";
  }
  static {
    this.e = "process";
  }
  static {
    this.f = "shell";
  }
  static {
    this.g = "$empty";
  }
  constructor(definition, arg2, arg3, arg4, arg5, arg6) {
    this.k = false;
    this.l = this.definition = definition;
    let problemMatchers;
    if (typeof arg2 === "string") {
      this.o = this.name = arg2;
      this.w = this.source = arg3;
      this.execution = arg4;
      problemMatchers = arg5;
      this.k = true;
    } else if (arg2 === TaskScope.Global || arg2 === TaskScope.Workspace) {
      this.target = arg2;
      this.o = this.name = arg3;
      this.w = this.source = arg4;
      this.execution = arg5;
      problemMatchers = arg6;
    } else {
      this.target = arg2;
      this.o = this.name = arg3;
      this.w = this.source = arg4;
      this.execution = arg5;
      problemMatchers = arg6;
    }
    if (typeof problemMatchers === "string") {
      this.r = [problemMatchers];
      this.t = true;
    } else if (Array.isArray(problemMatchers)) {
      this.r = problemMatchers;
      this.t = true;
    } else {
      this.r = [];
      this.t = false;
    }
    this.u = false;
    this.y = /* @__PURE__ */ Object.create(null);
    this.z = /* @__PURE__ */ Object.create(null);
  }
  get _id() {
    return this.j;
  }
  set _id(value) {
    this.j = value;
  }
  get _deprecated() {
    return this.k;
  }
  B() {
    if (this.j === void 0) {
      return;
    }
    this.j = void 0;
    this.m = void 0;
    this.C();
  }
  C() {
    if (this.q instanceof $nU) {
      this.l = {
        type: $qU_1.e,
        id: this.q.computeId()
      };
    } else if (this.q instanceof $oU) {
      this.l = {
        type: $qU_1.f,
        id: this.q.computeId()
      };
    } else if (this.q instanceof $pU) {
      this.l = {
        type: $qU_1.c,
        id: this.q.computeId()
      };
    } else {
      this.l = {
        type: $qU_1.g,
        id: $ps()
      };
    }
  }
  get definition() {
    return this.l;
  }
  set definition(value) {
    if (value === void 0 || value === null) {
      throw $nb("Kind can't be undefined or null");
    }
    this.B();
    this.l = value;
  }
  get scope() {
    return this.m;
  }
  set target(value) {
    this.B();
    this.m = value;
  }
  get name() {
    return this.o;
  }
  set name(value) {
    if (typeof value !== "string") {
      throw $nb("name");
    }
    this.B();
    this.o = value;
  }
  get execution() {
    return this.q;
  }
  set execution(value) {
    if (value === null) {
      value = void 0;
    }
    this.B();
    this.q = value;
    const type = this.l.type;
    if ($qU_1.g === type || $qU_1.e === type || $qU_1.f === type || $qU_1.c === type) {
      this.C();
    }
  }
  get problemMatchers() {
    return this.r;
  }
  set problemMatchers(value) {
    if (!Array.isArray(value)) {
      this.B();
      this.r = [];
      this.t = false;
      return;
    } else {
      this.B();
      this.r = value;
      this.t = true;
    }
  }
  get hasDefinedMatchers() {
    return this.t;
  }
  get isBackground() {
    return this.u;
  }
  set isBackground(value) {
    if (value !== true && value !== false) {
      value = false;
    }
    this.B();
    this.u = value;
  }
  get source() {
    return this.w;
  }
  set source(value) {
    if (typeof value !== "string" || value.length === 0) {
      throw $nb("source must be a string of length > 0");
    }
    this.B();
    this.w = value;
  }
  get group() {
    return this.x;
  }
  set group(value) {
    if (value === null) {
      value = void 0;
    }
    this.B();
    this.x = value;
  }
  get detail() {
    return this.A;
  }
  set detail(value) {
    if (value === null) {
      value = void 0;
    }
    this.A = value;
  }
  get presentationOptions() {
    return this.y;
  }
  set presentationOptions(value) {
    if (value === null || value === void 0) {
      value = /* @__PURE__ */ Object.create(null);
    }
    this.B();
    this.y = value;
  }
  get runOptions() {
    return this.z;
  }
  set runOptions(value) {
    if (value === null || value === void 0) {
      value = /* @__PURE__ */ Object.create(null);
    }
    this.B();
    this.z = value;
  }
};
$qU = $qU_1 = __decorate([
  es5ClassCompat
], $qU);
var ProgressLocation;
(function(ProgressLocation4) {
  ProgressLocation4[ProgressLocation4["SourceControl"] = 1] = "SourceControl";
  ProgressLocation4[ProgressLocation4["Window"] = 10] = "Window";
  ProgressLocation4[ProgressLocation4["Notification"] = 15] = "Notification";
})(ProgressLocation || (ProgressLocation = {}));
var ViewBadge;
(function(ViewBadge3) {
  function isViewBadge(thing) {
    const viewBadgeThing = thing;
    if (!$Dg(viewBadgeThing.value)) {
      console.log("INVALID view badge, invalid value", viewBadgeThing.value);
      return false;
    }
    if (viewBadgeThing.tooltip && !$zg(viewBadgeThing.tooltip)) {
      console.log("INVALID view badge, invalid tooltip", viewBadgeThing.tooltip);
      return false;
    }
    return true;
  }
  ViewBadge3.isViewBadge = isViewBadge;
})(ViewBadge || (ViewBadge = {}));
var $rU = $rU_1 = class $rU2 {
  static isTreeItem(thing, extension) {
    const treeItemThing = thing;
    if (treeItemThing.checkboxState !== void 0) {
      const checkbox = $Dg(treeItemThing.checkboxState) ? treeItemThing.checkboxState : $Bg(treeItemThing.checkboxState) && $Dg(treeItemThing.checkboxState.state) ? treeItemThing.checkboxState.state : void 0;
      const tooltip = !$Dg(treeItemThing.checkboxState) && $Bg(treeItemThing.checkboxState) ? treeItemThing.checkboxState.tooltip : void 0;
      if (checkbox === void 0 || checkbox !== TreeItemCheckboxState.Checked && checkbox !== TreeItemCheckboxState.Unchecked || tooltip !== void 0 && !$zg(tooltip)) {
        console.log("INVALID tree item, invalid checkboxState", treeItemThing.checkboxState);
        return false;
      }
    }
    if (thing instanceof $rU_1) {
      return true;
    }
    if (treeItemThing.label !== void 0 && !$zg(treeItemThing.label) && !treeItemThing.label?.label) {
      console.log("INVALID tree item, invalid label", treeItemThing.label);
      return false;
    }
    if (treeItemThing.id !== void 0 && !$zg(treeItemThing.id)) {
      console.log("INVALID tree item, invalid id", treeItemThing.id);
      return false;
    }
    if (treeItemThing.iconPath !== void 0 && !$zg(treeItemThing.iconPath) && !URI.isUri(treeItemThing.iconPath) && (!treeItemThing.iconPath || !$zg(treeItemThing.iconPath.id))) {
      const asLightAndDarkThing = treeItemThing.iconPath;
      if (!asLightAndDarkThing || !$zg(asLightAndDarkThing.light) && !URI.isUri(asLightAndDarkThing.light) && !$zg(asLightAndDarkThing.dark) && !URI.isUri(asLightAndDarkThing.dark)) {
        console.log("INVALID tree item, invalid iconPath", treeItemThing.iconPath);
        return false;
      }
    }
    if (treeItemThing.description !== void 0 && !$zg(treeItemThing.description) && typeof treeItemThing.description !== "boolean") {
      console.log("INVALID tree item, invalid description", treeItemThing.description);
      return false;
    }
    if (treeItemThing.resourceUri !== void 0 && !URI.isUri(treeItemThing.resourceUri)) {
      console.log("INVALID tree item, invalid resourceUri", treeItemThing.resourceUri);
      return false;
    }
    if (treeItemThing.tooltip !== void 0 && !$zg(treeItemThing.tooltip) && !(treeItemThing.tooltip instanceof $4T)) {
      console.log("INVALID tree item, invalid tooltip", treeItemThing.tooltip);
      return false;
    }
    if (treeItemThing.command !== void 0 && !treeItemThing.command.command) {
      console.log("INVALID tree item, invalid command", treeItemThing.command);
      return false;
    }
    if (treeItemThing.collapsibleState !== void 0 && treeItemThing.collapsibleState < TreeItemCollapsibleState.None && treeItemThing.collapsibleState > TreeItemCollapsibleState.Expanded) {
      console.log("INVALID tree item, invalid collapsibleState", treeItemThing.collapsibleState);
      return false;
    }
    if (treeItemThing.contextValue !== void 0 && !$zg(treeItemThing.contextValue)) {
      console.log("INVALID tree item, invalid contextValue", treeItemThing.contextValue);
      return false;
    }
    if (treeItemThing.accessibilityInformation !== void 0 && !treeItemThing.accessibilityInformation?.label) {
      console.log("INVALID tree item, invalid accessibilityInformation", treeItemThing.accessibilityInformation);
      return false;
    }
    return true;
  }
  constructor(arg1, collapsibleState = TreeItemCollapsibleState.None) {
    this.collapsibleState = collapsibleState;
    if (URI.isUri(arg1)) {
      this.resourceUri = arg1;
    } else {
      this.label = arg1;
    }
  }
};
$rU = $rU_1 = __decorate([
  es5ClassCompat
], $rU);
var TreeItemCollapsibleState;
(function(TreeItemCollapsibleState3) {
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["None"] = 0] = "None";
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["Collapsed"] = 1] = "Collapsed";
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["Expanded"] = 2] = "Expanded";
})(TreeItemCollapsibleState || (TreeItemCollapsibleState = {}));
var TreeItemCheckboxState;
(function(TreeItemCheckboxState2) {
  TreeItemCheckboxState2[TreeItemCheckboxState2["Unchecked"] = 0] = "Unchecked";
  TreeItemCheckboxState2[TreeItemCheckboxState2["Checked"] = 1] = "Checked";
})(TreeItemCheckboxState || (TreeItemCheckboxState = {}));
var $sU = class $sU2 {
  async asString() {
    return typeof this.value === "string" ? this.value : JSON.stringify(this.value);
  }
  asFile() {
    return void 0;
  }
  constructor(value) {
    this.value = value;
  }
};
$sU = __decorate([
  es5ClassCompat
], $sU);
var $tU = class extends $sU {
};
var $uU = class extends $tU {
  #file;
  constructor(file) {
    super("");
    this.#file = file;
  }
  asFile() {
    return this.#file;
  }
};
var $vU = class {
  constructor(name, uri, itemId, getData) {
    this.name = name;
    this.uri = uri;
    this._itemId = itemId;
    this.c = getData;
  }
  data() {
    return this.c();
  }
};
var $wU = class $wU2 {
  #items = /* @__PURE__ */ new Map();
  constructor(init) {
    for (const [mime, item] of init ?? []) {
      const existing = this.#items.get(this.#normalizeMime(mime));
      if (existing) {
        existing.push(item);
      } else {
        this.#items.set(this.#normalizeMime(mime), [item]);
      }
    }
  }
  get(mimeType) {
    return this.#items.get(this.#normalizeMime(mimeType))?.[0];
  }
  set(mimeType, value) {
    this.#items.set(this.#normalizeMime(mimeType), [value]);
  }
  forEach(callbackfn, thisArg) {
    for (const [mime, items] of this.#items) {
      for (const item of items) {
        callbackfn.call(thisArg, item, mime, this);
      }
    }
  }
  *[Symbol.iterator]() {
    for (const [mime, items] of this.#items) {
      for (const item of items) {
        yield [mime, item];
      }
    }
  }
  #normalizeMime(mimeType) {
    return mimeType.toLowerCase();
  }
};
$wU = __decorate([
  es5ClassCompat
], $wU);
var $xU = class $xU2 {
  constructor(insertText, title, kind) {
    this.insertText = insertText;
    this.title = title;
    this.kind = kind;
  }
};
$xU = __decorate([
  es5ClassCompat
], $xU);
var DocumentPasteTriggerKind2;
(function(DocumentPasteTriggerKind3) {
  DocumentPasteTriggerKind3[DocumentPasteTriggerKind3["Automatic"] = 0] = "Automatic";
  DocumentPasteTriggerKind3[DocumentPasteTriggerKind3["PasteAs"] = 1] = "PasteAs";
})(DocumentPasteTriggerKind2 || (DocumentPasteTriggerKind2 = {}));
var $yU = class _$yU {
  static {
    this.c = ".";
  }
  constructor(value) {
    this.value = value;
  }
  append(...parts) {
    return new _$yU((this.value ? [this.value, ...parts] : parts).join(_$yU.c));
  }
  intersects(other) {
    return this.contains(other) || other.contains(this);
  }
  contains(other) {
    return this.value === other.value || other.value.startsWith(this.value + _$yU.c);
  }
};
$yU.Empty = new $yU("");
$yU.Text = new $yU("text");
var $zU = class {
  constructor(insertText, title, kind) {
    this.title = title;
    this.insertText = insertText;
    this.kind = kind;
  }
};
var $AU = class $AU2 {
  constructor(id2, color2) {
    this.id = id2;
    this.color = color2;
  }
  static isThemeIcon(thing) {
    if (typeof thing.id !== "string") {
      console.log("INVALID ThemeIcon, invalid id", thing.id);
      return false;
    }
    return true;
  }
};
$AU = __decorate([
  es5ClassCompat
], $AU);
$AU.File = new $AU("file");
$AU.Folder = new $AU("folder");
var $BU = class $BU2 {
  constructor(id2) {
    this.id = id2;
  }
};
$BU = __decorate([
  es5ClassCompat
], $BU);
var ConfigurationTarget2;
(function(ConfigurationTarget3) {
  ConfigurationTarget3[ConfigurationTarget3["Global"] = 1] = "Global";
  ConfigurationTarget3[ConfigurationTarget3["Workspace"] = 2] = "Workspace";
  ConfigurationTarget3[ConfigurationTarget3["WorkspaceFolder"] = 3] = "WorkspaceFolder";
})(ConfigurationTarget2 || (ConfigurationTarget2 = {}));
var $CU = class $CU2 {
  get base() {
    return this.c;
  }
  set base(base) {
    this.c = base;
    this.e = URI.file(base);
  }
  get baseUri() {
    return this.e;
  }
  set baseUri(baseUri) {
    this.e = baseUri;
    this.c = baseUri.fsPath;
  }
  constructor(base, pattern) {
    if (typeof base !== "string") {
      if (!base || !URI.isUri(base) && !URI.isUri(base.uri)) {
        throw $nb("base");
      }
    }
    if (typeof pattern !== "string") {
      throw $nb("pattern");
    }
    if (typeof base === "string") {
      this.baseUri = URI.file(base);
    } else if (URI.isUri(base)) {
      this.baseUri = base;
    } else {
      this.baseUri = base.uri;
    }
    this.pattern = pattern;
  }
  toJSON() {
    return {
      pattern: this.pattern,
      base: this.base,
      baseUri: this.baseUri.toJSON()
    };
  }
};
$CU = __decorate([
  es5ClassCompat
], $CU);
var breakpointIds = /* @__PURE__ */ new WeakMap();
function $DU(bp, id2) {
  breakpointIds.set(bp, id2);
}
var $EU = class $EU2 {
  constructor(enabled, condition, hitCondition, logMessage, mode) {
    this.enabled = typeof enabled === "boolean" ? enabled : true;
    if (typeof condition === "string") {
      this.condition = condition;
    }
    if (typeof hitCondition === "string") {
      this.hitCondition = hitCondition;
    }
    if (typeof logMessage === "string") {
      this.logMessage = logMessage;
    }
    if (typeof mode === "string") {
      this.mode = mode;
    }
  }
  get id() {
    if (!this.c) {
      this.c = breakpointIds.get(this) ?? $ps();
    }
    return this.c;
  }
};
$EU = __decorate([
  es5ClassCompat
], $EU);
var $FU = class $FU2 extends $EU {
  constructor(location2, enabled, condition, hitCondition, logMessage, mode) {
    super(enabled, condition, hitCondition, logMessage, mode);
    if (location2 === null) {
      throw $nb("location");
    }
    this.location = location2;
  }
};
$FU = __decorate([
  es5ClassCompat
], $FU);
var $GU = class $GU2 extends $EU {
  constructor(functionName, enabled, condition, hitCondition, logMessage, mode) {
    super(enabled, condition, hitCondition, logMessage, mode);
    this.functionName = functionName;
  }
};
$GU = __decorate([
  es5ClassCompat
], $GU);
var $HU = class $HU2 extends $EU {
  constructor(label, dataId, canPersist, enabled, condition, hitCondition, logMessage, mode) {
    super(enabled, condition, hitCondition, logMessage, mode);
    if (!dataId) {
      throw $nb("dataId");
    }
    this.label = label;
    this.dataId = dataId;
    this.canPersist = canPersist;
  }
};
$HU = __decorate([
  es5ClassCompat
], $HU);
var $IU = class $IU2 {
  constructor(command, args2, options2) {
    this.command = command;
    this.args = args2 || [];
    this.options = options2;
  }
};
$IU = __decorate([
  es5ClassCompat
], $IU);
var $JU = class $JU2 {
  constructor(port, host) {
    this.port = port;
    this.host = host;
  }
};
$JU = __decorate([
  es5ClassCompat
], $JU);
var $KU = class $KU2 {
  constructor(path) {
    this.path = path;
  }
};
$KU = __decorate([
  es5ClassCompat
], $KU);
var $LU = class $LU2 {
  constructor(impl) {
    this.implementation = impl;
  }
};
$LU = __decorate([
  es5ClassCompat
], $LU);
var $MU = class {
  constructor(session, threadId, frameId) {
    this.session = session;
    this.threadId = threadId;
    this.frameId = frameId;
  }
};
var $NU = class {
  constructor(session, threadId) {
    this.session = session;
    this.threadId = threadId;
  }
};
var $OU = class $OU2 {
  constructor(range, expression) {
    this.range = range;
    this.expression = expression;
  }
};
$OU = __decorate([
  es5ClassCompat
], $OU);
var InlineCompletionTriggerKind2;
(function(InlineCompletionTriggerKind3) {
  InlineCompletionTriggerKind3[InlineCompletionTriggerKind3["Invoke"] = 0] = "Invoke";
  InlineCompletionTriggerKind3[InlineCompletionTriggerKind3["Automatic"] = 1] = "Automatic";
})(InlineCompletionTriggerKind2 || (InlineCompletionTriggerKind2 = {}));
var $PU = class $PU2 {
  constructor(range, text) {
    this.range = range;
    this.text = text;
  }
};
$PU = __decorate([
  es5ClassCompat
], $PU);
var $QU = class $QU2 {
  constructor(range, variableName, caseSensitiveLookup = true) {
    this.range = range;
    this.variableName = variableName;
    this.caseSensitiveLookup = caseSensitiveLookup;
  }
};
$QU = __decorate([
  es5ClassCompat
], $QU);
var $RU = class $RU2 {
  constructor(range, expression) {
    this.range = range;
    this.expression = expression;
  }
};
$RU = __decorate([
  es5ClassCompat
], $RU);
var $SU = class $SU2 {
  constructor(frameId, range) {
    this.frameId = frameId;
    this.stoppedLocation = range;
  }
};
$SU = __decorate([
  es5ClassCompat
], $SU);
var NewSymbolNameTag2;
(function(NewSymbolNameTag3) {
  NewSymbolNameTag3[NewSymbolNameTag3["AIGenerated"] = 1] = "AIGenerated";
})(NewSymbolNameTag2 || (NewSymbolNameTag2 = {}));
var NewSymbolNameTriggerKind2;
(function(NewSymbolNameTriggerKind3) {
  NewSymbolNameTriggerKind3[NewSymbolNameTriggerKind3["Invoke"] = 0] = "Invoke";
  NewSymbolNameTriggerKind3[NewSymbolNameTriggerKind3["Automatic"] = 1] = "Automatic";
})(NewSymbolNameTriggerKind2 || (NewSymbolNameTriggerKind2 = {}));
var $TU = class {
  constructor(newSymbolName, tags) {
    this.newSymbolName = newSymbolName;
    this.tags = tags;
  }
};
var FileChangeType2;
(function(FileChangeType3) {
  FileChangeType3[FileChangeType3["Changed"] = 1] = "Changed";
  FileChangeType3[FileChangeType3["Created"] = 2] = "Created";
  FileChangeType3[FileChangeType3["Deleted"] = 3] = "Deleted";
})(FileChangeType2 || (FileChangeType2 = {}));
var $UU = $UU_1 = class $UU2 extends Error {
  static FileExists(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.FileExists, $UU_1.FileExists);
  }
  static FileNotFound(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.FileNotFound, $UU_1.FileNotFound);
  }
  static FileNotADirectory(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.FileNotADirectory, $UU_1.FileNotADirectory);
  }
  static FileIsADirectory(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.FileIsADirectory, $UU_1.FileIsADirectory);
  }
  static NoPermissions(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.NoPermissions, $UU_1.NoPermissions);
  }
  static Unavailable(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.Unavailable, $UU_1.Unavailable);
  }
  constructor(uriOrMessage, code = FileSystemProviderErrorCode.Unknown, terminator) {
    super(URI.isUri(uriOrMessage) ? uriOrMessage.toString(true) : uriOrMessage);
    this.code = terminator?.name ?? "Unknown";
    $zm(this, code);
    Object.setPrototypeOf(this, $UU_1.prototype);
    if (typeof Error.captureStackTrace === "function" && typeof terminator === "function") {
      Error.captureStackTrace(this, terminator);
    }
  }
};
$UU = $UU_1 = __decorate([
  es5ClassCompat
], $UU);
var $VU = class $VU2 {
  constructor(start, end, kind) {
    this.start = start;
    this.end = end;
    this.kind = kind;
  }
};
$VU = __decorate([
  es5ClassCompat
], $VU);
var FoldingRangeKind;
(function(FoldingRangeKind3) {
  FoldingRangeKind3[FoldingRangeKind3["Comment"] = 1] = "Comment";
  FoldingRangeKind3[FoldingRangeKind3["Imports"] = 2] = "Imports";
  FoldingRangeKind3[FoldingRangeKind3["Region"] = 3] = "Region";
})(FoldingRangeKind || (FoldingRangeKind = {}));
var CommentThreadCollapsibleState2;
(function(CommentThreadCollapsibleState3) {
  CommentThreadCollapsibleState3[CommentThreadCollapsibleState3["Collapsed"] = 0] = "Collapsed";
  CommentThreadCollapsibleState3[CommentThreadCollapsibleState3["Expanded"] = 1] = "Expanded";
})(CommentThreadCollapsibleState2 || (CommentThreadCollapsibleState2 = {}));
var CommentMode2;
(function(CommentMode3) {
  CommentMode3[CommentMode3["Editing"] = 0] = "Editing";
  CommentMode3[CommentMode3["Preview"] = 1] = "Preview";
})(CommentMode2 || (CommentMode2 = {}));
var CommentState2;
(function(CommentState3) {
  CommentState3[CommentState3["Published"] = 0] = "Published";
  CommentState3[CommentState3["Draft"] = 1] = "Draft";
})(CommentState2 || (CommentState2 = {}));
var CommentThreadState2;
(function(CommentThreadState3) {
  CommentThreadState3[CommentThreadState3["Unresolved"] = 0] = "Unresolved";
  CommentThreadState3[CommentThreadState3["Resolved"] = 1] = "Resolved";
})(CommentThreadState2 || (CommentThreadState2 = {}));
var CommentThreadApplicability2;
(function(CommentThreadApplicability3) {
  CommentThreadApplicability3[CommentThreadApplicability3["Current"] = 0] = "Current";
  CommentThreadApplicability3[CommentThreadApplicability3["Outdated"] = 1] = "Outdated";
})(CommentThreadApplicability2 || (CommentThreadApplicability2 = {}));
var CommentThreadFocus;
(function(CommentThreadFocus2) {
  CommentThreadFocus2[CommentThreadFocus2["Reply"] = 1] = "Reply";
  CommentThreadFocus2[CommentThreadFocus2["Comment"] = 2] = "Comment";
})(CommentThreadFocus || (CommentThreadFocus = {}));
var $WU = class {
  constructor(tokenTypes, tokenModifiers = []) {
    this.tokenTypes = tokenTypes;
    this.tokenModifiers = tokenModifiers;
  }
};
function isStrArrayOrUndefined(arg) {
  return typeof arg === "undefined" || $Ag(arg);
}
var $XU = class _$XU {
  constructor(legend) {
    this.c = 0;
    this.e = 0;
    this.f = true;
    this.g = [];
    this.j = 0;
    this.k = /* @__PURE__ */ new Map();
    this.l = /* @__PURE__ */ new Map();
    this.m = false;
    if (legend) {
      this.m = true;
      for (let i = 0, len = legend.tokenTypes.length; i < len; i++) {
        this.k.set(legend.tokenTypes[i], i);
      }
      for (let i = 0, len = legend.tokenModifiers.length; i < len; i++) {
        this.l.set(legend.tokenModifiers[i], i);
      }
    }
  }
  push(arg0, arg1, arg2, arg3, arg4) {
    if (typeof arg0 === "number" && typeof arg1 === "number" && typeof arg2 === "number" && typeof arg3 === "number" && (typeof arg4 === "number" || typeof arg4 === "undefined")) {
      if (typeof arg4 === "undefined") {
        arg4 = 0;
      }
      return this.q(arg0, arg1, arg2, arg3, arg4);
    }
    if ($BT.isRange(arg0) && typeof arg1 === "string" && isStrArrayOrUndefined(arg2)) {
      return this.o(arg0, arg1, arg2);
    }
    throw $nb();
  }
  o(range, tokenType, tokenModifiers) {
    if (!this.m) {
      throw new Error("Legend must be provided in constructor");
    }
    if (range.start.line !== range.end.line) {
      throw new Error("`range` cannot span multiple lines");
    }
    if (!this.k.has(tokenType)) {
      throw new Error("`tokenType` is not in the provided legend");
    }
    const line = range.start.line;
    const char = range.start.character;
    const length = range.end.character - range.start.character;
    const nTokenType = this.k.get(tokenType);
    let nTokenModifiers = 0;
    if (tokenModifiers) {
      for (const tokenModifier of tokenModifiers) {
        if (!this.l.has(tokenModifier)) {
          throw new Error("`tokenModifier` is not in the provided legend");
        }
        const nTokenModifier = this.l.get(tokenModifier);
        nTokenModifiers |= 1 << nTokenModifier >>> 0;
      }
    }
    this.q(line, char, length, nTokenType, nTokenModifiers);
  }
  q(line, char, length, tokenType, tokenModifiers) {
    if (this.f && (line < this.c || line === this.c && char < this.e)) {
      this.f = false;
      const tokenCount = this.g.length / 5 | 0;
      let prevLine = 0;
      let prevChar = 0;
      for (let i = 0; i < tokenCount; i++) {
        let line2 = this.g[5 * i];
        let char2 = this.g[5 * i + 1];
        if (line2 === 0) {
          line2 = prevLine;
          char2 += prevChar;
        } else {
          line2 += prevLine;
        }
        this.g[5 * i] = line2;
        this.g[5 * i + 1] = char2;
        prevLine = line2;
        prevChar = char2;
      }
    }
    let pushLine = line;
    let pushChar = char;
    if (this.f && this.j > 0) {
      pushLine -= this.c;
      if (pushLine === 0) {
        pushChar -= this.e;
      }
    }
    this.g[this.j++] = pushLine;
    this.g[this.j++] = pushChar;
    this.g[this.j++] = length;
    this.g[this.j++] = tokenType;
    this.g[this.j++] = tokenModifiers;
    this.c = line;
    this.e = char;
  }
  static r(data) {
    const pos = [];
    const tokenCount = data.length / 5 | 0;
    for (let i = 0; i < tokenCount; i++) {
      pos[i] = i;
    }
    pos.sort((a, b) => {
      const aLine = data[5 * a];
      const bLine = data[5 * b];
      if (aLine === bLine) {
        const aChar = data[5 * a + 1];
        const bChar = data[5 * b + 1];
        return aChar - bChar;
      }
      return aLine - bLine;
    });
    const result = new Uint32Array(data.length);
    let prevLine = 0;
    let prevChar = 0;
    for (let i = 0; i < tokenCount; i++) {
      const srcOffset = 5 * pos[i];
      const line = data[srcOffset + 0];
      const char = data[srcOffset + 1];
      const length = data[srcOffset + 2];
      const tokenType = data[srcOffset + 3];
      const tokenModifiers = data[srcOffset + 4];
      const pushLine = line - prevLine;
      const pushChar = pushLine === 0 ? char - prevChar : char;
      const dstOffset = 5 * i;
      result[dstOffset + 0] = pushLine;
      result[dstOffset + 1] = pushChar;
      result[dstOffset + 2] = length;
      result[dstOffset + 3] = tokenType;
      result[dstOffset + 4] = tokenModifiers;
      prevLine = line;
      prevChar = char;
    }
    return result;
  }
  build(resultId) {
    if (!this.f) {
      return new $YU(_$XU.r(this.g), resultId);
    }
    return new $YU(new Uint32Array(this.g), resultId);
  }
};
var $YU = class {
  constructor(data, resultId) {
    this.resultId = resultId;
    this.data = data;
  }
};
var $ZU = class {
  constructor(start, deleteCount, data) {
    this.start = start;
    this.deleteCount = deleteCount;
    this.data = data;
  }
};
var $1U = class {
  constructor(edits, resultId) {
    this.resultId = resultId;
    this.edits = edits;
  }
};
var DebugConsoleMode;
(function(DebugConsoleMode2) {
  DebugConsoleMode2[DebugConsoleMode2["Separate"] = 0] = "Separate";
  DebugConsoleMode2[DebugConsoleMode2["MergeWithParent"] = 1] = "MergeWithParent";
})(DebugConsoleMode || (DebugConsoleMode = {}));
var $2U = class {
  constructor(name) {
    this.name = name;
  }
};
var QuickInputButtonLocation;
(function(QuickInputButtonLocation2) {
  QuickInputButtonLocation2[QuickInputButtonLocation2["Title"] = 1] = "Title";
  QuickInputButtonLocation2[QuickInputButtonLocation2["Inline"] = 2] = "Inline";
})(QuickInputButtonLocation || (QuickInputButtonLocation = {}));
var $3U = class $3U2 {
  static {
    this.Back = { iconPath: new $AU("arrow-left") };
  }
  constructor() {
  }
};
$3U = __decorate([
  es5ClassCompat
], $3U);
var QuickPickItemKind;
(function(QuickPickItemKind2) {
  QuickPickItemKind2[QuickPickItemKind2["Separator"] = -1] = "Separator";
  QuickPickItemKind2[QuickPickItemKind2["Default"] = 0] = "Default";
})(QuickPickItemKind || (QuickPickItemKind = {}));
var InputBoxValidationSeverity;
(function(InputBoxValidationSeverity2) {
  InputBoxValidationSeverity2[InputBoxValidationSeverity2["Info"] = 1] = "Info";
  InputBoxValidationSeverity2[InputBoxValidationSeverity2["Warning"] = 2] = "Warning";
  InputBoxValidationSeverity2[InputBoxValidationSeverity2["Error"] = 3] = "Error";
})(InputBoxValidationSeverity || (InputBoxValidationSeverity = {}));
var ExtensionKind;
(function(ExtensionKind2) {
  ExtensionKind2[ExtensionKind2["UI"] = 1] = "UI";
  ExtensionKind2[ExtensionKind2["Workspace"] = 2] = "Workspace";
})(ExtensionKind || (ExtensionKind = {}));
var $4U = class {
  static validate(d) {
    if (typeof d.badge === "string") {
      let len = $$f(d.badge, 0);
      if (len < d.badge.length) {
        len += $$f(d.badge, len);
      }
      if (d.badge.length > len) {
        throw new Error(`The 'badge'-property must be undefined or a short character`);
      }
    } else if (d.badge) {
      if (!$AU.isThemeIcon(d.badge)) {
        throw new Error(`The 'badge'-property is not a valid ThemeIcon`);
      }
    }
    if (!d.color && !d.badge && !d.tooltip) {
      throw new Error(`The decoration is empty`);
    }
    return true;
  }
  constructor(badge, tooltip, color2) {
    this.badge = badge;
    this.tooltip = tooltip;
    this.color = color2;
  }
};
var $5U = class $5U2 {
  constructor(kind) {
    this.kind = kind;
  }
};
$5U = __decorate([
  es5ClassCompat
], $5U);
var ColorThemeKind;
(function(ColorThemeKind2) {
  ColorThemeKind2[ColorThemeKind2["Light"] = 1] = "Light";
  ColorThemeKind2[ColorThemeKind2["Dark"] = 2] = "Dark";
  ColorThemeKind2[ColorThemeKind2["HighContrast"] = 3] = "HighContrast";
  ColorThemeKind2[ColorThemeKind2["HighContrastLight"] = 4] = "HighContrastLight";
})(ColorThemeKind || (ColorThemeKind = {}));
var $6U = class _$6U {
  static isNotebookRange(thing) {
    if (thing instanceof _$6U) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return typeof thing.start === "number" && typeof thing.end === "number";
  }
  get start() {
    return this.c;
  }
  get end() {
    return this.e;
  }
  get isEmpty() {
    return this.c === this.e;
  }
  constructor(start, end) {
    if (start < 0) {
      throw $nb("start must be positive");
    }
    if (end < 0) {
      throw $nb("end must be positive");
    }
    if (start <= end) {
      this.c = start;
      this.e = end;
    } else {
      this.c = end;
      this.e = start;
    }
  }
  with(change) {
    let start = this.c;
    let end = this.e;
    if (change.start !== void 0) {
      start = change.start;
    }
    if (change.end !== void 0) {
      end = change.end;
    }
    if (start === this.c && end === this.e) {
      return this;
    }
    return new _$6U(start, end);
  }
};
var $7U = class _$7U {
  static validate(data) {
    if (typeof data.kind !== "number") {
      throw new Error("NotebookCellData MUST have 'kind' property");
    }
    if (typeof data.value !== "string") {
      throw new Error("NotebookCellData MUST have 'value' property");
    }
    if (typeof data.languageId !== "string") {
      throw new Error("NotebookCellData MUST have 'languageId' property");
    }
  }
  static isNotebookCellDataArray(value) {
    return Array.isArray(value) && value.every((elem) => _$7U.isNotebookCellData(elem));
  }
  static isNotebookCellData(value) {
    return true;
  }
  constructor(kind, value, languageId, mime, outputs, metadata, executionSummary) {
    this.kind = kind;
    this.value = value;
    this.languageId = languageId;
    this.mime = mime;
    this.outputs = outputs ?? [];
    this.metadata = metadata;
    this.executionSummary = executionSummary;
    _$7U.validate(this);
  }
};
var $8U = class {
  constructor(cells) {
    this.cells = cells;
  }
};
var $9U = class _$9U {
  static isNotebookCellOutputItem(obj) {
    if (obj instanceof _$9U) {
      return true;
    }
    if (!obj) {
      return false;
    }
    return typeof obj.mime === "string" && obj.data instanceof Uint8Array;
  }
  static error(err) {
    const obj = {
      name: err.name,
      message: err.message,
      stack: err.stack
    };
    return _$9U.json(obj, "application/vnd.code.notebook.error");
  }
  static stdout(value) {
    return _$9U.text(value, "application/vnd.code.notebook.stdout");
  }
  static stderr(value) {
    return _$9U.text(value, "application/vnd.code.notebook.stderr");
  }
  static bytes(value, mime = "application/octet-stream") {
    return new _$9U(value, mime);
  }
  static #encoder = new TextEncoder();
  static text(value, mime = $YC.text) {
    const bytes = _$9U.#encoder.encode(String(value));
    return new _$9U(bytes, mime);
  }
  static json(value, mime = "text/x-json") {
    const rawStr = JSON.stringify(value, void 0, "	");
    return _$9U.text(rawStr, mime);
  }
  constructor(data, mime) {
    this.data = data;
    this.mime = mime;
    const mimeNormalized = $3C(mime, true);
    if (!mimeNormalized) {
      throw new Error(`INVALID mime type: ${mime}. Must be in the format "type/subtype[;optionalparameter]"`);
    }
    this.mime = mimeNormalized;
  }
};
var $0U = class _$0U {
  static isNotebookCellOutput(candidate) {
    if (candidate instanceof _$0U) {
      return true;
    }
    if (!candidate || typeof candidate !== "object") {
      return false;
    }
    return typeof candidate.id === "string" && Array.isArray(candidate.items);
  }
  static ensureUniqueMimeTypes(items, warn = false) {
    const seen = /* @__PURE__ */ new Set();
    const removeIdx = /* @__PURE__ */ new Set();
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      const normalMime = $3C(item.mime);
      if (!seen.has(normalMime) || $tM(normalMime)) {
        seen.add(normalMime);
        continue;
      }
      removeIdx.add(i);
      if (warn) {
        console.warn(`DUPLICATED mime type '${item.mime}' will be dropped`);
      }
    }
    if (removeIdx.size === 0) {
      return items;
    }
    return items.filter((_item, index) => !removeIdx.has(index));
  }
  constructor(items, idOrMetadata, metadata) {
    this.items = _$0U.ensureUniqueMimeTypes(items, true);
    if (typeof idOrMetadata === "string") {
      this.id = idOrMetadata;
      this.metadata = metadata;
    } else {
      this.id = $ps();
      this.metadata = idOrMetadata ?? metadata;
    }
  }
};
var $$U = class {
  /**
   * @param label The name of the stack frame
   * @param file The file URI of the stack frame
   * @param position The position of the stack frame within the file
   */
  constructor(label, uri, position) {
    this.label = label;
    this.uri = uri;
    this.position = position;
  }
};
var NotebookCellKind;
(function(NotebookCellKind3) {
  NotebookCellKind3[NotebookCellKind3["Markup"] = 1] = "Markup";
  NotebookCellKind3[NotebookCellKind3["Code"] = 2] = "Code";
})(NotebookCellKind || (NotebookCellKind = {}));
var NotebookCellExecutionState2;
(function(NotebookCellExecutionState4) {
  NotebookCellExecutionState4[NotebookCellExecutionState4["Idle"] = 1] = "Idle";
  NotebookCellExecutionState4[NotebookCellExecutionState4["Pending"] = 2] = "Pending";
  NotebookCellExecutionState4[NotebookCellExecutionState4["Executing"] = 3] = "Executing";
})(NotebookCellExecutionState2 || (NotebookCellExecutionState2 = {}));
var NotebookCellStatusBarAlignment;
(function(NotebookCellStatusBarAlignment2) {
  NotebookCellStatusBarAlignment2[NotebookCellStatusBarAlignment2["Left"] = 1] = "Left";
  NotebookCellStatusBarAlignment2[NotebookCellStatusBarAlignment2["Right"] = 2] = "Right";
})(NotebookCellStatusBarAlignment || (NotebookCellStatusBarAlignment = {}));
var NotebookEditorRevealType2;
(function(NotebookEditorRevealType3) {
  NotebookEditorRevealType3[NotebookEditorRevealType3["Default"] = 0] = "Default";
  NotebookEditorRevealType3[NotebookEditorRevealType3["InCenter"] = 1] = "InCenter";
  NotebookEditorRevealType3[NotebookEditorRevealType3["InCenterIfOutsideViewport"] = 2] = "InCenterIfOutsideViewport";
  NotebookEditorRevealType3[NotebookEditorRevealType3["AtTop"] = 3] = "AtTop";
})(NotebookEditorRevealType2 || (NotebookEditorRevealType2 = {}));
var $_U = class {
  constructor(text, alignment) {
    this.text = text;
    this.alignment = alignment;
  }
};
var NotebookControllerAffinity;
(function(NotebookControllerAffinity3) {
  NotebookControllerAffinity3[NotebookControllerAffinity3["Default"] = 1] = "Default";
  NotebookControllerAffinity3[NotebookControllerAffinity3["Preferred"] = 2] = "Preferred";
})(NotebookControllerAffinity || (NotebookControllerAffinity = {}));
var NotebookControllerAffinity2;
(function(NotebookControllerAffinity22) {
  NotebookControllerAffinity22[NotebookControllerAffinity22["Default"] = 1] = "Default";
  NotebookControllerAffinity22[NotebookControllerAffinity22["Preferred"] = 2] = "Preferred";
  NotebookControllerAffinity22[NotebookControllerAffinity22["Hidden"] = -1] = "Hidden";
})(NotebookControllerAffinity2 || (NotebookControllerAffinity2 = {}));
var $aV = class {
  constructor(uri, provides = []) {
    this.uri = uri;
    this.provides = $5b(provides);
  }
};
var $bV = class {
  constructor(label) {
    this.label = label;
  }
};
var NotebookVariablesRequestKind;
(function(NotebookVariablesRequestKind2) {
  NotebookVariablesRequestKind2[NotebookVariablesRequestKind2["Named"] = 1] = "Named";
  NotebookVariablesRequestKind2[NotebookVariablesRequestKind2["Indexed"] = 2] = "Indexed";
})(NotebookVariablesRequestKind || (NotebookVariablesRequestKind = {}));
var $cV = class $cV2 {
  constructor(label, timestamp) {
    this.label = label;
    this.timestamp = timestamp;
  }
};
$cV = __decorate([
  es5ClassCompat
], $cV);
var ExtensionMode;
(function(ExtensionMode2) {
  ExtensionMode2[ExtensionMode2["Production"] = 1] = "Production";
  ExtensionMode2[ExtensionMode2["Development"] = 2] = "Development";
  ExtensionMode2[ExtensionMode2["Test"] = 3] = "Test";
})(ExtensionMode || (ExtensionMode = {}));
var ExtensionRuntime;
(function(ExtensionRuntime2) {
  ExtensionRuntime2[ExtensionRuntime2["Node"] = 1] = "Node";
  ExtensionRuntime2[ExtensionRuntime2["Webworker"] = 2] = "Webworker";
})(ExtensionRuntime || (ExtensionRuntime = {}));
var StandardTokenType;
(function(StandardTokenType2) {
  StandardTokenType2[StandardTokenType2["Other"] = 0] = "Other";
  StandardTokenType2[StandardTokenType2["Comment"] = 1] = "Comment";
  StandardTokenType2[StandardTokenType2["String"] = 2] = "String";
  StandardTokenType2[StandardTokenType2["RegEx"] = 3] = "RegEx";
})(StandardTokenType || (StandardTokenType = {}));
var $dV = class {
  constructor(ranges, wordPattern) {
    this.ranges = ranges;
    this.wordPattern = wordPattern;
  }
};
var $eV = class {
  constructor(autoForwardAction) {
    this.c = autoForwardAction;
  }
  get autoForwardAction() {
    return this.c;
  }
};
var TestResultState2;
(function(TestResultState3) {
  TestResultState3[TestResultState3["Queued"] = 1] = "Queued";
  TestResultState3[TestResultState3["Running"] = 2] = "Running";
  TestResultState3[TestResultState3["Passed"] = 3] = "Passed";
  TestResultState3[TestResultState3["Failed"] = 4] = "Failed";
  TestResultState3[TestResultState3["Skipped"] = 5] = "Skipped";
  TestResultState3[TestResultState3["Errored"] = 6] = "Errored";
})(TestResultState2 || (TestResultState2 = {}));
var TestRunProfileKind;
(function(TestRunProfileKind3) {
  TestRunProfileKind3[TestRunProfileKind3["Run"] = 1] = "Run";
  TestRunProfileKind3[TestRunProfileKind3["Debug"] = 2] = "Debug";
  TestRunProfileKind3[TestRunProfileKind3["Coverage"] = 3] = "Coverage";
})(TestRunProfileKind || (TestRunProfileKind = {}));
var $fV = class {
  constructor(controllerId, profileId, kind) {
    this.controllerId = controllerId;
    this.profileId = profileId;
    this.kind = kind;
  }
};
var $gV = class $gV2 {
  constructor(include = void 0, exclude = void 0, profile = void 0, continuous = false, preserveFocus = true) {
    this.include = include;
    this.exclude = exclude;
    this.profile = profile;
    this.continuous = continuous;
    this.preserveFocus = preserveFocus;
  }
};
$gV = __decorate([
  es5ClassCompat
], $gV);
var $hV = $hV_1 = class $hV2 {
  static diff(message, expected, actual) {
    const msg = new $hV_1(message);
    msg.expectedOutput = expected;
    msg.actualOutput = actual;
    return msg;
  }
  constructor(message) {
    this.message = message;
  }
};
$hV = $hV_1 = __decorate([
  es5ClassCompat
], $hV);
var $iV = class $iV2 {
  constructor(id2) {
    this.id = id2;
  }
};
$iV = __decorate([
  es5ClassCompat
], $iV);
var $jV = class {
  /**
   * @param label The name of the stack frame
   * @param file The file URI of the stack frame
   * @param position The position of the stack frame within the file
   */
  constructor(label, uri, position) {
    this.label = label;
    this.uri = uri;
    this.position = position;
  }
};
var $kV = class {
  constructor(covered, total) {
    this.covered = covered;
    this.total = total;
    $lV(this);
  }
};
function $lV(cc) {
  if (!cc) {
    return;
  }
  if (cc.covered > cc.total) {
    throw new Error(`The total number of covered items (${cc.covered}) cannot be greater than the total (${cc.total})`);
  }
  if (cc.total < 0) {
    throw new Error(`The number of covered items (${cc.total}) cannot be negative`);
  }
}
var $mV = class _$mV {
  static fromDetails(uri, details) {
    const statements = new $kV(0, 0);
    const branches = new $kV(0, 0);
    const decl = new $kV(0, 0);
    for (const detail of details) {
      if ("branches" in detail) {
        statements.total += 1;
        statements.covered += detail.executed ? 1 : 0;
        for (const branch of detail.branches) {
          branches.total += 1;
          branches.covered += branch.executed ? 1 : 0;
        }
      } else {
        decl.total += 1;
        decl.covered += detail.executed ? 1 : 0;
      }
    }
    const coverage = new _$mV(uri, statements, branches.total > 0 ? branches : void 0, decl.total > 0 ? decl : void 0);
    coverage.detailedCoverage = details;
    return coverage;
  }
  constructor(uri, statementCoverage, branchCoverage, declarationCoverage, includesTests = []) {
    this.uri = uri;
    this.statementCoverage = statementCoverage;
    this.branchCoverage = branchCoverage;
    this.declarationCoverage = declarationCoverage;
    this.includesTests = includesTests;
  }
};
var $nV = class {
  // back compat until finalization:
  get executionCount() {
    return +this.executed;
  }
  set executionCount(n) {
    this.executed = n;
  }
  constructor(executed, location2, branches = []) {
    this.executed = executed;
    this.location = location2;
    this.branches = branches;
  }
};
var $oV = class {
  // back compat until finalization:
  get executionCount() {
    return +this.executed;
  }
  set executionCount(n) {
    this.executed = n;
  }
  constructor(executed, location2, label) {
    this.executed = executed;
    this.location = location2;
    this.label = label;
  }
};
var $pV = class {
  // back compat until finalization:
  get executionCount() {
    return +this.executed;
  }
  set executionCount(n) {
    this.executed = n;
  }
  constructor(name, executed, location2) {
    this.name = name;
    this.executed = executed;
    this.location = location2;
  }
};
var ExternalUriOpenerPriority2;
(function(ExternalUriOpenerPriority3) {
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["None"] = 0] = "None";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Option"] = 1] = "Option";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Default"] = 2] = "Default";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Preferred"] = 3] = "Preferred";
})(ExternalUriOpenerPriority2 || (ExternalUriOpenerPriority2 = {}));
var WorkspaceTrustState;
(function(WorkspaceTrustState2) {
  WorkspaceTrustState2[WorkspaceTrustState2["Untrusted"] = 0] = "Untrusted";
  WorkspaceTrustState2[WorkspaceTrustState2["Trusted"] = 1] = "Trusted";
  WorkspaceTrustState2[WorkspaceTrustState2["Unspecified"] = 2] = "Unspecified";
})(WorkspaceTrustState || (WorkspaceTrustState = {}));
var PortAutoForwardAction;
(function(PortAutoForwardAction2) {
  PortAutoForwardAction2[PortAutoForwardAction2["Notify"] = 1] = "Notify";
  PortAutoForwardAction2[PortAutoForwardAction2["OpenBrowser"] = 2] = "OpenBrowser";
  PortAutoForwardAction2[PortAutoForwardAction2["OpenPreview"] = 3] = "OpenPreview";
  PortAutoForwardAction2[PortAutoForwardAction2["Silent"] = 4] = "Silent";
  PortAutoForwardAction2[PortAutoForwardAction2["Ignore"] = 5] = "Ignore";
  PortAutoForwardAction2[PortAutoForwardAction2["OpenBrowserOnce"] = 6] = "OpenBrowserOnce";
})(PortAutoForwardAction || (PortAutoForwardAction = {}));
var $qV = class {
  constructor(kind, name, detail, uri, range, selectionRange) {
    this.kind = kind;
    this.name = name;
    this.detail = detail;
    this.uri = uri;
    this.range = range;
    this.selectionRange = selectionRange;
  }
};
var $rV = class {
  constructor(uri) {
    this.uri = uri;
  }
};
var $sV = class {
  constructor(original, modified) {
    this.original = original;
    this.modified = modified;
  }
};
var $tV = class {
  constructor(base, input1, input2, result) {
    this.base = base;
    this.input1 = input1;
    this.input2 = input2;
    this.result = result;
  }
};
var $uV = class {
  constructor(uri, viewType) {
    this.uri = uri;
    this.viewType = viewType;
  }
};
var $vV = class {
  constructor(viewType) {
    this.viewType = viewType;
  }
};
var $wV = class {
  constructor(uri, notebookType) {
    this.uri = uri;
    this.notebookType = notebookType;
  }
};
var $xV = class {
  constructor(original, modified, notebookType) {
    this.original = original;
    this.modified = modified;
    this.notebookType = notebookType;
  }
};
var $yV = class {
  constructor() {
  }
};
var $zV = class {
  constructor(uri, inputBoxUri) {
    this.uri = uri;
    this.inputBoxUri = inputBoxUri;
  }
};
var $AV = class {
  constructor() {
  }
};
var $BV = class {
  constructor(textDiffs) {
    this.textDiffs = textDiffs;
  }
};
var InteractiveSessionVoteDirection;
(function(InteractiveSessionVoteDirection2) {
  InteractiveSessionVoteDirection2[InteractiveSessionVoteDirection2["Down"] = 0] = "Down";
  InteractiveSessionVoteDirection2[InteractiveSessionVoteDirection2["Up"] = 1] = "Up";
})(InteractiveSessionVoteDirection || (InteractiveSessionVoteDirection = {}));
var ChatCopyKind;
(function(ChatCopyKind3) {
  ChatCopyKind3[ChatCopyKind3["Action"] = 1] = "Action";
  ChatCopyKind3[ChatCopyKind3["Toolbar"] = 2] = "Toolbar";
})(ChatCopyKind || (ChatCopyKind = {}));
var ChatVariableLevel;
(function(ChatVariableLevel2) {
  ChatVariableLevel2[ChatVariableLevel2["Short"] = 1] = "Short";
  ChatVariableLevel2[ChatVariableLevel2["Medium"] = 2] = "Medium";
  ChatVariableLevel2[ChatVariableLevel2["Full"] = 3] = "Full";
})(ChatVariableLevel || (ChatVariableLevel = {}));
var $CV = class {
  constructor(id2, label, values) {
    this.id = id2;
    this.label = label;
    this.values = values;
  }
};
var ChatEditingSessionActionOutcome;
(function(ChatEditingSessionActionOutcome2) {
  ChatEditingSessionActionOutcome2[ChatEditingSessionActionOutcome2["Accepted"] = 1] = "Accepted";
  ChatEditingSessionActionOutcome2[ChatEditingSessionActionOutcome2["Rejected"] = 2] = "Rejected";
  ChatEditingSessionActionOutcome2[ChatEditingSessionActionOutcome2["Saved"] = 3] = "Saved";
})(ChatEditingSessionActionOutcome || (ChatEditingSessionActionOutcome = {}));
var InteractiveEditorResponseFeedbackKind;
(function(InteractiveEditorResponseFeedbackKind2) {
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Unhelpful"] = 0] = "Unhelpful";
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Helpful"] = 1] = "Helpful";
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Undone"] = 2] = "Undone";
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Accepted"] = 3] = "Accepted";
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Bug"] = 4] = "Bug";
})(InteractiveEditorResponseFeedbackKind || (InteractiveEditorResponseFeedbackKind = {}));
var ChatResultFeedbackKind;
(function(ChatResultFeedbackKind2) {
  ChatResultFeedbackKind2[ChatResultFeedbackKind2["Unhelpful"] = 0] = "Unhelpful";
  ChatResultFeedbackKind2[ChatResultFeedbackKind2["Helpful"] = 1] = "Helpful";
})(ChatResultFeedbackKind || (ChatResultFeedbackKind = {}));
var $DV = class {
  constructor(value) {
    if (typeof value !== "string" && value.isTrusted === true) {
      throw new Error("The boolean form of MarkdownString.isTrusted is NOT supported for chat participants.");
    }
    this.value = typeof value === "string" ? new $4T(value) : value;
  }
};
var $EV = class {
  constructor(value, vulnerabilities) {
    if (typeof value !== "string" && value.isTrusted === true) {
      throw new Error("The boolean form of MarkdownString.isTrusted is NOT supported for chat participants.");
    }
    this.value = typeof value === "string" ? new $4T(value) : value;
    this.vulnerabilities = vulnerabilities;
  }
};
var $FV = class {
  constructor(participant, command) {
    this.participant = participant;
    this.command = command;
  }
};
var $GV = class {
  constructor(title, message, data, buttons) {
    this.title = title;
    this.message = message;
    this.data = data;
    this.buttons = buttons;
  }
};
var $HV = class {
  constructor(value, baseUri) {
    this.value = value;
    this.baseUri = baseUri;
  }
};
var $IV = class {
  constructor(value, title) {
    this.value = value;
    this.value2 = value;
    this.title = title;
  }
};
var $JV = class {
  constructor(value) {
    this.value = value;
  }
};
var $KV = class {
  constructor(value, task) {
    this.value = value;
    this.task = task;
  }
};
var $LV = class {
  constructor(value) {
    if (typeof value !== "string" && value.isTrusted === true) {
      throw new Error("The boolean form of MarkdownString.isTrusted is NOT supported for chat participants.");
    }
    this.value = typeof value === "string" ? new $4T(value) : value;
  }
};
var $MV = class {
  constructor(value) {
    this.value = value;
  }
};
var $NV = class {
  constructor(value, iconPath, options2) {
    this.value = value;
    this.iconPath = iconPath;
    this.options = options2;
  }
};
var $OV = class {
  constructor(value) {
    this.value = value;
  }
};
var $PV = class {
  constructor(value, license, snippet) {
    this.value = value;
    this.license = license;
    this.snippet = snippet;
  }
};
var $QV = class {
  constructor(uri, range) {
    this.uri = uri;
    this.range = range;
  }
};
var $RV = class {
  constructor(uri, editsOrDone) {
    this.uri = uri;
    if (editsOrDone === true) {
      this.isDone = true;
      this.edits = [];
    } else {
      this.edits = Array.isArray(editsOrDone) ? editsOrDone : [editsOrDone];
    }
  }
};
var $SV = class {
  constructor(prompt, command, references, participant, toolReferences) {
    this.prompt = prompt;
    this.command = command;
    this.references = references;
    this.participant = participant;
    this.toolReferences = toolReferences;
  }
};
var $TV = class {
  constructor(response, result, participant, command) {
    this.response = response;
    this.result = result;
    this.participant = participant;
    this.command = command;
  }
};
var ChatLocation;
(function(ChatLocation3) {
  ChatLocation3[ChatLocation3["Panel"] = 1] = "Panel";
  ChatLocation3[ChatLocation3["Terminal"] = 2] = "Terminal";
  ChatLocation3[ChatLocation3["Notebook"] = 3] = "Notebook";
  ChatLocation3[ChatLocation3["Editor"] = 4] = "Editor";
  ChatLocation3[ChatLocation3["EditingSession"] = 5] = "EditingSession";
})(ChatLocation || (ChatLocation = {}));
var ChatResponseReferencePartStatusKind;
(function(ChatResponseReferencePartStatusKind3) {
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Complete"] = 1] = "Complete";
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Partial"] = 2] = "Partial";
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Omitted"] = 3] = "Omitted";
})(ChatResponseReferencePartStatusKind || (ChatResponseReferencePartStatusKind = {}));
var $UV = class {
  constructor(document2, selection, wholeRange) {
    this.document = document2;
    this.selection = selection;
    this.wholeRange = wholeRange;
  }
};
var $VV = class {
  constructor(cell) {
    this.cell = cell;
  }
};
var $WV = class {
  constructor(mimeType, data) {
    this.mimeType = mimeType;
    this.data = data;
  }
};
var LanguageModelChatMessageRole;
(function(LanguageModelChatMessageRole3) {
  LanguageModelChatMessageRole3[LanguageModelChatMessageRole3["User"] = 1] = "User";
  LanguageModelChatMessageRole3[LanguageModelChatMessageRole3["Assistant"] = 2] = "Assistant";
  LanguageModelChatMessageRole3[LanguageModelChatMessageRole3["System"] = 3] = "System";
})(LanguageModelChatMessageRole || (LanguageModelChatMessageRole = {}));
var $XV = class {
  constructor(callId, content, isError) {
    this.callId = callId;
    this.content = content;
    this.isError = isError ?? false;
  }
};
var $YV = class _$YV {
  static User(content, name) {
    return new _$YV(LanguageModelChatMessageRole.User, content, name);
  }
  static Assistant(content, name) {
    return new _$YV(LanguageModelChatMessageRole.Assistant, content, name);
  }
  set content(value) {
    if (typeof value === "string") {
      this.c = [new $1V(value)];
    } else {
      this.c = value;
    }
  }
  get content() {
    return this.c;
  }
  // Temp to avoid breaking changes
  set content2(value) {
    if (value) {
      this.content = value.map((part) => {
        if (typeof part === "string") {
          return new $1V(part);
        }
        return part;
      });
    }
  }
  get content2() {
    return this.content.map((part) => {
      if (part instanceof $1V) {
        return part.value;
      }
      return part;
    });
  }
  constructor(role, content, name) {
    this.c = [];
    this.role = role;
    this.content = content;
    this.name = name;
  }
};
var $ZV = class {
  constructor(callId, name, input) {
    this.callId = callId;
    this.name = name;
    this.input = input;
  }
};
var $1V = class {
  constructor(value) {
    this.value = value;
  }
  toJSON() {
    return {
      $mid: 21,
      value: this.value
    };
  }
};
var $2V = class {
  constructor(value) {
    this.value = value;
  }
  toJSON() {
    return {
      $mid: 22,
      value: this.value
    };
  }
};
var $6V = class _$6V extends Error {
  static NotFound(message) {
    return new _$6V(message, _$6V.NotFound.name);
  }
  static NoPermissions(message) {
    return new _$6V(message, _$6V.NoPermissions.name);
  }
  static Blocked(message) {
    return new _$6V(message, _$6V.Blocked.name);
  }
  constructor(message, code, cause) {
    super(message, { cause });
    this.name = "LanguageModelError";
    this.code = code ?? "";
  }
};
var $7V = class {
  constructor(content) {
    this.content = content;
  }
  toJSON() {
    return {
      $mid: 20,
      content: this.content
    };
  }
};
var LanguageModelChatToolMode;
(function(LanguageModelChatToolMode2) {
  LanguageModelChatToolMode2[LanguageModelChatToolMode2["Auto"] = 1] = "Auto";
  LanguageModelChatToolMode2[LanguageModelChatToolMode2["Required"] = 2] = "Required";
})(LanguageModelChatToolMode || (LanguageModelChatToolMode = {}));
var RelatedInformationType;
(function(RelatedInformationType2) {
  RelatedInformationType2[RelatedInformationType2["SymbolInformation"] = 1] = "SymbolInformation";
  RelatedInformationType2[RelatedInformationType2["CommandInformation"] = 2] = "CommandInformation";
  RelatedInformationType2[RelatedInformationType2["SearchInformation"] = 3] = "SearchInformation";
  RelatedInformationType2[RelatedInformationType2["SettingInformation"] = 4] = "SettingInformation";
})(RelatedInformationType || (RelatedInformationType = {}));
var SpeechToTextStatus;
(function(SpeechToTextStatus2) {
  SpeechToTextStatus2[SpeechToTextStatus2["Started"] = 1] = "Started";
  SpeechToTextStatus2[SpeechToTextStatus2["Recognizing"] = 2] = "Recognizing";
  SpeechToTextStatus2[SpeechToTextStatus2["Recognized"] = 3] = "Recognized";
  SpeechToTextStatus2[SpeechToTextStatus2["Stopped"] = 4] = "Stopped";
  SpeechToTextStatus2[SpeechToTextStatus2["Error"] = 5] = "Error";
})(SpeechToTextStatus || (SpeechToTextStatus = {}));
var TextToSpeechStatus;
(function(TextToSpeechStatus2) {
  TextToSpeechStatus2[TextToSpeechStatus2["Started"] = 1] = "Started";
  TextToSpeechStatus2[TextToSpeechStatus2["Stopped"] = 2] = "Stopped";
  TextToSpeechStatus2[TextToSpeechStatus2["Error"] = 3] = "Error";
})(TextToSpeechStatus || (TextToSpeechStatus = {}));
var KeywordRecognitionStatus;
(function(KeywordRecognitionStatus2) {
  KeywordRecognitionStatus2[KeywordRecognitionStatus2["Recognized"] = 1] = "Recognized";
  KeywordRecognitionStatus2[KeywordRecognitionStatus2["Stopped"] = 2] = "Stopped";
})(KeywordRecognitionStatus || (KeywordRecognitionStatus = {}));
var $8V = class {
  constructor(text, range) {
    this.text = text;
    this.range = range;
  }
};
var InlineEditTriggerKind2;
(function(InlineEditTriggerKind3) {
  InlineEditTriggerKind3[InlineEditTriggerKind3["Invoke"] = 0] = "Invoke";
  InlineEditTriggerKind3[InlineEditTriggerKind3["Automatic"] = 1] = "Automatic";
})(InlineEditTriggerKind2 || (InlineEditTriggerKind2 = {}));

// out-build/vs/workbench/api/common/extHostTypeConverters.js
var Selection;
(function(Selection2) {
  function to(selection) {
    const { selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn } = selection;
    const start = new $AT(selectionStartLineNumber - 1, selectionStartColumn - 1);
    const end = new $AT(positionLineNumber - 1, positionColumn - 1);
    return new $CT(start, end);
  }
  Selection2.to = to;
  function from(selection) {
    const { anchor, active } = selection;
    return {
      selectionStartLineNumber: anchor.line + 1,
      selectionStartColumn: anchor.character + 1,
      positionLineNumber: active.line + 1,
      positionColumn: active.character + 1
    };
  }
  Selection2.from = from;
})(Selection || (Selection = {}));
var Range;
(function(Range3) {
  function from(range) {
    if (!range) {
      return void 0;
    }
    const { start, end } = range;
    return {
      startLineNumber: start.line + 1,
      startColumn: start.character + 1,
      endLineNumber: end.line + 1,
      endColumn: end.character + 1
    };
  }
  Range3.from = from;
  function to(range) {
    if (!range) {
      return void 0;
    }
    const { startLineNumber, startColumn, endLineNumber, endColumn } = range;
    return new $BT(startLineNumber - 1, startColumn - 1, endLineNumber - 1, endColumn - 1);
  }
  Range3.to = to;
})(Range || (Range = {}));
var Location;
(function(Location2) {
  function from(location2) {
    return {
      uri: location2.uri,
      range: Range.from(location2.range)
    };
  }
  Location2.from = from;
  function to(location2) {
    return new $NT(URI.revive(location2.uri), Range.to(location2.range));
  }
  Location2.to = to;
})(Location || (Location = {}));
var TokenType2;
(function(TokenType3) {
  function to(type) {
    switch (type) {
      case 1:
        return StandardTokenType.Comment;
      case 0:
        return StandardTokenType.Other;
      case 3:
        return StandardTokenType.RegEx;
      case 2:
        return StandardTokenType.String;
    }
  }
  TokenType3.to = to;
})(TokenType2 || (TokenType2 = {}));
var Position;
(function(Position2) {
  function to(position) {
    return new $AT(position.lineNumber - 1, position.column - 1);
  }
  Position2.to = to;
  function from(position) {
    return { lineNumber: position.line + 1, column: position.character + 1 };
  }
  Position2.from = from;
})(Position || (Position = {}));
var DocumentSelector;
(function(DocumentSelector2) {
  function from(value, uriTransformer, extension) {
    return $Mb($5b(value).map((sel) => _doTransformDocumentSelector(sel, uriTransformer, extension)));
  }
  DocumentSelector2.from = from;
  function _doTransformDocumentSelector(selector, uriTransformer, extension) {
    if (typeof selector === "string") {
      return {
        $serialized: true,
        language: selector,
        isBuiltin: extension?.isBuiltin
      };
    }
    if (selector) {
      return {
        $serialized: true,
        language: selector.language,
        scheme: _transformScheme(selector.scheme, uriTransformer),
        pattern: GlobPattern.from(selector.pattern) ?? void 0,
        exclusive: selector.exclusive,
        notebookType: selector.notebookType,
        isBuiltin: extension?.isBuiltin
      };
    }
    return void 0;
  }
  function _transformScheme(scheme, uriTransformer) {
    if (uriTransformer && typeof scheme === "string") {
      return uriTransformer.transformOutgoingScheme(scheme);
    }
    return scheme;
  }
})(DocumentSelector || (DocumentSelector = {}));
var DiagnosticTag2;
(function(DiagnosticTag3) {
  function from(value) {
    switch (value) {
      case DiagnosticTag.Unnecessary:
        return 1;
      case DiagnosticTag.Deprecated:
        return 2;
    }
    return void 0;
  }
  DiagnosticTag3.from = from;
  function to(value) {
    switch (value) {
      case 1:
        return DiagnosticTag.Unnecessary;
      case 2:
        return DiagnosticTag.Deprecated;
      default:
        return void 0;
    }
  }
  DiagnosticTag3.to = to;
})(DiagnosticTag2 || (DiagnosticTag2 = {}));
var Diagnostic;
(function(Diagnostic2) {
  function from(value) {
    let code;
    if (value.code) {
      if ($zg(value.code) || $Dg(value.code)) {
        code = String(value.code);
      } else {
        code = {
          value: String(value.code.value),
          target: value.code.target
        };
      }
    }
    return {
      ...Range.from(value.range),
      message: value.message,
      source: value.source,
      code,
      severity: DiagnosticSeverity2.from(value.severity),
      relatedInformation: value.relatedInformation && value.relatedInformation.map(DiagnosticRelatedInformation.from),
      tags: Array.isArray(value.tags) ? $Mb(value.tags.map(DiagnosticTag2.from)) : void 0
    };
  }
  Diagnostic2.from = from;
  function to(value) {
    const res = new $PT(Range.to(value), value.message, DiagnosticSeverity2.to(value.severity));
    res.source = value.source;
    res.code = $zg(value.code) ? value.code : value.code?.value;
    res.relatedInformation = value.relatedInformation && value.relatedInformation.map(DiagnosticRelatedInformation.to);
    res.tags = value.tags && $Mb(value.tags.map(DiagnosticTag2.to));
    return res;
  }
  Diagnostic2.to = to;
})(Diagnostic || (Diagnostic = {}));
var DiagnosticRelatedInformation;
(function(DiagnosticRelatedInformation2) {
  function from(value) {
    return {
      ...Range.from(value.location.range),
      message: value.message,
      resource: value.location.uri
    };
  }
  DiagnosticRelatedInformation2.from = from;
  function to(value) {
    return new $OT(new $NT(value.resource, Range.to(value)), value.message);
  }
  DiagnosticRelatedInformation2.to = to;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
var DiagnosticSeverity2;
(function(DiagnosticSeverity3) {
  function from(value) {
    switch (value) {
      case DiagnosticSeverity.Error:
        return MarkerSeverity.Error;
      case DiagnosticSeverity.Warning:
        return MarkerSeverity.Warning;
      case DiagnosticSeverity.Information:
        return MarkerSeverity.Info;
      case DiagnosticSeverity.Hint:
        return MarkerSeverity.Hint;
    }
    return MarkerSeverity.Error;
  }
  DiagnosticSeverity3.from = from;
  function to(value) {
    switch (value) {
      case MarkerSeverity.Info:
        return DiagnosticSeverity.Information;
      case MarkerSeverity.Warning:
        return DiagnosticSeverity.Warning;
      case MarkerSeverity.Error:
        return DiagnosticSeverity.Error;
      case MarkerSeverity.Hint:
        return DiagnosticSeverity.Hint;
      default:
        return DiagnosticSeverity.Error;
    }
  }
  DiagnosticSeverity3.to = to;
})(DiagnosticSeverity2 || (DiagnosticSeverity2 = {}));
var ViewColumn2;
(function(ViewColumn3) {
  function from(column) {
    if (typeof column === "number" && column >= ViewColumn.One) {
      return column - 1;
    }
    if (column === ViewColumn.Beside) {
      return $oJ;
    }
    return $nJ;
  }
  ViewColumn3.from = from;
  function to(position) {
    if (typeof position === "number" && position >= 0) {
      return position + 1;
    }
    throw new Error(`invalid 'EditorGroupColumn'`);
  }
  ViewColumn3.to = to;
})(ViewColumn2 || (ViewColumn2 = {}));
function isDecorationOptions(something) {
  return typeof something.range !== "undefined";
}
function $dW(something) {
  if (something.length === 0) {
    return true;
  }
  return isDecorationOptions(something[0]) ? true : false;
}
var MarkdownString;
(function(MarkdownString2) {
  function fromMany(markup) {
    return markup.map(MarkdownString2.from);
  }
  MarkdownString2.fromMany = fromMany;
  function isCodeblock(thing) {
    return thing && typeof thing === "object" && typeof thing.language === "string" && typeof thing.value === "string";
  }
  function from(markup) {
    let res;
    if (isCodeblock(markup)) {
      const { language, value } = markup;
      res = { value: "```" + language + "\n" + value + "\n```\n" };
    } else if ($4T.isMarkdownString(markup)) {
      res = { value: markup.value, isTrusted: markup.isTrusted, supportThemeIcons: markup.supportThemeIcons, supportHtml: markup.supportHtml, baseUri: markup.baseUri };
    } else if (typeof markup === "string") {
      res = { value: markup };
    } else {
      res = { value: "" };
    }
    const resUris = /* @__PURE__ */ Object.create(null);
    res.uris = resUris;
    const collectUri = ({ href }) => {
      try {
        let uri = URI.parse(href, true);
        uri = uri.with({ query: _uriMassage(uri.query, resUris) });
        resUris[href] = uri;
      } catch (e) {
      }
      return "";
    };
    marked.walkTokens(marked.lexer(res.value), (token) => {
      if (token.type === "link") {
        collectUri({ href: token.href });
      } else if (token.type === "image") {
        if (typeof token.href === "string") {
          collectUri($jm(token.href));
        }
      }
    });
    return res;
  }
  MarkdownString2.from = from;
  function _uriMassage(part, bucket) {
    if (!part) {
      return part;
    }
    let data;
    try {
      data = $bu(part);
    } catch (e) {
    }
    if (!data) {
      return part;
    }
    let changed = false;
    data = $Nv(data, (value) => {
      if (URI.isUri(value)) {
        const key = `__uri_${Math.random().toString(16).slice(2, 8)}`;
        bucket[key] = value;
        changed = true;
        return key;
      } else {
        return void 0;
      }
    });
    if (!changed) {
      return part;
    }
    return JSON.stringify(data);
  }
  function to(value) {
    const result = new $4T(value.value, value.supportThemeIcons);
    result.isTrusted = value.isTrusted;
    result.supportHtml = value.supportHtml;
    result.baseUri = value.baseUri ? URI.from(value.baseUri) : void 0;
    return result;
  }
  MarkdownString2.to = to;
  function fromStrict(value) {
    if (!value) {
      return void 0;
    }
    return typeof value === "string" ? value : MarkdownString2.from(value);
  }
  MarkdownString2.fromStrict = fromStrict;
})(MarkdownString || (MarkdownString = {}));
function $eW(ranges) {
  if ($dW(ranges)) {
    return ranges.map((r) => {
      return {
        range: Range.from(r.range),
        hoverMessage: Array.isArray(r.hoverMessage) ? MarkdownString.fromMany(r.hoverMessage) : r.hoverMessage ? MarkdownString.from(r.hoverMessage) : void 0,
        renderOptions: (
          /* URI vs Uri */
          r.renderOptions
        )
      };
    });
  } else {
    return ranges.map((r) => {
      return {
        range: Range.from(r)
      };
    });
  }
}
function $fW(value) {
  if (typeof value === "undefined") {
    return value;
  }
  if (typeof value === "string") {
    return URI.file(value);
  } else {
    return value;
  }
}
var ThemableDecorationAttachmentRenderOptions;
(function(ThemableDecorationAttachmentRenderOptions2) {
  function from(options2) {
    if (typeof options2 === "undefined") {
      return options2;
    }
    return {
      contentText: options2.contentText,
      contentIconPath: options2.contentIconPath ? $fW(options2.contentIconPath) : void 0,
      border: options2.border,
      borderColor: options2.borderColor,
      fontStyle: options2.fontStyle,
      fontWeight: options2.fontWeight,
      textDecoration: options2.textDecoration,
      color: options2.color,
      backgroundColor: options2.backgroundColor,
      margin: options2.margin,
      width: options2.width,
      height: options2.height
    };
  }
  ThemableDecorationAttachmentRenderOptions2.from = from;
})(ThemableDecorationAttachmentRenderOptions || (ThemableDecorationAttachmentRenderOptions = {}));
var ThemableDecorationRenderOptions;
(function(ThemableDecorationRenderOptions2) {
  function from(options2) {
    if (typeof options2 === "undefined") {
      return options2;
    }
    return {
      backgroundColor: options2.backgroundColor,
      outline: options2.outline,
      outlineColor: options2.outlineColor,
      outlineStyle: options2.outlineStyle,
      outlineWidth: options2.outlineWidth,
      border: options2.border,
      borderColor: options2.borderColor,
      borderRadius: options2.borderRadius,
      borderSpacing: options2.borderSpacing,
      borderStyle: options2.borderStyle,
      borderWidth: options2.borderWidth,
      fontStyle: options2.fontStyle,
      fontWeight: options2.fontWeight,
      textDecoration: options2.textDecoration,
      cursor: options2.cursor,
      color: options2.color,
      opacity: options2.opacity,
      letterSpacing: options2.letterSpacing,
      gutterIconPath: options2.gutterIconPath ? $fW(options2.gutterIconPath) : void 0,
      gutterIconSize: options2.gutterIconSize,
      overviewRulerColor: options2.overviewRulerColor,
      before: options2.before ? ThemableDecorationAttachmentRenderOptions.from(options2.before) : void 0,
      after: options2.after ? ThemableDecorationAttachmentRenderOptions.from(options2.after) : void 0
    };
  }
  ThemableDecorationRenderOptions2.from = from;
})(ThemableDecorationRenderOptions || (ThemableDecorationRenderOptions = {}));
var DecorationRangeBehavior2;
(function(DecorationRangeBehavior3) {
  function from(value) {
    if (typeof value === "undefined") {
      return value;
    }
    switch (value) {
      case DecorationRangeBehavior.OpenOpen:
        return 0;
      case DecorationRangeBehavior.ClosedClosed:
        return 1;
      case DecorationRangeBehavior.OpenClosed:
        return 2;
      case DecorationRangeBehavior.ClosedOpen:
        return 3;
    }
  }
  DecorationRangeBehavior3.from = from;
})(DecorationRangeBehavior2 || (DecorationRangeBehavior2 = {}));
var DecorationRenderOptions;
(function(DecorationRenderOptions2) {
  function from(options2) {
    return {
      isWholeLine: options2.isWholeLine,
      rangeBehavior: options2.rangeBehavior ? DecorationRangeBehavior2.from(options2.rangeBehavior) : void 0,
      overviewRulerLane: options2.overviewRulerLane,
      light: options2.light ? ThemableDecorationRenderOptions.from(options2.light) : void 0,
      dark: options2.dark ? ThemableDecorationRenderOptions.from(options2.dark) : void 0,
      backgroundColor: options2.backgroundColor,
      outline: options2.outline,
      outlineColor: options2.outlineColor,
      outlineStyle: options2.outlineStyle,
      outlineWidth: options2.outlineWidth,
      border: options2.border,
      borderColor: options2.borderColor,
      borderRadius: options2.borderRadius,
      borderSpacing: options2.borderSpacing,
      borderStyle: options2.borderStyle,
      borderWidth: options2.borderWidth,
      fontStyle: options2.fontStyle,
      fontWeight: options2.fontWeight,
      textDecoration: options2.textDecoration,
      cursor: options2.cursor,
      color: options2.color,
      opacity: options2.opacity,
      letterSpacing: options2.letterSpacing,
      gutterIconPath: options2.gutterIconPath ? $fW(options2.gutterIconPath) : void 0,
      gutterIconSize: options2.gutterIconSize,
      overviewRulerColor: options2.overviewRulerColor,
      before: options2.before ? ThemableDecorationAttachmentRenderOptions.from(options2.before) : void 0,
      after: options2.after ? ThemableDecorationAttachmentRenderOptions.from(options2.after) : void 0
    };
  }
  DecorationRenderOptions2.from = from;
})(DecorationRenderOptions || (DecorationRenderOptions = {}));
var TextEdit;
(function(TextEdit2) {
  function from(edit2) {
    return {
      text: edit2.newText,
      eol: edit2.newEol && EndOfLine2.from(edit2.newEol),
      range: Range.from(edit2.range)
    };
  }
  TextEdit2.from = from;
  function to(edit2) {
    const result = new $IT(Range.to(edit2.range), edit2.text);
    result.newEol = typeof edit2.eol === "undefined" ? void 0 : EndOfLine2.to(edit2.eol);
    return result;
  }
  TextEdit2.to = to;
})(TextEdit || (TextEdit = {}));
var WorkspaceEdit;
(function(WorkspaceEdit2) {
  function from(value, versionInfo) {
    const result = {
      edits: []
    };
    if (value instanceof $LT) {
      const toCreate = new $Fc();
      for (const entry of value._allEntries()) {
        if (entry._type === 1 && URI.isUri(entry.to) && entry.from === void 0) {
          toCreate.add(entry.to);
        }
      }
      for (const entry of value._allEntries()) {
        if (entry._type === 1) {
          let contents;
          if (entry.options?.contents) {
            if (ArrayBuffer.isView(entry.options.contents)) {
              contents = { type: "base64", value: $Wi($Ci.wrap(entry.options.contents)) };
            } else {
              contents = { type: "dataTransferItem", id: entry.options.contents._itemId };
            }
          }
          result.edits.push({
            oldResource: entry.from,
            newResource: entry.to,
            options: { ...entry.options, contents },
            metadata: entry.metadata
          });
        } else if (entry._type === 2) {
          result.edits.push({
            resource: entry.uri,
            textEdit: TextEdit.from(entry.edit),
            versionId: !toCreate.has(entry.uri) ? versionInfo?.getTextDocumentVersion(entry.uri) : void 0,
            metadata: entry.metadata
          });
        } else if (entry._type === 6) {
          result.edits.push({
            resource: entry.uri,
            textEdit: {
              range: Range.from(entry.range),
              text: entry.edit.value,
              insertAsSnippet: true
            },
            versionId: !toCreate.has(entry.uri) ? versionInfo?.getTextDocumentVersion(entry.uri) : void 0,
            metadata: entry.metadata
          });
        } else if (entry._type === 3) {
          result.edits.push({
            metadata: entry.metadata,
            resource: entry.uri,
            cellEdit: entry.edit,
            notebookVersionId: versionInfo?.getNotebookDocumentVersion(entry.uri)
          });
        } else if (entry._type === 5) {
          result.edits.push({
            metadata: entry.metadata,
            resource: entry.uri,
            notebookVersionId: versionInfo?.getNotebookDocumentVersion(entry.uri),
            cellEdit: {
              editType: 1,
              index: entry.index,
              count: entry.count,
              cells: entry.cells.map(NotebookCellData.from)
            }
          });
        }
      }
    }
    return result;
  }
  WorkspaceEdit2.from = from;
  function to(value) {
    const result = new $LT();
    const edits = new $Ec();
    for (const edit2 of value.edits) {
      if (edit2.textEdit) {
        const item = edit2;
        const uri = URI.revive(item.resource);
        const range = Range.to(item.textEdit.range);
        const text = item.textEdit.text;
        const isSnippet = item.textEdit.insertAsSnippet;
        let editOrSnippetTest;
        if (isSnippet) {
          editOrSnippetTest = $KT.replace(range, new $MT(text));
        } else {
          editOrSnippetTest = $IT.replace(range, text);
        }
        const array = edits.get(uri);
        if (!array) {
          edits.set(uri, [editOrSnippetTest]);
        } else {
          array.push(editOrSnippetTest);
        }
      } else {
        result.renameFile(URI.revive(edit2.oldResource), URI.revive(edit2.newResource), edit2.options);
      }
    }
    for (const [uri, array] of edits) {
      result.set(uri, array);
    }
    return result;
  }
  WorkspaceEdit2.to = to;
})(WorkspaceEdit || (WorkspaceEdit = {}));
var SymbolKind3;
(function(SymbolKind4) {
  const _fromMapping = /* @__PURE__ */ Object.create(null);
  _fromMapping[SymbolKind2.File] = 0;
  _fromMapping[SymbolKind2.Module] = 1;
  _fromMapping[SymbolKind2.Namespace] = 2;
  _fromMapping[SymbolKind2.Package] = 3;
  _fromMapping[SymbolKind2.Class] = 4;
  _fromMapping[SymbolKind2.Method] = 5;
  _fromMapping[SymbolKind2.Property] = 6;
  _fromMapping[SymbolKind2.Field] = 7;
  _fromMapping[SymbolKind2.Constructor] = 8;
  _fromMapping[SymbolKind2.Enum] = 9;
  _fromMapping[SymbolKind2.Interface] = 10;
  _fromMapping[SymbolKind2.Function] = 11;
  _fromMapping[SymbolKind2.Variable] = 12;
  _fromMapping[SymbolKind2.Constant] = 13;
  _fromMapping[SymbolKind2.String] = 14;
  _fromMapping[SymbolKind2.Number] = 15;
  _fromMapping[SymbolKind2.Boolean] = 16;
  _fromMapping[SymbolKind2.Array] = 17;
  _fromMapping[SymbolKind2.Object] = 18;
  _fromMapping[SymbolKind2.Key] = 19;
  _fromMapping[SymbolKind2.Null] = 20;
  _fromMapping[SymbolKind2.EnumMember] = 21;
  _fromMapping[SymbolKind2.Struct] = 22;
  _fromMapping[SymbolKind2.Event] = 23;
  _fromMapping[SymbolKind2.Operator] = 24;
  _fromMapping[SymbolKind2.TypeParameter] = 25;
  function from(kind) {
    return typeof _fromMapping[kind] === "number" ? _fromMapping[kind] : 6;
  }
  SymbolKind4.from = from;
  function to(kind) {
    for (const k in _fromMapping) {
      if (_fromMapping[k] === kind) {
        return Number(k);
      }
    }
    return SymbolKind2.Property;
  }
  SymbolKind4.to = to;
})(SymbolKind3 || (SymbolKind3 = {}));
var SymbolTag3;
(function(SymbolTag4) {
  function from(kind) {
    switch (kind) {
      case SymbolTag2.Deprecated:
        return 1;
    }
  }
  SymbolTag4.from = from;
  function to(kind) {
    switch (kind) {
      case 1:
        return SymbolTag2.Deprecated;
    }
  }
  SymbolTag4.to = to;
})(SymbolTag3 || (SymbolTag3 = {}));
var WorkspaceSymbol;
(function(WorkspaceSymbol2) {
  function from(info) {
    return {
      name: info.name,
      kind: SymbolKind3.from(info.kind),
      tags: info.tags && info.tags.map(SymbolTag3.from),
      containerName: info.containerName,
      location: location.from(info.location)
    };
  }
  WorkspaceSymbol2.from = from;
  function to(info) {
    const result = new $UT(info.name, SymbolKind3.to(info.kind), info.containerName, location.to(info.location));
    result.tags = info.tags && info.tags.map(SymbolTag3.to);
    return result;
  }
  WorkspaceSymbol2.to = to;
})(WorkspaceSymbol || (WorkspaceSymbol = {}));
var DocumentSymbol;
(function(DocumentSymbol2) {
  function from(info) {
    const result = {
      name: info.name || "!!MISSING: name!!",
      detail: info.detail,
      range: Range.from(info.range),
      selectionRange: Range.from(info.selectionRange),
      kind: SymbolKind3.from(info.kind),
      tags: info.tags?.map(SymbolTag3.from) ?? []
    };
    if (info.children) {
      result.children = info.children.map(from);
    }
    return result;
  }
  DocumentSymbol2.from = from;
  function to(info) {
    const result = new $VT(info.name, info.detail, SymbolKind3.to(info.kind), Range.to(info.range), Range.to(info.selectionRange));
    if ($Qb(info.tags)) {
      result.tags = info.tags.map(SymbolTag3.to);
    }
    if (info.children) {
      result.children = info.children.map(to);
    }
    return result;
  }
  DocumentSymbol2.to = to;
})(DocumentSymbol || (DocumentSymbol = {}));
var CallHierarchyItem;
(function(CallHierarchyItem2) {
  function to(item) {
    const result = new $ZT(SymbolKind3.to(item.kind), item.name, item.detail || "", URI.revive(item.uri), Range.to(item.range), Range.to(item.selectionRange));
    result._sessionId = item._sessionId;
    result._itemId = item._itemId;
    return result;
  }
  CallHierarchyItem2.to = to;
  function from(item, sessionId, itemId) {
    sessionId = sessionId ?? item._sessionId;
    itemId = itemId ?? item._itemId;
    if (sessionId === void 0 || itemId === void 0) {
      throw new Error("invalid item");
    }
    return {
      _sessionId: sessionId,
      _itemId: itemId,
      name: item.name,
      detail: item.detail,
      kind: SymbolKind3.from(item.kind),
      uri: item.uri,
      range: Range.from(item.range),
      selectionRange: Range.from(item.selectionRange),
      tags: item.tags?.map(SymbolTag3.from)
    };
  }
  CallHierarchyItem2.from = from;
})(CallHierarchyItem || (CallHierarchyItem = {}));
var CallHierarchyIncomingCall;
(function(CallHierarchyIncomingCall2) {
  function to(item) {
    return new $1T(CallHierarchyItem.to(item.from), item.fromRanges.map((r) => Range.to(r)));
  }
  CallHierarchyIncomingCall2.to = to;
})(CallHierarchyIncomingCall || (CallHierarchyIncomingCall = {}));
var CallHierarchyOutgoingCall;
(function(CallHierarchyOutgoingCall2) {
  function to(item) {
    return new $2T(CallHierarchyItem.to(item.to), item.fromRanges.map((r) => Range.to(r)));
  }
  CallHierarchyOutgoingCall2.to = to;
})(CallHierarchyOutgoingCall || (CallHierarchyOutgoingCall = {}));
var location;
(function(location2) {
  function from(value) {
    return {
      range: value.range && Range.from(value.range),
      uri: value.uri
    };
  }
  location2.from = from;
  function to(value) {
    return new $NT(URI.revive(value.uri), Range.to(value.range));
  }
  location2.to = to;
})(location || (location = {}));
var DefinitionLink;
(function(DefinitionLink2) {
  function from(value) {
    const definitionLink = value;
    const location2 = value;
    return {
      originSelectionRange: definitionLink.originSelectionRange ? Range.from(definitionLink.originSelectionRange) : void 0,
      uri: definitionLink.targetUri ? definitionLink.targetUri : location2.uri,
      range: Range.from(definitionLink.targetRange ? definitionLink.targetRange : location2.range),
      targetSelectionRange: definitionLink.targetSelectionRange ? Range.from(definitionLink.targetSelectionRange) : void 0
    };
  }
  DefinitionLink2.from = from;
  function to(value) {
    return {
      targetUri: URI.revive(value.uri),
      targetRange: Range.to(value.range),
      targetSelectionRange: value.targetSelectionRange ? Range.to(value.targetSelectionRange) : void 0,
      originSelectionRange: value.originSelectionRange ? Range.to(value.originSelectionRange) : void 0
    };
  }
  DefinitionLink2.to = to;
})(DefinitionLink || (DefinitionLink = {}));
var Hover;
(function(Hover2) {
  function from(hover) {
    const convertedHover = {
      range: Range.from(hover.range),
      contents: MarkdownString.fromMany(hover.contents),
      canIncreaseVerbosity: hover.canIncreaseVerbosity,
      canDecreaseVerbosity: hover.canDecreaseVerbosity
    };
    return convertedHover;
  }
  Hover2.from = from;
  function to(info) {
    const contents = info.contents.map(MarkdownString.to);
    const range = Range.to(info.range);
    const canIncreaseVerbosity = info.canIncreaseVerbosity;
    const canDecreaseVerbosity = info.canDecreaseVerbosity;
    return new $RT(contents, range, canIncreaseVerbosity, canDecreaseVerbosity);
  }
  Hover2.to = to;
})(Hover || (Hover = {}));
var EvaluatableExpression;
(function(EvaluatableExpression2) {
  function from(expression) {
    return {
      range: Range.from(expression.range),
      expression: expression.expression
    };
  }
  EvaluatableExpression2.from = from;
  function to(info) {
    return new $OU(Range.to(info.range), info.expression);
  }
  EvaluatableExpression2.to = to;
})(EvaluatableExpression || (EvaluatableExpression = {}));
var InlineValue;
(function(InlineValue2) {
  function from(inlineValue) {
    if (inlineValue instanceof $PU) {
      return {
        type: "text",
        range: Range.from(inlineValue.range),
        text: inlineValue.text
      };
    } else if (inlineValue instanceof $QU) {
      return {
        type: "variable",
        range: Range.from(inlineValue.range),
        variableName: inlineValue.variableName,
        caseSensitiveLookup: inlineValue.caseSensitiveLookup
      };
    } else if (inlineValue instanceof $RU) {
      return {
        type: "expression",
        range: Range.from(inlineValue.range),
        expression: inlineValue.expression
      };
    } else {
      throw new Error(`Unknown 'InlineValue' type`);
    }
  }
  InlineValue2.from = from;
  function to(inlineValue) {
    switch (inlineValue.type) {
      case "text":
        return {
          range: Range.to(inlineValue.range),
          text: inlineValue.text
        };
      case "variable":
        return {
          range: Range.to(inlineValue.range),
          variableName: inlineValue.variableName,
          caseSensitiveLookup: inlineValue.caseSensitiveLookup
        };
      case "expression":
        return {
          range: Range.to(inlineValue.range),
          expression: inlineValue.expression
        };
    }
  }
  InlineValue2.to = to;
})(InlineValue || (InlineValue = {}));
var InlineValueContext;
(function(InlineValueContext2) {
  function from(inlineValueContext) {
    return {
      frameId: inlineValueContext.frameId,
      stoppedLocation: Range.from(inlineValueContext.stoppedLocation)
    };
  }
  InlineValueContext2.from = from;
  function to(inlineValueContext) {
    return new $SU(inlineValueContext.frameId, Range.to(inlineValueContext.stoppedLocation));
  }
  InlineValueContext2.to = to;
})(InlineValueContext || (InlineValueContext = {}));
var DocumentHighlight;
(function(DocumentHighlight2) {
  function from(documentHighlight) {
    return {
      range: Range.from(documentHighlight.range),
      kind: documentHighlight.kind
    };
  }
  DocumentHighlight2.from = from;
  function to(occurrence) {
    return new $ST(Range.to(occurrence.range), occurrence.kind);
  }
  DocumentHighlight2.to = to;
})(DocumentHighlight || (DocumentHighlight = {}));
var MultiDocumentHighlight;
(function(MultiDocumentHighlight2) {
  function from(multiDocumentHighlight) {
    return {
      uri: multiDocumentHighlight.uri,
      highlights: multiDocumentHighlight.highlights.map(DocumentHighlight.from)
    };
  }
  MultiDocumentHighlight2.from = from;
  function to(multiDocumentHighlight) {
    return new $TT(URI.revive(multiDocumentHighlight.uri), multiDocumentHighlight.highlights.map(DocumentHighlight.to));
  }
  MultiDocumentHighlight2.to = to;
})(MultiDocumentHighlight || (MultiDocumentHighlight = {}));
var CompletionTriggerKind3;
(function(CompletionTriggerKind4) {
  function to(kind) {
    switch (kind) {
      case 1:
        return CompletionTriggerKind2.TriggerCharacter;
      case 2:
        return CompletionTriggerKind2.TriggerForIncompleteCompletions;
      case 0:
      default:
        return CompletionTriggerKind2.Invoke;
    }
  }
  CompletionTriggerKind4.to = to;
})(CompletionTriggerKind3 || (CompletionTriggerKind3 = {}));
var CompletionContext;
(function(CompletionContext2) {
  function to(context) {
    return {
      triggerKind: CompletionTriggerKind3.to(context.triggerKind),
      triggerCharacter: context.triggerCharacter
    };
  }
  CompletionContext2.to = to;
})(CompletionContext || (CompletionContext = {}));
var CompletionItemTag3;
(function(CompletionItemTag4) {
  function from(kind) {
    switch (kind) {
      case CompletionItemTag2.Deprecated:
        return 1;
    }
  }
  CompletionItemTag4.from = from;
  function to(kind) {
    switch (kind) {
      case 1:
        return CompletionItemTag2.Deprecated;
    }
  }
  CompletionItemTag4.to = to;
})(CompletionItemTag3 || (CompletionItemTag3 = {}));
var CompletionItemKind3;
(function(CompletionItemKind4) {
  const _from = /* @__PURE__ */ new Map([
    [
      CompletionItemKind2.Method,
      0
      /* languages.CompletionItemKind.Method */
    ],
    [
      CompletionItemKind2.Function,
      1
      /* languages.CompletionItemKind.Function */
    ],
    [
      CompletionItemKind2.Constructor,
      2
      /* languages.CompletionItemKind.Constructor */
    ],
    [
      CompletionItemKind2.Field,
      3
      /* languages.CompletionItemKind.Field */
    ],
    [
      CompletionItemKind2.Variable,
      4
      /* languages.CompletionItemKind.Variable */
    ],
    [
      CompletionItemKind2.Class,
      5
      /* languages.CompletionItemKind.Class */
    ],
    [
      CompletionItemKind2.Interface,
      7
      /* languages.CompletionItemKind.Interface */
    ],
    [
      CompletionItemKind2.Struct,
      6
      /* languages.CompletionItemKind.Struct */
    ],
    [
      CompletionItemKind2.Module,
      8
      /* languages.CompletionItemKind.Module */
    ],
    [
      CompletionItemKind2.Property,
      9
      /* languages.CompletionItemKind.Property */
    ],
    [
      CompletionItemKind2.Unit,
      12
      /* languages.CompletionItemKind.Unit */
    ],
    [
      CompletionItemKind2.Value,
      13
      /* languages.CompletionItemKind.Value */
    ],
    [
      CompletionItemKind2.Constant,
      14
      /* languages.CompletionItemKind.Constant */
    ],
    [
      CompletionItemKind2.Enum,
      15
      /* languages.CompletionItemKind.Enum */
    ],
    [
      CompletionItemKind2.EnumMember,
      16
      /* languages.CompletionItemKind.EnumMember */
    ],
    [
      CompletionItemKind2.Keyword,
      17
      /* languages.CompletionItemKind.Keyword */
    ],
    [
      CompletionItemKind2.Snippet,
      27
      /* languages.CompletionItemKind.Snippet */
    ],
    [
      CompletionItemKind2.Text,
      18
      /* languages.CompletionItemKind.Text */
    ],
    [
      CompletionItemKind2.Color,
      19
      /* languages.CompletionItemKind.Color */
    ],
    [
      CompletionItemKind2.File,
      20
      /* languages.CompletionItemKind.File */
    ],
    [
      CompletionItemKind2.Reference,
      21
      /* languages.CompletionItemKind.Reference */
    ],
    [
      CompletionItemKind2.Folder,
      23
      /* languages.CompletionItemKind.Folder */
    ],
    [
      CompletionItemKind2.Event,
      10
      /* languages.CompletionItemKind.Event */
    ],
    [
      CompletionItemKind2.Operator,
      11
      /* languages.CompletionItemKind.Operator */
    ],
    [
      CompletionItemKind2.TypeParameter,
      24
      /* languages.CompletionItemKind.TypeParameter */
    ],
    [
      CompletionItemKind2.Issue,
      26
      /* languages.CompletionItemKind.Issue */
    ],
    [
      CompletionItemKind2.User,
      25
      /* languages.CompletionItemKind.User */
    ]
  ]);
  function from(kind) {
    return _from.get(kind) ?? 9;
  }
  CompletionItemKind4.from = from;
  const _to = /* @__PURE__ */ new Map([
    [0, CompletionItemKind2.Method],
    [1, CompletionItemKind2.Function],
    [2, CompletionItemKind2.Constructor],
    [3, CompletionItemKind2.Field],
    [4, CompletionItemKind2.Variable],
    [5, CompletionItemKind2.Class],
    [7, CompletionItemKind2.Interface],
    [6, CompletionItemKind2.Struct],
    [8, CompletionItemKind2.Module],
    [9, CompletionItemKind2.Property],
    [12, CompletionItemKind2.Unit],
    [13, CompletionItemKind2.Value],
    [14, CompletionItemKind2.Constant],
    [15, CompletionItemKind2.Enum],
    [16, CompletionItemKind2.EnumMember],
    [17, CompletionItemKind2.Keyword],
    [27, CompletionItemKind2.Snippet],
    [18, CompletionItemKind2.Text],
    [19, CompletionItemKind2.Color],
    [20, CompletionItemKind2.File],
    [21, CompletionItemKind2.Reference],
    [23, CompletionItemKind2.Folder],
    [10, CompletionItemKind2.Event],
    [11, CompletionItemKind2.Operator],
    [24, CompletionItemKind2.TypeParameter],
    [25, CompletionItemKind2.User],
    [26, CompletionItemKind2.Issue]
  ]);
  function to(kind) {
    return _to.get(kind) ?? CompletionItemKind2.Property;
  }
  CompletionItemKind4.to = to;
})(CompletionItemKind3 || (CompletionItemKind3 = {}));
var CompletionItem;
(function(CompletionItem2) {
  function to(suggestion, converter) {
    const result = new $0T(suggestion.label);
    result.insertText = suggestion.insertText;
    result.kind = CompletionItemKind3.to(suggestion.kind);
    result.tags = suggestion.tags?.map(CompletionItemTag3.to);
    result.detail = suggestion.detail;
    result.documentation = $dm(suggestion.documentation) ? MarkdownString.to(suggestion.documentation) : suggestion.documentation;
    result.sortText = suggestion.sortText;
    result.filterText = suggestion.filterText;
    result.preselect = suggestion.preselect;
    result.commitCharacters = suggestion.commitCharacters;
    if ($9C.isIRange(suggestion.range)) {
      result.range = Range.to(suggestion.range);
    } else if (typeof suggestion.range === "object") {
      result.range = { inserting: Range.to(suggestion.range.insert), replacing: Range.to(suggestion.range.replace) };
    }
    result.keepWhitespace = typeof suggestion.insertTextRules === "undefined" ? false : Boolean(
      suggestion.insertTextRules & 1
      /* languages.CompletionItemInsertTextRule.KeepWhitespace */
    );
    if (typeof suggestion.insertTextRules !== "undefined" && suggestion.insertTextRules & 4) {
      result.insertText = new $MT(suggestion.insertText);
    } else {
      result.insertText = suggestion.insertText;
      result.textEdit = result.range instanceof $BT ? new $IT(result.range, result.insertText) : void 0;
    }
    if (suggestion.additionalTextEdits && suggestion.additionalTextEdits.length > 0) {
      result.additionalTextEdits = suggestion.additionalTextEdits.map((e) => TextEdit.to(e));
    }
    result.command = converter && suggestion.command ? converter.fromInternal(suggestion.command) : void 0;
    return result;
  }
  CompletionItem2.to = to;
})(CompletionItem || (CompletionItem = {}));
var ParameterInformation;
(function(ParameterInformation2) {
  function from(info) {
    if (typeof info.label !== "string" && !Array.isArray(info.label)) {
      throw new TypeError("Invalid label");
    }
    return {
      label: info.label,
      documentation: MarkdownString.fromStrict(info.documentation)
    };
  }
  ParameterInformation2.from = from;
  function to(info) {
    return {
      label: info.label,
      documentation: $dm(info.documentation) ? MarkdownString.to(info.documentation) : info.documentation
    };
  }
  ParameterInformation2.to = to;
})(ParameterInformation || (ParameterInformation = {}));
var SignatureInformation;
(function(SignatureInformation2) {
  function from(info) {
    return {
      label: info.label,
      documentation: MarkdownString.fromStrict(info.documentation),
      parameters: Array.isArray(info.parameters) ? info.parameters.map(ParameterInformation.from) : [],
      activeParameter: info.activeParameter
    };
  }
  SignatureInformation2.from = from;
  function to(info) {
    return {
      label: info.label,
      documentation: $dm(info.documentation) ? MarkdownString.to(info.documentation) : info.documentation,
      parameters: Array.isArray(info.parameters) ? info.parameters.map(ParameterInformation.to) : [],
      activeParameter: info.activeParameter
    };
  }
  SignatureInformation2.to = to;
})(SignatureInformation || (SignatureInformation = {}));
var SignatureHelp;
(function(SignatureHelp2) {
  function from(help) {
    return {
      activeSignature: help.activeSignature,
      activeParameter: help.activeParameter,
      signatures: Array.isArray(help.signatures) ? help.signatures.map(SignatureInformation.from) : []
    };
  }
  SignatureHelp2.from = from;
  function to(help) {
    return {
      activeSignature: help.activeSignature,
      activeParameter: help.activeParameter,
      signatures: Array.isArray(help.signatures) ? help.signatures.map(SignatureInformation.to) : []
    };
  }
  SignatureHelp2.to = to;
})(SignatureHelp || (SignatureHelp = {}));
var InlayHint;
(function(InlayHint2) {
  function to(converter, hint) {
    const res = new $9T(Position.to(hint.position), typeof hint.label === "string" ? hint.label : hint.label.map(InlayHintLabelPart.to.bind(void 0, converter)), hint.kind && InlayHintKind3.to(hint.kind));
    res.textEdits = hint.textEdits && hint.textEdits.map(TextEdit.to);
    res.tooltip = $dm(hint.tooltip) ? MarkdownString.to(hint.tooltip) : hint.tooltip;
    res.paddingLeft = hint.paddingLeft;
    res.paddingRight = hint.paddingRight;
    return res;
  }
  InlayHint2.to = to;
})(InlayHint || (InlayHint = {}));
var InlayHintLabelPart;
(function(InlayHintLabelPart2) {
  function to(converter, part) {
    const result = new $8T(part.label);
    result.tooltip = $dm(part.tooltip) ? MarkdownString.to(part.tooltip) : part.tooltip;
    if (Command.is(part.command)) {
      result.command = converter.fromInternal(part.command);
    }
    if (part.location) {
      result.location = location.to(part.location);
    }
    return result;
  }
  InlayHintLabelPart2.to = to;
})(InlayHintLabelPart || (InlayHintLabelPart = {}));
var InlayHintKind3;
(function(InlayHintKind4) {
  function from(kind) {
    return kind;
  }
  InlayHintKind4.from = from;
  function to(kind) {
    return kind;
  }
  InlayHintKind4.to = to;
})(InlayHintKind3 || (InlayHintKind3 = {}));
var DocumentLink;
(function(DocumentLink2) {
  function from(link2) {
    return {
      range: Range.from(link2.range),
      url: link2.target,
      tooltip: link2.tooltip
    };
  }
  DocumentLink2.from = from;
  function to(link2) {
    let target = void 0;
    if (link2.url) {
      try {
        target = typeof link2.url === "string" ? URI.parse(link2.url, true) : URI.revive(link2.url);
      } catch (err) {
      }
    }
    const result = new $cU(Range.to(link2.range), target);
    result.tooltip = link2.tooltip;
    return result;
  }
  DocumentLink2.to = to;
})(DocumentLink || (DocumentLink = {}));
var ColorPresentation;
(function(ColorPresentation2) {
  function to(colorPresentation) {
    const cp6 = new $fU(colorPresentation.label);
    if (colorPresentation.textEdit) {
      cp6.textEdit = TextEdit.to(colorPresentation.textEdit);
    }
    if (colorPresentation.additionalTextEdits) {
      cp6.additionalTextEdits = colorPresentation.additionalTextEdits.map((value) => TextEdit.to(value));
    }
    return cp6;
  }
  ColorPresentation2.to = to;
  function from(colorPresentation) {
    return {
      label: colorPresentation.label,
      textEdit: colorPresentation.textEdit ? TextEdit.from(colorPresentation.textEdit) : void 0,
      additionalTextEdits: colorPresentation.additionalTextEdits ? colorPresentation.additionalTextEdits.map((value) => TextEdit.from(value)) : void 0
    };
  }
  ColorPresentation2.from = from;
})(ColorPresentation || (ColorPresentation = {}));
var Color;
(function(Color2) {
  function to(c) {
    return new $dU(c[0], c[1], c[2], c[3]);
  }
  Color2.to = to;
  function from(color2) {
    return [color2.red, color2.green, color2.blue, color2.alpha];
  }
  Color2.from = from;
})(Color || (Color = {}));
var SelectionRange;
(function(SelectionRange2) {
  function from(obj) {
    return { range: Range.from(obj.range) };
  }
  SelectionRange2.from = from;
  function to(obj) {
    return new $YT(Range.to(obj.range));
  }
  SelectionRange2.to = to;
})(SelectionRange || (SelectionRange = {}));
var TextDocumentSaveReason2;
(function(TextDocumentSaveReason3) {
  function to(reason) {
    switch (reason) {
      case 2:
        return TextDocumentSaveReason.AfterDelay;
      case 1:
        return TextDocumentSaveReason.Manual;
      case 3:
      case 4:
        return TextDocumentSaveReason.FocusOut;
    }
  }
  TextDocumentSaveReason3.to = to;
})(TextDocumentSaveReason2 || (TextDocumentSaveReason2 = {}));
var TextEditorLineNumbersStyle2;
(function(TextEditorLineNumbersStyle3) {
  function from(style) {
    switch (style) {
      case TextEditorLineNumbersStyle.Off:
        return 0;
      case TextEditorLineNumbersStyle.Relative:
        return 2;
      case TextEditorLineNumbersStyle.Interval:
        return 3;
      case TextEditorLineNumbersStyle.On:
      default:
        return 1;
    }
  }
  TextEditorLineNumbersStyle3.from = from;
  function to(style) {
    switch (style) {
      case 0:
        return TextEditorLineNumbersStyle.Off;
      case 2:
        return TextEditorLineNumbersStyle.Relative;
      case 3:
        return TextEditorLineNumbersStyle.Interval;
      case 1:
      default:
        return TextEditorLineNumbersStyle.On;
    }
  }
  TextEditorLineNumbersStyle3.to = to;
})(TextEditorLineNumbersStyle2 || (TextEditorLineNumbersStyle2 = {}));
var EndOfLine2;
(function(EndOfLine3) {
  function from(eol) {
    if (eol === EndOfLine.CRLF) {
      return 1;
    } else if (eol === EndOfLine.LF) {
      return 0;
    }
    return void 0;
  }
  EndOfLine3.from = from;
  function to(eol) {
    if (eol === 1) {
      return EndOfLine.CRLF;
    } else if (eol === 0) {
      return EndOfLine.LF;
    }
    return void 0;
  }
  EndOfLine3.to = to;
})(EndOfLine2 || (EndOfLine2 = {}));
var ProgressLocation2;
(function(ProgressLocation4) {
  function from(loc) {
    if (typeof loc === "object") {
      return loc.viewId;
    }
    switch (loc) {
      case ProgressLocation.SourceControl:
        return 3;
      case ProgressLocation.Window:
        return 10;
      case ProgressLocation.Notification:
        return 15;
    }
    throw new Error(`Unknown 'ProgressLocation'`);
  }
  ProgressLocation4.from = from;
})(ProgressLocation2 || (ProgressLocation2 = {}));
var FoldingRange;
(function(FoldingRange2) {
  function from(r) {
    const range = { start: r.start + 1, end: r.end + 1 };
    if (r.kind) {
      range.kind = FoldingRangeKind2.from(r.kind);
    }
    return range;
  }
  FoldingRange2.from = from;
  function to(r) {
    const range = { start: r.start - 1, end: r.end - 1 };
    if (r.kind) {
      range.kind = FoldingRangeKind2.to(r.kind);
    }
    return range;
  }
  FoldingRange2.to = to;
})(FoldingRange || (FoldingRange = {}));
var FoldingRangeKind2;
(function(FoldingRangeKind3) {
  function from(kind) {
    if (kind) {
      switch (kind) {
        case FoldingRangeKind.Comment:
          return $WE.Comment;
        case FoldingRangeKind.Imports:
          return $WE.Imports;
        case FoldingRangeKind.Region:
          return $WE.Region;
      }
    }
    return void 0;
  }
  FoldingRangeKind3.from = from;
  function to(kind) {
    if (kind) {
      switch (kind.value) {
        case $WE.Comment.value:
          return FoldingRangeKind.Comment;
        case $WE.Imports.value:
          return FoldingRangeKind.Imports;
        case $WE.Region.value:
          return FoldingRangeKind.Region;
      }
    }
    return void 0;
  }
  FoldingRangeKind3.to = to;
})(FoldingRangeKind2 || (FoldingRangeKind2 = {}));
var TextEditorOpenOptions;
(function(TextEditorOpenOptions2) {
  function from(options2) {
    if (options2) {
      return {
        pinned: typeof options2.preview === "boolean" ? !options2.preview : void 0,
        inactive: options2.background,
        preserveFocus: options2.preserveFocus,
        selection: typeof options2.selection === "object" ? Range.from(options2.selection) : void 0,
        override: typeof options2.override === "boolean" ? $1K.id : void 0
      };
    }
    return void 0;
  }
  TextEditorOpenOptions2.from = from;
})(TextEditorOpenOptions || (TextEditorOpenOptions = {}));
var GlobPattern;
(function(GlobPattern2) {
  function from(pattern) {
    if (pattern instanceof $CU) {
      return pattern.toJSON();
    }
    if (typeof pattern === "string") {
      return pattern;
    }
    if (isRelativePatternShape(pattern) || isLegacyRelativePatternShape(pattern)) {
      return new $CU(pattern.baseUri ?? pattern.base, pattern.pattern).toJSON();
    }
    return pattern;
  }
  GlobPattern2.from = from;
  function isRelativePatternShape(obj) {
    const rp = obj;
    if (!rp) {
      return false;
    }
    return URI.isUri(rp.baseUri) && typeof rp.pattern === "string";
  }
  function isLegacyRelativePatternShape(obj) {
    const rp = obj;
    if (!rp) {
      return false;
    }
    return typeof rp.base === "string" && typeof rp.pattern === "string";
  }
  function to(pattern) {
    if (typeof pattern === "string") {
      return pattern;
    }
    return new $CU(URI.revive(pattern.baseUri), pattern.pattern);
  }
  GlobPattern2.to = to;
})(GlobPattern || (GlobPattern = {}));
var LanguageSelector;
(function(LanguageSelector2) {
  function from(selector) {
    if (!selector) {
      return void 0;
    } else if (Array.isArray(selector)) {
      return selector.map(from);
    } else if (typeof selector === "string") {
      return selector;
    } else {
      const filter = selector;
      return {
        language: filter.language,
        scheme: filter.scheme,
        pattern: GlobPattern.from(filter.pattern) ?? void 0,
        exclusive: filter.exclusive,
        notebookType: filter.notebookType
      };
    }
  }
  LanguageSelector2.from = from;
})(LanguageSelector || (LanguageSelector = {}));
var MappedEditsContext;
(function(MappedEditsContext2) {
  function is(v) {
    return !!v && typeof v === "object" && "documents" in v && Array.isArray(v.documents) && v.documents.every((subArr) => Array.isArray(subArr) && subArr.every(DocumentContextItem.is));
  }
  MappedEditsContext2.is = is;
  function from(extContext) {
    return {
      documents: extContext.documents.map((subArray) => subArray.map(DocumentContextItem.from)),
      conversation: extContext.conversation?.map((item) => item.type === "request" ? {
        type: "request",
        message: item.message
      } : {
        type: "response",
        message: item.message,
        result: item.result ? ChatAgentResult.from(item.result) : void 0,
        references: item.references?.map(DocumentContextItem.from)
      })
    };
  }
  MappedEditsContext2.from = from;
})(MappedEditsContext || (MappedEditsContext = {}));
var DocumentContextItem;
(function(DocumentContextItem2) {
  function is(item) {
    return typeof item === "object" && item !== null && "uri" in item && URI.isUri(item.uri) && "version" in item && typeof item.version === "number" && "ranges" in item && Array.isArray(item.ranges) && item.ranges.every((r) => r instanceof $BT);
  }
  DocumentContextItem2.is = is;
  function from(item) {
    return {
      uri: item.uri,
      version: item.version,
      ranges: item.ranges.map((r) => Range.from(r))
    };
  }
  DocumentContextItem2.from = from;
  function to(item) {
    return {
      uri: URI.revive(item.uri),
      version: item.version,
      ranges: item.ranges.map((r) => Range.to(r))
    };
  }
  DocumentContextItem2.to = to;
})(DocumentContextItem || (DocumentContextItem = {}));
var NotebookRange;
(function(NotebookRange2) {
  function from(range) {
    return { start: range.start, end: range.end };
  }
  NotebookRange2.from = from;
  function to(range) {
    return new $6U(range.start, range.end);
  }
  NotebookRange2.to = to;
})(NotebookRange || (NotebookRange = {}));
var NotebookCellExecutionSummary;
(function(NotebookCellExecutionSummary2) {
  function to(data) {
    return {
      timing: typeof data.runStartTime === "number" && typeof data.runEndTime === "number" ? { startTime: data.runStartTime, endTime: data.runEndTime } : void 0,
      executionOrder: data.executionOrder,
      success: data.lastRunSuccess
    };
  }
  NotebookCellExecutionSummary2.to = to;
  function from(data) {
    return {
      lastRunSuccess: data.success,
      runStartTime: data.timing?.startTime,
      runEndTime: data.timing?.endTime,
      executionOrder: data.executionOrder
    };
  }
  NotebookCellExecutionSummary2.from = from;
})(NotebookCellExecutionSummary || (NotebookCellExecutionSummary = {}));
var NotebookCellExecutionState3;
(function(NotebookCellExecutionState4) {
  function to(state) {
    if (state === NotebookCellExecutionState.Unconfirmed) {
      return NotebookCellExecutionState2.Pending;
    } else if (state === NotebookCellExecutionState.Pending) {
      return void 0;
    } else if (state === NotebookCellExecutionState.Executing) {
      return NotebookCellExecutionState2.Executing;
    } else {
      throw new Error(`Unknown state: ${state}`);
    }
  }
  NotebookCellExecutionState4.to = to;
})(NotebookCellExecutionState3 || (NotebookCellExecutionState3 = {}));
var NotebookCellKind2;
(function(NotebookCellKind3) {
  function from(data) {
    switch (data) {
      case NotebookCellKind.Markup:
        return CellKind.Markup;
      case NotebookCellKind.Code:
      default:
        return CellKind.Code;
    }
  }
  NotebookCellKind3.from = from;
  function to(data) {
    switch (data) {
      case CellKind.Markup:
        return NotebookCellKind.Markup;
      case CellKind.Code:
      default:
        return NotebookCellKind.Code;
    }
  }
  NotebookCellKind3.to = to;
})(NotebookCellKind2 || (NotebookCellKind2 = {}));
var NotebookData;
(function(NotebookData2) {
  function from(data) {
    const res = {
      metadata: data.metadata ?? /* @__PURE__ */ Object.create(null),
      cells: []
    };
    for (const cell of data.cells) {
      $7U.validate(cell);
      res.cells.push(NotebookCellData.from(cell));
    }
    return res;
  }
  NotebookData2.from = from;
  function to(data) {
    const res = new $8U(data.cells.map(NotebookCellData.to));
    if (!$Mg(data.metadata)) {
      res.metadata = data.metadata;
    }
    return res;
  }
  NotebookData2.to = to;
})(NotebookData || (NotebookData = {}));
var NotebookCellData;
(function(NotebookCellData2) {
  function from(data) {
    return {
      cellKind: NotebookCellKind2.from(data.kind),
      language: data.languageId,
      mime: data.mime,
      source: data.value,
      metadata: data.metadata,
      internalMetadata: NotebookCellExecutionSummary.from(data.executionSummary ?? {}),
      outputs: data.outputs ? data.outputs.map(NotebookCellOutput.from) : []
    };
  }
  NotebookCellData2.from = from;
  function to(data) {
    return new $7U(NotebookCellKind2.to(data.cellKind), data.source, data.language, data.mime, data.outputs ? data.outputs.map(NotebookCellOutput.to) : void 0, data.metadata, data.internalMetadata ? NotebookCellExecutionSummary.to(data.internalMetadata) : void 0);
  }
  NotebookCellData2.to = to;
})(NotebookCellData || (NotebookCellData = {}));
var NotebookCellOutputItem;
(function(NotebookCellOutputItem2) {
  function from(item) {
    return {
      mime: item.mime,
      valueBytes: $Ci.wrap(item.data)
    };
  }
  NotebookCellOutputItem2.from = from;
  function to(item) {
    return new $9U(item.valueBytes.buffer, item.mime);
  }
  NotebookCellOutputItem2.to = to;
})(NotebookCellOutputItem || (NotebookCellOutputItem = {}));
var NotebookCellOutput;
(function(NotebookCellOutput2) {
  function from(output) {
    return {
      outputId: output.id,
      items: output.items.map(NotebookCellOutputItem.from),
      metadata: output.metadata
    };
  }
  NotebookCellOutput2.from = from;
  function to(output) {
    const items = output.items.map(NotebookCellOutputItem.to);
    return new $0U(items, output.outputId, output.metadata);
  }
  NotebookCellOutput2.to = to;
})(NotebookCellOutput || (NotebookCellOutput = {}));
var NotebookExclusiveDocumentPattern;
(function(NotebookExclusiveDocumentPattern2) {
  function from(pattern) {
    if (isExclusivePattern(pattern)) {
      return {
        include: GlobPattern.from(pattern.include) ?? void 0,
        exclude: GlobPattern.from(pattern.exclude) ?? void 0
      };
    }
    return GlobPattern.from(pattern) ?? void 0;
  }
  NotebookExclusiveDocumentPattern2.from = from;
  function to(pattern) {
    if (isExclusivePattern(pattern)) {
      return {
        include: GlobPattern.to(pattern.include),
        exclude: GlobPattern.to(pattern.exclude)
      };
    }
    return GlobPattern.to(pattern);
  }
  NotebookExclusiveDocumentPattern2.to = to;
  function isExclusivePattern(obj) {
    const ep = obj;
    if (!ep) {
      return false;
    }
    return !$Ig(ep.include) && !$Ig(ep.exclude);
  }
})(NotebookExclusiveDocumentPattern || (NotebookExclusiveDocumentPattern = {}));
var NotebookStatusBarItem;
(function(NotebookStatusBarItem2) {
  function from(item, commandsConverter, disposables) {
    const command = typeof item.command === "string" ? { title: "", command: item.command } : item.command;
    return {
      alignment: item.alignment === NotebookCellStatusBarAlignment.Left ? 1 : 2,
      command: commandsConverter.toInternal(command, disposables),
      // TODO@roblou
      text: item.text,
      tooltip: item.tooltip,
      accessibilityInformation: item.accessibilityInformation,
      priority: item.priority
    };
  }
  NotebookStatusBarItem2.from = from;
})(NotebookStatusBarItem || (NotebookStatusBarItem = {}));
var NotebookKernelSourceAction;
(function(NotebookKernelSourceAction2) {
  function from(item, commandsConverter, disposables) {
    const command = typeof item.command === "string" ? { title: "", command: item.command } : item.command;
    return {
      command: commandsConverter.toInternal(command, disposables),
      label: item.label,
      description: item.description,
      detail: item.detail,
      documentation: item.documentation
    };
  }
  NotebookKernelSourceAction2.from = from;
})(NotebookKernelSourceAction || (NotebookKernelSourceAction = {}));
var NotebookDocumentContentOptions;
(function(NotebookDocumentContentOptions2) {
  function from(options2) {
    return {
      transientOutputs: options2?.transientOutputs ?? false,
      transientCellMetadata: options2?.transientCellMetadata ?? {},
      transientDocumentMetadata: options2?.transientDocumentMetadata ?? {},
      cellContentMetadata: options2?.cellContentMetadata ?? {}
    };
  }
  NotebookDocumentContentOptions2.from = from;
})(NotebookDocumentContentOptions || (NotebookDocumentContentOptions = {}));
var NotebookRendererScript;
(function(NotebookRendererScript2) {
  function from(preload) {
    return {
      uri: preload.uri,
      provides: preload.provides
    };
  }
  NotebookRendererScript2.from = from;
  function to(preload) {
    return new $aV(URI.revive(preload.uri), preload.provides);
  }
  NotebookRendererScript2.to = to;
})(NotebookRendererScript || (NotebookRendererScript = {}));
var TestMessage;
(function(TestMessage2) {
  function from(message) {
    return {
      message: MarkdownString.fromStrict(message.message) || "",
      type: 0,
      expected: message.expectedOutput,
      actual: message.actualOutput,
      contextValue: message.contextValue,
      location: message.location && { range: Range.from(message.location.range), uri: message.location.uri },
      stackTrace: message.stackTrace?.map((s) => ({
        label: s.label,
        position: s.position && Position.from(s.position),
        uri: s.uri && URI.revive(s.uri).toJSON()
      }))
    };
  }
  TestMessage2.from = from;
  function to(item) {
    const message = new $hV(typeof item.message === "string" ? item.message : MarkdownString.to(item.message));
    message.actualOutput = item.actual;
    message.expectedOutput = item.expected;
    message.contextValue = item.contextValue;
    message.location = item.location ? location.to(item.location) : void 0;
    return message;
  }
  TestMessage2.to = to;
})(TestMessage || (TestMessage = {}));
var TestTag;
(function(TestTag2) {
  TestTag2.namespace = $sQ;
  TestTag2.denamespace = $tQ;
})(TestTag || (TestTag = {}));
var TestRunProfile;
(function(TestRunProfile2) {
  function from(item) {
    return {
      controllerId: item.controllerId,
      profileId: item.profileId,
      group: TestRunProfileKind2.from(item.kind)
    };
  }
  TestRunProfile2.from = from;
})(TestRunProfile || (TestRunProfile = {}));
var TestRunProfileKind2;
(function(TestRunProfileKind3) {
  const profileGroupToBitset = {
    [TestRunProfileKind.Coverage]: 8,
    [TestRunProfileKind.Debug]: 4,
    [TestRunProfileKind.Run]: 2
  };
  function from(kind) {
    return profileGroupToBitset.hasOwnProperty(kind) ? profileGroupToBitset[kind] : 2;
  }
  TestRunProfileKind3.from = from;
})(TestRunProfileKind2 || (TestRunProfileKind2 = {}));
var TestItem;
(function(TestItem2) {
  function from(item) {
    const ctrlId = $cW(item).controllerId;
    return {
      extId: $mQ.fromExtHostTestItem(item, ctrlId).toString(),
      label: item.label,
      uri: URI.revive(item.uri),
      busy: item.busy,
      tags: item.tags.map((t) => TestTag.namespace(ctrlId, t.id)),
      range: $9C.lift(Range.from(item.range)),
      description: item.description || null,
      sortText: item.sortText || null,
      error: item.error ? MarkdownString.fromStrict(item.error) || null : null
    };
  }
  TestItem2.from = from;
  function toPlain(item) {
    return {
      parent: void 0,
      error: void 0,
      id: $mQ.fromString(item.extId).localId,
      label: item.label,
      uri: URI.revive(item.uri),
      tags: (item.tags || []).map((t) => {
        const { tagId } = TestTag.denamespace(t);
        return new $iV(tagId);
      }),
      children: {
        add: () => {
        },
        delete: () => {
        },
        forEach: () => {
        },
        *[Symbol.iterator]() {
        },
        get: () => void 0,
        replace: () => {
        },
        size: 0
      },
      range: Range.to(item.range || void 0),
      canResolveChildren: false,
      busy: item.busy,
      description: item.description || void 0,
      sortText: item.sortText || void 0
    };
  }
  TestItem2.toPlain = toPlain;
})(TestItem || (TestItem = {}));
(function(TestTag2) {
  function from(tag2) {
    return { id: tag2.id };
  }
  TestTag2.from = from;
  function to(tag2) {
    return new $iV(tag2.id);
  }
  TestTag2.to = to;
})(TestTag || (TestTag = {}));
var TestResults;
(function(TestResults2) {
  const convertTestResultItem = (node, parent) => {
    const item = node.value;
    if (!item) {
      return void 0;
    }
    const snapshot = {
      ...TestItem.toPlain(item.item),
      parent,
      taskStates: item.tasks.map((t) => ({
        state: t.state,
        duration: t.duration,
        messages: t.messages.filter(
          (m) => m.type === 0
          /* TestMessageType.Error */
        ).map(TestMessage.to)
      })),
      children: []
    };
    if (node.children) {
      for (const child of node.children.values()) {
        const c = convertTestResultItem(child, snapshot);
        if (c) {
          snapshot.children.push(c);
        }
      }
    }
    return snapshot;
  };
  function to(serialized) {
    const tree = new $lQ();
    for (const item of serialized.items) {
      tree.insert($mQ.fromString(item.item.extId).path, item);
    }
    const queue = [tree.nodes];
    const roots = [];
    while (queue.length) {
      for (const node of queue.pop()) {
        if (node.value) {
          roots.push(node);
        } else if (node.children) {
          queue.push(node.children.values());
        }
      }
    }
    return {
      completedAt: serialized.completedAt,
      results: roots.map((r) => convertTestResultItem(r)).filter($Hg)
    };
  }
  TestResults2.to = to;
})(TestResults || (TestResults = {}));
var TestCoverage;
(function(TestCoverage2) {
  function fromCoverageCount(count) {
    return { covered: count.covered, total: count.total };
  }
  function fromLocation(location2) {
    return "line" in location2 ? Position.from(location2) : Range.from(location2);
  }
  function toLocation(location2) {
    if (!location2) {
      return void 0;
    }
    return "endLineNumber" in location2 ? Range.to(location2) : Position.to(location2);
  }
  function to(serialized) {
    if (serialized.type === 1) {
      const branches = [];
      if (serialized.branches) {
        for (const branch of serialized.branches) {
          branches.push({
            executed: branch.count,
            location: toLocation(branch.location),
            label: branch.label
          });
        }
      }
      return new $nV(serialized.count, toLocation(serialized.location), serialized.branches?.map((b) => new $oV(b.count, toLocation(b.location), b.label)));
    } else {
      return new $pV(serialized.name, serialized.count, toLocation(serialized.location));
    }
  }
  TestCoverage2.to = to;
  function fromDetails(coverage) {
    if (typeof coverage.executed === "number" && coverage.executed < 0) {
      throw new Error(`Invalid coverage count ${coverage.executed}`);
    }
    if ("branches" in coverage) {
      return {
        count: coverage.executed,
        location: fromLocation(coverage.location),
        type: 1,
        branches: coverage.branches.length ? coverage.branches.map((b) => ({ count: b.executed, location: b.location && fromLocation(b.location), label: b.label })) : void 0
      };
    } else {
      return {
        type: 0,
        name: coverage.name,
        count: coverage.executed,
        location: fromLocation(coverage.location)
      };
    }
  }
  TestCoverage2.fromDetails = fromDetails;
  function fromFile(controllerId, id2, coverage) {
    $lV(coverage.statementCoverage);
    $lV(coverage.branchCoverage);
    $lV(coverage.declarationCoverage);
    return {
      id: id2,
      uri: coverage.uri,
      statement: fromCoverageCount(coverage.statementCoverage),
      branch: coverage.branchCoverage && fromCoverageCount(coverage.branchCoverage),
      declaration: coverage.declarationCoverage && fromCoverageCount(coverage.declarationCoverage),
      testIds: coverage instanceof $mV && coverage.includesTests.length ? coverage.includesTests.map((t) => $mQ.fromExtHostTestItem(t, controllerId).toString()) : void 0
    };
  }
  TestCoverage2.fromFile = fromFile;
})(TestCoverage || (TestCoverage = {}));
var CodeActionTriggerKind2;
(function(CodeActionTriggerKind3) {
  function to(value) {
    switch (value) {
      case 1:
        return CodeActionTriggerKind.Invoke;
      case 2:
        return CodeActionTriggerKind.Automatic;
    }
  }
  CodeActionTriggerKind3.to = to;
})(CodeActionTriggerKind2 || (CodeActionTriggerKind2 = {}));
var TypeHierarchyItem;
(function(TypeHierarchyItem2) {
  function to(item) {
    const result = new $qV(SymbolKind3.to(item.kind), item.name, item.detail || "", URI.revive(item.uri), Range.to(item.range), Range.to(item.selectionRange));
    result._sessionId = item._sessionId;
    result._itemId = item._itemId;
    return result;
  }
  TypeHierarchyItem2.to = to;
  function from(item, sessionId, itemId) {
    sessionId = sessionId ?? item._sessionId;
    itemId = itemId ?? item._itemId;
    if (sessionId === void 0 || itemId === void 0) {
      throw new Error("invalid item");
    }
    return {
      _sessionId: sessionId,
      _itemId: itemId,
      kind: SymbolKind3.from(item.kind),
      name: item.name,
      detail: item.detail ?? "",
      uri: item.uri,
      range: Range.from(item.range),
      selectionRange: Range.from(item.selectionRange),
      tags: item.tags?.map(SymbolTag3.from)
    };
  }
  TypeHierarchyItem2.from = from;
})(TypeHierarchyItem || (TypeHierarchyItem = {}));
var ViewBadge2;
(function(ViewBadge3) {
  function from(badge) {
    if (!badge) {
      return void 0;
    }
    return {
      value: badge.value,
      tooltip: badge.tooltip
    };
  }
  ViewBadge3.from = from;
})(ViewBadge2 || (ViewBadge2 = {}));
var DataTransferItem;
(function(DataTransferItem2) {
  function to(mime, item, resolveFileData) {
    const file = item.fileData;
    if (file) {
      return new $uU(new $vU(file.name, URI.revive(file.uri), file.id, $Qc(() => resolveFileData(file.id))));
    }
    if (mime === $YC.uriList && item.uriListData) {
      return new $tU(reviveUriList(item.uriListData));
    }
    return new $tU(item.asString);
  }
  DataTransferItem2.to = to;
  async function from(mime, item) {
    const stringValue = await item.asString();
    if (mime === $YC.uriList) {
      return {
        asString: stringValue,
        fileData: void 0,
        uriListData: serializeUriList(stringValue)
      };
    }
    const fileValue = item.asFile();
    return {
      asString: stringValue,
      fileData: fileValue ? {
        name: fileValue.name,
        uri: fileValue.uri,
        id: fileValue._itemId ?? fileValue.id
      } : void 0
    };
  }
  DataTransferItem2.from = from;
  function serializeUriList(stringValue) {
    return $nE.split(stringValue).map((part) => {
      if (part.startsWith("#")) {
        return part;
      }
      try {
        return URI.parse(part);
      } catch {
      }
      return part;
    });
  }
  function reviveUriList(parts) {
    return $nE.create(parts.map((part) => {
      return typeof part === "string" ? part : URI.revive(part);
    }));
  }
})(DataTransferItem || (DataTransferItem = {}));
var DataTransfer;
(function(DataTransfer2) {
  function toDataTransfer(value, resolveFileData) {
    const init = value.items.map(([type, item]) => {
      return [type, DataTransferItem.to(type, item, resolveFileData)];
    });
    return new $wU(init);
  }
  DataTransfer2.toDataTransfer = toDataTransfer;
  async function from(dataTransfer) {
    const newDTO = { items: [] };
    const promises8 = [];
    for (const [mime, value] of dataTransfer) {
      promises8.push((async () => {
        newDTO.items.push([mime, await DataTransferItem.from(mime, value)]);
      })());
    }
    await Promise.all(promises8);
    return newDTO;
  }
  DataTransfer2.from = from;
})(DataTransfer || (DataTransfer = {}));
var ChatFollowup;
(function(ChatFollowup2) {
  function from(followup, request) {
    return {
      kind: "reply",
      agentId: followup.participant ?? request?.agentId ?? "",
      subCommand: followup.command ?? request?.command,
      message: followup.prompt,
      title: followup.label
    };
  }
  ChatFollowup2.from = from;
  function to(followup) {
    return {
      prompt: followup.message,
      label: followup.title,
      participant: followup.agentId,
      command: followup.subCommand
    };
  }
  ChatFollowup2.to = to;
})(ChatFollowup || (ChatFollowup = {}));
var LanguageModelChatMessageRole2;
(function(LanguageModelChatMessageRole3) {
  function to(role) {
    switch (role) {
      case 0:
        return LanguageModelChatMessageRole.System;
      case 1:
        return LanguageModelChatMessageRole.User;
      case 2:
        return LanguageModelChatMessageRole.Assistant;
    }
  }
  LanguageModelChatMessageRole3.to = to;
  function from(role) {
    switch (role) {
      case LanguageModelChatMessageRole.System:
        return 0;
      case LanguageModelChatMessageRole.User:
        return 1;
      case LanguageModelChatMessageRole.Assistant:
        return 2;
    }
    return 1;
  }
  LanguageModelChatMessageRole3.from = from;
})(LanguageModelChatMessageRole2 || (LanguageModelChatMessageRole2 = {}));
var LanguageModelChatMessage;
(function(LanguageModelChatMessage2) {
  function to(message) {
    const content = message.content.map((c) => {
      if (c.type === "text") {
        return new $1V(c.value);
      } else if (c.type === "tool_result") {
        const content2 = c.value.map((part) => {
          if (part.type === "text") {
            return new $1V(part.value);
          } else {
            return new $2V(part.value);
          }
        });
        return new $XV(c.toolCallId, content2, c.isError);
      } else {
        return new $ZV(c.toolCallId, c.name, c.parameters);
      }
    });
    const role = LanguageModelChatMessageRole2.to(message.role);
    const result = new $YV(role, content, message.name);
    return result;
  }
  LanguageModelChatMessage2.to = to;
  function from(message) {
    const role = LanguageModelChatMessageRole2.from(message.role);
    const name = message.name;
    let messageContent = message.content;
    if (typeof messageContent === "string") {
      messageContent = [new $1V(messageContent)];
    }
    const content = messageContent.map((c) => {
      if (c instanceof $XV) {
        return {
          type: "tool_result",
          toolCallId: c.callId,
          value: $Mb(c.content.map((part) => {
            if (part instanceof $1V) {
              return {
                type: "text",
                value: part.value
              };
            } else if (part instanceof $2V) {
              return {
                type: "prompt_tsx",
                value: part.value
              };
            } else {
              return void 0;
            }
          })),
          isError: c.isError
        };
      } else if (c instanceof $ZV) {
        return {
          type: "tool_use",
          toolCallId: c.callId,
          name: c.name,
          parameters: c.input
        };
      } else if (c instanceof $1V) {
        return {
          type: "text",
          value: c.value
        };
      } else {
        if (typeof c !== "string") {
          throw new Error("Unexpected chat message content type");
        }
        return {
          type: "text",
          value: c
        };
      }
    });
    return {
      role,
      name,
      content
    };
  }
  LanguageModelChatMessage2.from = from;
})(LanguageModelChatMessage || (LanguageModelChatMessage = {}));
var ChatResponseMarkdownPart;
(function(ChatResponseMarkdownPart2) {
  function from(part) {
    return {
      kind: "markdownContent",
      content: MarkdownString.from(part.value)
    };
  }
  ChatResponseMarkdownPart2.from = from;
  function to(part) {
    return new $DV(MarkdownString.to(part.content));
  }
  ChatResponseMarkdownPart2.to = to;
})(ChatResponseMarkdownPart || (ChatResponseMarkdownPart = {}));
var ChatResponseCodeblockUriPart;
(function(ChatResponseCodeblockUriPart2) {
  function from(part) {
    return {
      kind: "codeblockUri",
      uri: part.value
    };
  }
  ChatResponseCodeblockUriPart2.from = from;
  function to(part) {
    return new $OV(URI.revive(part.uri));
  }
  ChatResponseCodeblockUriPart2.to = to;
})(ChatResponseCodeblockUriPart || (ChatResponseCodeblockUriPart = {}));
var ChatResponseMarkdownWithVulnerabilitiesPart;
(function(ChatResponseMarkdownWithVulnerabilitiesPart2) {
  function from(part) {
    return {
      kind: "markdownVuln",
      content: MarkdownString.from(part.value),
      vulnerabilities: part.vulnerabilities
    };
  }
  ChatResponseMarkdownWithVulnerabilitiesPart2.from = from;
  function to(part) {
    return new $EV(MarkdownString.to(part.content), part.vulnerabilities);
  }
  ChatResponseMarkdownWithVulnerabilitiesPart2.to = to;
})(ChatResponseMarkdownWithVulnerabilitiesPart || (ChatResponseMarkdownWithVulnerabilitiesPart = {}));
var ChatResponseDetectedParticipantPart;
(function(ChatResponseDetectedParticipantPart2) {
  function from(part) {
    return {
      kind: "agentDetection",
      agentId: part.participant,
      command: part.command
    };
  }
  ChatResponseDetectedParticipantPart2.from = from;
  function to(part) {
    return new $FV(part.agentId, part.command);
  }
  ChatResponseDetectedParticipantPart2.to = to;
})(ChatResponseDetectedParticipantPart || (ChatResponseDetectedParticipantPart = {}));
var ChatResponseConfirmationPart;
(function(ChatResponseConfirmationPart2) {
  function from(part) {
    return {
      kind: "confirmation",
      title: part.title,
      message: part.message,
      data: part.data,
      buttons: part.buttons
    };
  }
  ChatResponseConfirmationPart2.from = from;
})(ChatResponseConfirmationPart || (ChatResponseConfirmationPart = {}));
var ChatResponseFilesPart;
(function(ChatResponseFilesPart2) {
  function from(part) {
    const { value, baseUri } = part;
    function convert(items, baseUri2) {
      return items.map((item) => {
        const myUri = URI.joinPath(baseUri2, item.name);
        return {
          label: item.name,
          uri: myUri,
          children: item.children && convert(item.children, myUri)
        };
      });
    }
    return {
      kind: "treeData",
      treeData: {
        label: $sh(baseUri),
        uri: baseUri,
        children: convert(value, baseUri)
      }
    };
  }
  ChatResponseFilesPart2.from = from;
  function to(part) {
    const treeData = $cu(part.treeData);
    function convert(items2) {
      return items2.map((item) => {
        return {
          name: item.label,
          children: item.children && convert(item.children)
        };
      });
    }
    const baseUri = treeData.uri;
    const items = treeData.children ? convert(treeData.children) : [];
    return new $HV(items, baseUri);
  }
  ChatResponseFilesPart2.to = to;
})(ChatResponseFilesPart || (ChatResponseFilesPart = {}));
var ChatResponseAnchorPart;
(function(ChatResponseAnchorPart2) {
  function from(part) {
    const isUri3 = (thing) => URI.isUri(thing);
    const isSymbolInformation = (thing) => "name" in thing;
    return {
      kind: "inlineReference",
      name: part.title,
      inlineReference: isUri3(part.value) ? part.value : isSymbolInformation(part.value) ? WorkspaceSymbol.from(part.value) : Location.from(part.value)
    };
  }
  ChatResponseAnchorPart2.from = from;
  function to(part) {
    const value = $cu(part);
    return new $IV(URI.isUri(value.inlineReference) ? value.inlineReference : "location" in value.inlineReference ? WorkspaceSymbol.to(value.inlineReference) : Location.to(value.inlineReference), part.name);
  }
  ChatResponseAnchorPart2.to = to;
})(ChatResponseAnchorPart || (ChatResponseAnchorPart = {}));
var ChatResponseProgressPart;
(function(ChatResponseProgressPart2) {
  function from(part) {
    return {
      kind: "progressMessage",
      content: MarkdownString.from(part.value)
    };
  }
  ChatResponseProgressPart2.from = from;
  function to(part) {
    return new $JV(part.content.value);
  }
  ChatResponseProgressPart2.to = to;
})(ChatResponseProgressPart || (ChatResponseProgressPart = {}));
var ChatResponseWarningPart;
(function(ChatResponseWarningPart2) {
  function from(part) {
    return {
      kind: "warning",
      content: MarkdownString.from(part.value)
    };
  }
  ChatResponseWarningPart2.from = from;
  function to(part) {
    return new $LV(part.content.value);
  }
  ChatResponseWarningPart2.to = to;
})(ChatResponseWarningPart || (ChatResponseWarningPart = {}));
var ChatResponseMovePart;
(function(ChatResponseMovePart2) {
  function from(part) {
    return {
      kind: "move",
      uri: part.uri,
      range: Range.from(part.range)
    };
  }
  ChatResponseMovePart2.from = from;
  function to(part) {
    return new $QV(URI.revive(part.uri), Range.to(part.range));
  }
  ChatResponseMovePart2.to = to;
})(ChatResponseMovePart || (ChatResponseMovePart = {}));
var ChatTask;
(function(ChatTask2) {
  function from(part) {
    return {
      kind: "progressTask",
      content: MarkdownString.from(part.value)
    };
  }
  ChatTask2.from = from;
})(ChatTask || (ChatTask = {}));
var ChatTaskResult;
(function(ChatTaskResult2) {
  function from(part) {
    return {
      kind: "progressTaskResult",
      content: typeof part === "string" ? MarkdownString.from(part) : void 0
    };
  }
  ChatTaskResult2.from = from;
})(ChatTaskResult || (ChatTaskResult = {}));
var ChatResponseCommandButtonPart;
(function(ChatResponseCommandButtonPart2) {
  function from(part, commandsConverter, commandDisposables) {
    const command = commandsConverter.toInternal(part.value, commandDisposables) ?? { command: part.value.command, title: part.value.title };
    return {
      kind: "command",
      command
    };
  }
  ChatResponseCommandButtonPart2.from = from;
  function to(part, commandsConverter) {
    return new $MV(commandsConverter.fromInternal(part.command) ?? { command: part.command.id, title: part.command.title });
  }
  ChatResponseCommandButtonPart2.to = to;
})(ChatResponseCommandButtonPart || (ChatResponseCommandButtonPart = {}));
var ChatResponseTextEditPart;
(function(ChatResponseTextEditPart2) {
  function from(part) {
    return {
      kind: "textEdit",
      uri: part.uri,
      edits: part.edits.map((e) => TextEdit.from(e)),
      done: part.isDone
    };
  }
  ChatResponseTextEditPart2.from = from;
  function to(part) {
    const result = new $RV(URI.revive(part.uri), part.edits.map((e) => TextEdit.to(e)));
    result.isDone = part.done;
    return result;
  }
  ChatResponseTextEditPart2.to = to;
})(ChatResponseTextEditPart || (ChatResponseTextEditPart = {}));
var ChatResponseReferencePart;
(function(ChatResponseReferencePart2) {
  function from(part) {
    const iconPath = ThemeIcon.isThemeIcon(part.iconPath) ? part.iconPath : URI.isUri(part.iconPath) ? { light: URI.revive(part.iconPath) } : part.iconPath && "light" in part.iconPath && "dark" in part.iconPath && URI.isUri(part.iconPath.light) && URI.isUri(part.iconPath.dark) ? { light: URI.revive(part.iconPath.light), dark: URI.revive(part.iconPath.dark) } : void 0;
    if (typeof part.value === "object" && "variableName" in part.value) {
      return {
        kind: "reference",
        reference: {
          variableName: part.value.variableName,
          value: URI.isUri(part.value.value) || !part.value.value ? part.value.value : Location.from(part.value.value)
        },
        iconPath,
        options: part.options
      };
    }
    return {
      kind: "reference",
      reference: URI.isUri(part.value) || typeof part.value === "string" ? part.value : Location.from(part.value),
      iconPath,
      options: part.options
    };
  }
  ChatResponseReferencePart2.from = from;
  function to(part) {
    const value = $cu(part);
    const mapValue = (value2) => URI.isUri(value2) ? value2 : Location.to(value2);
    return new $NV(typeof value.reference === "string" ? value.reference : "variableName" in value.reference ? {
      variableName: value.reference.variableName,
      value: value.reference.value && mapValue(value.reference.value)
    } : mapValue(value.reference));
  }
  ChatResponseReferencePart2.to = to;
})(ChatResponseReferencePart || (ChatResponseReferencePart = {}));
var ChatResponseCodeCitationPart;
(function(ChatResponseCodeCitationPart2) {
  function from(part) {
    return {
      kind: "codeCitation",
      value: part.value,
      license: part.license,
      snippet: part.snippet
    };
  }
  ChatResponseCodeCitationPart2.from = from;
})(ChatResponseCodeCitationPart || (ChatResponseCodeCitationPart = {}));
var ChatResponsePart;
(function(ChatResponsePart2) {
  function from(part, commandsConverter, commandDisposables) {
    if (part instanceof $DV) {
      return ChatResponseMarkdownPart.from(part);
    } else if (part instanceof $IV) {
      return ChatResponseAnchorPart.from(part);
    } else if (part instanceof $NV) {
      return ChatResponseReferencePart.from(part);
    } else if (part instanceof $JV) {
      return ChatResponseProgressPart.from(part);
    } else if (part instanceof $HV) {
      return ChatResponseFilesPart.from(part);
    } else if (part instanceof $MV) {
      return ChatResponseCommandButtonPart.from(part, commandsConverter, commandDisposables);
    } else if (part instanceof $RV) {
      return ChatResponseTextEditPart.from(part);
    } else if (part instanceof $EV) {
      return ChatResponseMarkdownWithVulnerabilitiesPart.from(part);
    } else if (part instanceof $OV) {
      return ChatResponseCodeblockUriPart.from(part);
    } else if (part instanceof $FV) {
      return ChatResponseDetectedParticipantPart.from(part);
    } else if (part instanceof $LV) {
      return ChatResponseWarningPart.from(part);
    } else if (part instanceof $GV) {
      return ChatResponseConfirmationPart.from(part);
    } else if (part instanceof $PV) {
      return ChatResponseCodeCitationPart.from(part);
    } else if (part instanceof $QV) {
      return ChatResponseMovePart.from(part);
    }
    return {
      kind: "markdownContent",
      content: MarkdownString.from("")
    };
  }
  ChatResponsePart2.from = from;
  function to(part, commandsConverter) {
    switch (part.kind) {
      case "reference":
        return ChatResponseReferencePart.to(part);
      case "markdownContent":
      case "inlineReference":
      case "progressMessage":
      case "treeData":
      case "command":
        return toContent(part, commandsConverter);
    }
    return void 0;
  }
  ChatResponsePart2.to = to;
  function toContent(part, commandsConverter) {
    switch (part.kind) {
      case "markdownContent":
        return ChatResponseMarkdownPart.to(part);
      case "inlineReference":
        return ChatResponseAnchorPart.to(part);
      case "progressMessage":
        return void 0;
      case "treeData":
        return ChatResponseFilesPart.to(part);
      case "command":
        return ChatResponseCommandButtonPart.to(part, commandsConverter);
    }
    return void 0;
  }
  ChatResponsePart2.toContent = toContent;
})(ChatResponsePart || (ChatResponsePart = {}));
var ChatAgentRequest;
(function(ChatAgentRequest2) {
  function to(request, location2, model) {
    const toolReferences = request.variables.variables.filter((v) => v.isTool);
    const variableReferences = request.variables.variables.filter((v) => !v.isTool);
    return {
      prompt: request.message,
      command: request.command,
      attempt: request.attempt ?? 0,
      enableCommandDetection: request.enableCommandDetection ?? true,
      isParticipantDetected: request.isParticipantDetected ?? false,
      references: variableReferences.map(ChatPromptReference.to),
      toolReferences: toolReferences.map(ChatLanguageModelToolReference.to),
      location: ChatLocation2.to(request.location),
      acceptedConfirmationData: request.acceptedConfirmationData,
      rejectedConfirmationData: request.rejectedConfirmationData,
      location2,
      toolInvocationToken: Object.freeze({ sessionId: request.sessionId }),
      model
    };
  }
  ChatAgentRequest2.to = to;
})(ChatAgentRequest || (ChatAgentRequest = {}));
var ChatRequestDraft;
(function(ChatRequestDraft2) {
  function to(request) {
    return {
      prompt: request.prompt,
      files: request.files.map((uri) => URI.revive(uri))
    };
  }
  ChatRequestDraft2.to = to;
})(ChatRequestDraft || (ChatRequestDraft = {}));
var ChatLocation2;
(function(ChatLocation3) {
  function to(loc) {
    switch (loc) {
      case ChatAgentLocation.Notebook:
        return ChatLocation.Notebook;
      case ChatAgentLocation.Terminal:
        return ChatLocation.Terminal;
      case ChatAgentLocation.Panel:
        return ChatLocation.Panel;
      case ChatAgentLocation.Editor:
        return ChatLocation.Editor;
      case ChatAgentLocation.EditingSession:
        return ChatLocation.EditingSession;
    }
  }
  ChatLocation3.to = to;
  function from(loc) {
    switch (loc) {
      case ChatLocation.Notebook:
        return ChatAgentLocation.Notebook;
      case ChatLocation.Terminal:
        return ChatAgentLocation.Terminal;
      case ChatLocation.Panel:
        return ChatAgentLocation.Panel;
      case ChatLocation.Editor:
        return ChatAgentLocation.Editor;
      case ChatLocation.EditingSession:
        return ChatAgentLocation.EditingSession;
    }
  }
  ChatLocation3.from = from;
})(ChatLocation2 || (ChatLocation2 = {}));
var ChatPromptReference;
(function(ChatPromptReference2) {
  function to(variable) {
    const value = variable.value;
    if (!value) {
      throw new Error("Invalid value reference");
    }
    return {
      id: variable.id,
      name: variable.name,
      range: variable.range && [variable.range.start, variable.range.endExclusive],
      value: $zc(value) ? URI.revive(value) : value && typeof value === "object" && "uri" in value && "range" in value && $zc(value.uri) ? Location.to($cu(value)) : variable.isImage ? new $WV(variable.mimeType ?? "image/png", () => Promise.resolve(new Uint8Array(Object.values(value)))) : value,
      modelDescription: variable.modelDescription
    };
  }
  ChatPromptReference2.to = to;
})(ChatPromptReference || (ChatPromptReference = {}));
var ChatLanguageModelToolReference;
(function(ChatLanguageModelToolReference2) {
  function to(variable) {
    const value = variable.value;
    if (value) {
      throw new Error("Invalid tool reference");
    }
    return {
      name: variable.id,
      range: variable.range && [variable.range.start, variable.range.endExclusive]
    };
  }
  ChatLanguageModelToolReference2.to = to;
})(ChatLanguageModelToolReference || (ChatLanguageModelToolReference = {}));
var ChatAgentCompletionItem;
(function(ChatAgentCompletionItem2) {
  function from(item, commandsConverter, disposables) {
    return {
      id: item.id,
      label: item.label,
      fullName: item.fullName,
      icon: item.icon?.id,
      value: item.values[0].value,
      insertText: item.insertText,
      detail: item.detail,
      documentation: item.documentation,
      command: commandsConverter.toInternal(item.command, disposables)
    };
  }
  ChatAgentCompletionItem2.from = from;
})(ChatAgentCompletionItem || (ChatAgentCompletionItem = {}));
var ChatAgentResult;
(function(ChatAgentResult2) {
  function to(result) {
    return {
      errorDetails: result.errorDetails,
      metadata: reviveMetadata(result.metadata),
      nextQuestion: result.nextQuestion
    };
  }
  ChatAgentResult2.to = to;
  function from(result) {
    return {
      errorDetails: result.errorDetails,
      metadata: result.metadata,
      nextQuestion: result.nextQuestion
    };
  }
  ChatAgentResult2.from = from;
  function reviveMetadata(metadata) {
    return $Nv(metadata, (value) => {
      if (value.$mid === 20) {
        return new $7V($Nv(value.content, reviveMetadata));
      } else if (value.$mid === 21) {
        return new $1V(value.value);
      } else if (value.$mid === 22) {
        return new $2V(value.value);
      }
      return void 0;
    });
  }
})(ChatAgentResult || (ChatAgentResult = {}));
var ChatAgentUserActionEvent;
(function(ChatAgentUserActionEvent2) {
  function to(result, event, commandsConverter) {
    if (event.action.kind === "vote") {
      return;
    }
    const ehResult = ChatAgentResult.to(result);
    if (event.action.kind === "command") {
      const command = event.action.commandButton.command;
      const commandButton = {
        command: commandsConverter.fromInternal(command) ?? { command: command.id, title: command.title }
      };
      const commandAction = { kind: "command", commandButton };
      return { action: commandAction, result: ehResult };
    } else if (event.action.kind === "followUp") {
      const followupAction = { kind: "followUp", followup: ChatFollowup.to(event.action.followup) };
      return { action: followupAction, result: ehResult };
    } else if (event.action.kind === "inlineChat") {
      return { action: { kind: "editor", accepted: event.action.action === "accepted" }, result: ehResult };
    } else if (event.action.kind === "chatEditingSessionAction") {
      const outcomes = /* @__PURE__ */ new Map([
        ["accepted", ChatEditingSessionActionOutcome.Accepted],
        ["rejected", ChatEditingSessionActionOutcome.Rejected],
        ["saved", ChatEditingSessionActionOutcome.Saved]
      ]);
      return {
        action: {
          kind: "chatEditingSessionAction",
          outcome: outcomes.get(event.action.outcome) ?? ChatEditingSessionActionOutcome.Rejected,
          uri: URI.revive(event.action.uri),
          hasRemainingEdits: event.action.hasRemainingEdits
        },
        result: ehResult
      };
    } else {
      return { action: event.action, result: ehResult };
    }
  }
  ChatAgentUserActionEvent2.to = to;
})(ChatAgentUserActionEvent || (ChatAgentUserActionEvent = {}));
var TerminalQuickFix;
(function(TerminalQuickFix2) {
  function from(quickFix, converter, disposables) {
    if ("terminalCommand" in quickFix) {
      return { terminalCommand: quickFix.terminalCommand, shouldExecute: quickFix.shouldExecute };
    }
    if ("uri" in quickFix) {
      return { uri: quickFix.uri };
    }
    return converter.toInternal(quickFix, disposables);
  }
  TerminalQuickFix2.from = from;
})(TerminalQuickFix || (TerminalQuickFix = {}));
var PartialAcceptInfo;
(function(PartialAcceptInfo2) {
  function to(info) {
    return {
      kind: PartialAcceptTriggerKind3.to(info.kind)
    };
  }
  PartialAcceptInfo2.to = to;
})(PartialAcceptInfo || (PartialAcceptInfo = {}));
var PartialAcceptTriggerKind3;
(function(PartialAcceptTriggerKind4) {
  function to(kind) {
    switch (kind) {
      case 0:
        return PartialAcceptTriggerKind2.Word;
      case 1:
        return PartialAcceptTriggerKind2.Line;
      case 2:
        return PartialAcceptTriggerKind2.Suggest;
      default:
        return PartialAcceptTriggerKind2.Unknown;
    }
  }
  PartialAcceptTriggerKind4.to = to;
})(PartialAcceptTriggerKind3 || (PartialAcceptTriggerKind3 = {}));
var DebugTreeItem;
(function(DebugTreeItem2) {
  function from(item, id2) {
    return {
      id: id2,
      label: item.label,
      description: item.description,
      canEdit: item.canEdit,
      collapsibleState: item.collapsibleState || 0,
      contextValue: item.contextValue
    };
  }
  DebugTreeItem2.from = from;
})(DebugTreeItem || (DebugTreeItem = {}));
var LanguageModelToolDescription;
(function(LanguageModelToolDescription2) {
  function to(item) {
    return {
      // Note- the reason this is a unique 'name' is just to avoid confusion with the toolCallId
      name: item.id,
      description: item.modelDescription,
      inputSchema: item.inputSchema,
      tags: item.tags ?? []
    };
  }
  LanguageModelToolDescription2.to = to;
})(LanguageModelToolDescription || (LanguageModelToolDescription = {}));
var LanguageModelToolResult;
(function(LanguageModelToolResult2) {
  function to(result) {
    return new $7V(result.content.map((item) => {
      if (item.kind === "text") {
        return new $1V(item.value);
      } else {
        return new $2V(item.value);
      }
    }));
  }
  LanguageModelToolResult2.to = to;
  function from(result) {
    return {
      content: result.content.map((item) => {
        if (item instanceof $1V) {
          return {
            kind: "text",
            value: item.value
          };
        } else if (item instanceof $2V) {
          return {
            kind: "promptTsx",
            value: item.value
          };
        } else {
          throw new Error("Unknown LanguageModelToolResult part type");
        }
      })
    };
  }
  LanguageModelToolResult2.from = from;
})(LanguageModelToolResult || (LanguageModelToolResult = {}));

// out-build/vs/workbench/services/search/common/searchExtTypes.js
var $JN = class _$JN {
  constructor(line, character) {
    this.line = line;
    this.character = character;
  }
  isBefore(other) {
    return false;
  }
  isBeforeOrEqual(other) {
    return false;
  }
  isAfter(other) {
    return false;
  }
  isAfterOrEqual(other) {
    return false;
  }
  isEqual(other) {
    return false;
  }
  compareTo(other) {
    return 0;
  }
  translate(_, _2) {
    return new _$JN(0, 0);
  }
  with(_) {
    return new _$JN(0, 0);
  }
};
var $KN = class _$KN {
  constructor(startLine, startCol, endLine, endCol) {
    this.isEmpty = false;
    this.isSingleLine = false;
    this.start = new $JN(startLine, startCol);
    this.end = new $JN(endLine, endCol);
  }
  contains(positionOrRange) {
    return false;
  }
  isEqual(other) {
    return false;
  }
  intersection(range) {
    return void 0;
  }
  union(other) {
    return new _$KN(0, 0, 0, 0);
  }
  with(_) {
    return new _$KN(0, 0, 0, 0);
  }
};
var $LN = class {
  /**
   * @param uri The uri for the matching document.
   * @param ranges The ranges associated with this match.
   * @param previewText The text that is used to preview the match. The highlighted range in `previewText` is specified in `ranges`.
   */
  constructor(uri, ranges, previewText) {
    this.uri = uri;
    this.ranges = ranges;
    this.previewText = previewText;
  }
};
var $MN = class {
  /**
   * @param uri The uri for the matching document.
   * @param text The line of context text.
   * @param lineNumber The line number of this line of context.
   */
  constructor(uri, text, lineNumber) {
    this.uri = uri;
    this.text = text;
    this.lineNumber = lineNumber;
  }
};
var ExcludeSettingOptions;
(function(ExcludeSettingOptions2) {
  ExcludeSettingOptions2[ExcludeSettingOptions2["None"] = 1] = "None";
  ExcludeSettingOptions2[ExcludeSettingOptions2["FilesExclude"] = 2] = "FilesExclude";
  ExcludeSettingOptions2[ExcludeSettingOptions2["SearchAndFilesExclude"] = 3] = "SearchAndFilesExclude";
})(ExcludeSettingOptions || (ExcludeSettingOptions = {}));
var TextSearchCompleteMessageType;
(function(TextSearchCompleteMessageType2) {
  TextSearchCompleteMessageType2[TextSearchCompleteMessageType2["Information"] = 1] = "Information";
  TextSearchCompleteMessageType2[TextSearchCompleteMessageType2["Warning"] = 2] = "Warning";
})(TextSearchCompleteMessageType || (TextSearchCompleteMessageType = {}));

// out-build/vs/workbench/services/search/common/search.js
var $SN = 2e4;
var SEARCH_ELIDED_PREFIX = "\u27EA ";
var SEARCH_ELIDED_SUFFIX = " characters skipped \u27EB";
var SEARCH_ELIDED_MIN_LEN = (SEARCH_ELIDED_PREFIX.length + SEARCH_ELIDED_SUFFIX.length + 5) * 2;
var $TN = $Qk("searchService");
var SearchProviderType;
(function(SearchProviderType2) {
  SearchProviderType2[SearchProviderType2["file"] = 0] = "file";
  SearchProviderType2[SearchProviderType2["text"] = 1] = "text";
  SearchProviderType2[SearchProviderType2["aiText"] = 2] = "aiText";
})(SearchProviderType || (SearchProviderType = {}));
var QueryType;
(function(QueryType2) {
  QueryType2[QueryType2["File"] = 1] = "File";
  QueryType2[QueryType2["Text"] = 2] = "Text";
  QueryType2[QueryType2["aiText"] = 3] = "aiText";
})(QueryType || (QueryType = {}));
function $UN(result) {
  return !!result.rangeLocations && !!result.previewText;
}
var SearchCompletionExitCode;
(function(SearchCompletionExitCode2) {
  SearchCompletionExitCode2[SearchCompletionExitCode2["Normal"] = 0] = "Normal";
  SearchCompletionExitCode2[SearchCompletionExitCode2["NewSearchStarted"] = 1] = "NewSearchStarted";
})(SearchCompletionExitCode || (SearchCompletionExitCode = {}));
var $YN = class {
  constructor(text, ranges, previewOptions, webviewIndex) {
    this.rangeLocations = [];
    this.webviewIndex = webviewIndex;
    const rangesArr = Array.isArray(ranges) ? ranges : [ranges];
    if (previewOptions && previewOptions.matchLines === 1 && isSingleLineRangeList(rangesArr)) {
      text = $sg(text, previewOptions.matchLines);
      let result = "";
      let shift = 0;
      let lastEnd = 0;
      const leadingChars = Math.floor(previewOptions.charsPerLine / 5);
      for (const range of rangesArr) {
        const previewStart = Math.max(range.startColumn - leadingChars, 0);
        const previewEnd = range.startColumn + previewOptions.charsPerLine;
        if (previewStart > lastEnd + leadingChars + SEARCH_ELIDED_MIN_LEN) {
          const elision = SEARCH_ELIDED_PREFIX + (previewStart - lastEnd) + SEARCH_ELIDED_SUFFIX;
          result += elision + text.slice(previewStart, previewEnd);
          shift += previewStart - (lastEnd + elision.length);
        } else {
          result += text.slice(lastEnd, previewEnd);
        }
        lastEnd = previewEnd;
        this.rangeLocations.push({
          source: range,
          preview: new $1N(0, range.startColumn - shift, range.endColumn - shift)
        });
      }
      this.previewText = result;
    } else {
      const firstMatchLine = Array.isArray(ranges) ? ranges[0].startLineNumber : ranges.startLineNumber;
      const rangeLocs = $4b(ranges, (r) => ({
        preview: new $ZN(r.startLineNumber - firstMatchLine, r.startColumn, r.endLineNumber - firstMatchLine, r.endColumn),
        source: r
      }));
      this.rangeLocations = Array.isArray(rangeLocs) ? rangeLocs : [rangeLocs];
      this.previewText = text;
    }
  }
};
function isSingleLineRangeList(ranges) {
  const line = ranges[0].startLineNumber;
  for (const r of ranges) {
    if (r.startLineNumber !== line || r.endLineNumber !== line) {
      return false;
    }
  }
  return true;
}
var $ZN = class {
  constructor(startLineNumber, startColumn, endLineNumber, endColumn) {
    this.startLineNumber = startLineNumber;
    this.startColumn = startColumn;
    this.endLineNumber = endLineNumber;
    this.endColumn = endColumn;
  }
};
var $1N = class extends $ZN {
  constructor(lineNumber, startColumn, endColumn) {
    super(lineNumber, startColumn, lineNumber, endColumn);
  }
};
var ViewMode;
(function(ViewMode2) {
  ViewMode2["List"] = "list";
  ViewMode2["Tree"] = "tree";
})(ViewMode || (ViewMode = {}));
var SearchSortOrder;
(function(SearchSortOrder2) {
  SearchSortOrder2["Default"] = "default";
  SearchSortOrder2["FileNames"] = "fileNames";
  SearchSortOrder2["Type"] = "type";
  SearchSortOrder2["Modified"] = "modified";
  SearchSortOrder2["CountDescending"] = "countDescending";
  SearchSortOrder2["CountAscending"] = "countAscending";
})(SearchSortOrder || (SearchSortOrder = {}));
function $2N(configuration, includeSearchExcludes = true) {
  const fileExcludes = configuration && configuration.files && configuration.files.exclude;
  const searchExcludes = includeSearchExcludes && configuration && configuration.search && configuration.search.exclude;
  if (!fileExcludes && !searchExcludes) {
    return void 0;
  }
  if (!fileExcludes || !searchExcludes) {
    return fileExcludes || searchExcludes || void 0;
  }
  let allExcludes = /* @__PURE__ */ Object.create(null);
  allExcludes = $Ov(allExcludes, $Lv(fileExcludes));
  allExcludes = $Ov(allExcludes, $Lv(searchExcludes), true);
  return allExcludes;
}
function $3N(queryProps, fsPath) {
  if (queryProps.excludePattern && $Cl(queryProps.excludePattern, fsPath)) {
    return false;
  }
  if (queryProps.includePattern || queryProps.usingSearchPaths) {
    if (queryProps.includePattern && $Cl(queryProps.includePattern, fsPath)) {
      return true;
    }
    if (queryProps.usingSearchPaths) {
      return !!queryProps.folderQueries && queryProps.folderQueries.some((fq) => {
        const searchPath = fq.folder.fsPath;
        if ($Zg(fsPath, searchPath)) {
          const relPath = $pc(searchPath, fsPath);
          return !fq.includePattern || !!$Cl(fq.includePattern, relPath);
        } else {
          return false;
        }
      });
    }
    return false;
  }
  return true;
}
var SearchErrorCode;
(function(SearchErrorCode2) {
  SearchErrorCode2[SearchErrorCode2["unknownEncoding"] = 1] = "unknownEncoding";
  SearchErrorCode2[SearchErrorCode2["regexParseError"] = 2] = "regexParseError";
  SearchErrorCode2[SearchErrorCode2["globParseError"] = 3] = "globParseError";
  SearchErrorCode2[SearchErrorCode2["invalidLiteral"] = 4] = "invalidLiteral";
  SearchErrorCode2[SearchErrorCode2["rgProcessError"] = 5] = "rgProcessError";
  SearchErrorCode2[SearchErrorCode2["other"] = 6] = "other";
  SearchErrorCode2[SearchErrorCode2["canceled"] = 7] = "canceled";
})(SearchErrorCode || (SearchErrorCode = {}));
var $4N = class extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
};
function $6N(searchError) {
  const details = { message: searchError.message, code: searchError.code };
  return new Error(JSON.stringify(details));
}
function $9N(arg) {
  return !!arg.path;
}
function $0N(candidate, filePatternToUse, fuzzy = true) {
  const pathToMatch = candidate.searchPath ? candidate.searchPath : candidate.relativePath;
  return fuzzy ? $pg(pathToMatch, filePatternToUse) : $Cl(filePatternToUse, pathToMatch);
}
function $_N(globalPattern, folderPattern) {
  const merged = {
    ...globalPattern || {},
    ...folderPattern || {}
  };
  return Object.keys(merged).filter((key) => {
    const value = merged[key];
    return typeof value === "boolean" && value;
  });
}
var $aO = class {
  constructor(config, folderQuery) {
    this.c = null;
    this.a = folderQuery.excludePattern?.map((excludePattern) => {
      return {
        ...config.excludePattern || {},
        ...excludePattern.pattern || {}
      };
    }) ?? [];
    if (this.a.length === 0) {
      this.a = [config.excludePattern || {}];
    }
    this.b = this.a.map((e) => $Dl(e));
    let includeExpression = config.includePattern;
    if (folderQuery.includePattern) {
      if (includeExpression) {
        includeExpression = {
          ...includeExpression,
          ...folderQuery.includePattern
        };
      } else {
        includeExpression = folderQuery.includePattern;
      }
    }
    if (includeExpression) {
      this.c = $Dl(includeExpression);
    }
  }
  d(testPath, basename, hasSibling) {
    let result = null;
    for (const folderExclude of this.b) {
      const evaluation = folderExclude(testPath, basename, hasSibling);
      if (typeof evaluation === "string") {
        result = evaluation;
        break;
      }
    }
    return result;
  }
  matchesExcludesSync(testPath, basename, hasSibling) {
    if (this.b && this.d(testPath, basename, hasSibling)) {
      return true;
    }
    return false;
  }
  /**
   * Guaranteed sync - siblingsFn should not return a promise.
   */
  includedInQuerySync(testPath, basename, hasSibling) {
    if (this.b && this.d(testPath, basename, hasSibling)) {
      return false;
    }
    if (this.c && !this.c(testPath, basename, hasSibling)) {
      return false;
    }
    return true;
  }
  /**
   * Evaluating the exclude expression is only async if it includes sibling clauses. As an optimization, avoid doing anything with Promises
   * unless the expression is async.
   */
  includedInQuery(testPath, basename, hasSibling) {
    const isIncluded = () => {
      return this.c ? !!this.c(testPath, basename, hasSibling) : true;
    };
    return Promise.all(this.b.map((e) => {
      const excluded = e(testPath, basename, hasSibling);
      if ($Gh(excluded)) {
        return excluded.then((excluded2) => {
          if (excluded2) {
            return false;
          }
          return isIncluded();
        });
      }
      return isIncluded();
    })).then((e) => e.some((e2) => !!e2));
  }
  hasSiblingExcludeClauses() {
    return this.a.reduce((prev, curr) => hasSiblingClauses(curr) || prev, false);
  }
};
function hasSiblingClauses(pattern) {
  for (const key in pattern) {
    if (typeof pattern[key] !== "boolean") {
      return true;
    }
  }
  return false;
}
function $bO(siblingsFn) {
  if (!siblingsFn) {
    return void 0;
  }
  let siblings;
  return (name) => {
    if (!siblings) {
      siblings = (siblingsFn() || Promise.resolve([])).then((list2) => list2 ? listToMap(list2) : {});
    }
    return siblings.then((map) => !!map[name]);
  };
}
function $cO(siblingsFn) {
  if (!siblingsFn) {
    return void 0;
  }
  let siblings;
  return (name) => {
    if (!siblings) {
      const list2 = siblingsFn();
      siblings = list2 ? listToMap(list2) : {};
    }
    return !!siblings[name];
  };
}
function listToMap(list2) {
  const map = {};
  for (const key of list2) {
    map[key] = true;
  }
  return map;
}
function $dO(excludesForFolder) {
  return excludesForFolder.flatMap((exclude) => exclude.patterns.map((pattern) => {
    return exclude.baseUri ? {
      baseUri: exclude.baseUri,
      pattern
    } : pattern;
  }));
}
var $eO = {
  matchLines: 100,
  charsPerLine: 1e4
};

// out-build/vs/workbench/api/common/extHostWorkspace.js
function isFolderEqual(folderA, folderB, extHostFileSystemInfo) {
  return new $kh((uri) => ignorePathCasing(uri, extHostFileSystemInfo)).isEqual(folderA, folderB);
}
function compareWorkspaceFolderByUri(a, b, extHostFileSystemInfo) {
  return isFolderEqual(a.uri, b.uri, extHostFileSystemInfo) ? 0 : $Tf(a.uri.toString(), b.uri.toString());
}
function compareWorkspaceFolderByUriAndNameAndIndex(a, b, extHostFileSystemInfo) {
  if (a.index !== b.index) {
    return a.index < b.index ? -1 : 1;
  }
  return isFolderEqual(a.uri, b.uri, extHostFileSystemInfo) ? $Tf(a.name, b.name) : $Tf(a.uri.toString(), b.uri.toString());
}
function delta(oldFolders, newFolders, compare3, extHostFileSystemInfo) {
  const oldSortedFolders = oldFolders.slice(0).sort((a, b) => compare3(a, b, extHostFileSystemInfo));
  const newSortedFolders = newFolders.slice(0).sort((a, b) => compare3(a, b, extHostFileSystemInfo));
  return $Jb(oldSortedFolders, newSortedFolders, (a, b) => compare3(a, b, extHostFileSystemInfo));
}
function ignorePathCasing(uri, extHostFileSystemInfo) {
  const capabilities = extHostFileSystemInfo.getCapabilities(uri.scheme);
  return !(capabilities && capabilities & 1024);
}
var ExtHostWorkspaceImpl = class _ExtHostWorkspaceImpl extends $0k {
  static toExtHostWorkspace(data, previousConfirmedWorkspace, previousUnconfirmedWorkspace, extHostFileSystemInfo) {
    if (!data) {
      return { workspace: null, added: [], removed: [] };
    }
    const { id: id2, name, folders, configuration, transient, isUntitled } = data;
    const newWorkspaceFolders = [];
    const oldWorkspace = previousConfirmedWorkspace;
    if (previousConfirmedWorkspace) {
      folders.forEach((folderData, index) => {
        const folderUri = URI.revive(folderData.uri);
        const existingFolder = _ExtHostWorkspaceImpl.o(previousUnconfirmedWorkspace || previousConfirmedWorkspace, folderUri, extHostFileSystemInfo);
        if (existingFolder) {
          existingFolder.name = folderData.name;
          existingFolder.index = folderData.index;
          newWorkspaceFolders.push(existingFolder);
        } else {
          newWorkspaceFolders.push({ uri: folderUri, name: folderData.name, index });
        }
      });
    } else {
      newWorkspaceFolders.push(...folders.map(({ uri, name: name2, index }) => ({ uri: URI.revive(uri), name: name2, index })));
    }
    newWorkspaceFolders.sort((f1, f2) => f1.index < f2.index ? -1 : 1);
    const workspace = new _ExtHostWorkspaceImpl(id2, name, newWorkspaceFolders, !!transient, configuration ? URI.revive(configuration) : null, !!isUntitled, (uri) => ignorePathCasing(uri, extHostFileSystemInfo));
    const { added, removed } = delta(oldWorkspace ? oldWorkspace.workspaceFolders : [], workspace.workspaceFolders, compareWorkspaceFolderByUri, extHostFileSystemInfo);
    return { workspace, added, removed };
  }
  static o(workspace, folderUriToFind, extHostFileSystemInfo) {
    for (let i = 0; i < workspace.folders.length; i++) {
      const folder = workspace.workspaceFolders[i];
      if (isFolderEqual(folder.uri, folderUriToFind, extHostFileSystemInfo)) {
        return folder;
      }
    }
    return void 0;
  }
  constructor(id2, t, folders, transient, configuration, u, ignorePathCasing2) {
    super(id2, folders.map((f) => new $$k(f)), transient, configuration, ignorePathCasing2);
    this.t = t;
    this.u = u;
    this.q = [];
    this.s = $Wk.forUris(ignorePathCasing2, () => true);
    folders.forEach((folder) => {
      this.q.push(folder);
      this.s.set(folder.uri, folder);
    });
  }
  get name() {
    return this.t;
  }
  get isUntitled() {
    return this.u;
  }
  get workspaceFolders() {
    return this.q.slice(0);
  }
  getWorkspaceFolder(uri, resolveParent) {
    if (resolveParent && this.s.get(uri)) {
      uri = $uh(uri);
    }
    return this.s.findSubstr(uri);
  }
  resolveWorkspaceFolder(uri) {
    return this.s.get(uri);
  }
};
var $9wc = class $9wc2 {
  constructor(extHostRpc, initData, extHostFileSystemInfo, logService, uriTransformerService) {
    this.c = new $ze();
    this.onDidChangeWorkspace = this.c.event;
    this.g = new $ze();
    this.onDidGrantWorkspaceTrust = this.g.event;
    this.u = [];
    this.v = false;
    this.w = /* @__PURE__ */ new Map();
    this.B = 0;
    this.C = new $Be();
    this.D = /* @__PURE__ */ new Map();
    this.h = logService;
    this.s = extHostFileSystemInfo;
    this.t = uriTransformerService;
    this.j = new $6i();
    this.k = new $Uh();
    this.o = extHostRpc.getProxy($xT.MainThreadWorkspace);
    this.q = extHostRpc.getProxy($xT.MainThreadMessageService);
    const data = initData.workspace;
    this.l = data ? new ExtHostWorkspaceImpl(data.id, data.name, [], !!data.transient, data.configuration ? URI.revive(data.configuration) : null, !!data.isUntitled, (uri) => ignorePathCasing(uri, extHostFileSystemInfo)) : void 0;
  }
  $initializeWorkspace(data, trusted) {
    this.v = trusted;
    this.$acceptWorkspaceData(data);
    this.k.open();
  }
  waitForInitializeCall() {
    return this.k.wait();
  }
  // --- workspace ---
  get workspace() {
    return this.x;
  }
  get name() {
    return this.x ? this.x.name : void 0;
  }
  get workspaceFile() {
    if (this.x) {
      if (this.x.configuration) {
        if (this.x.isUntitled) {
          return URI.from({ scheme: Schemas.untitled, path: $sh($uh(this.x.configuration)) });
        }
        return this.x.configuration;
      }
    }
    return void 0;
  }
  get x() {
    return this.n || this.l;
  }
  getWorkspaceFolders() {
    if (!this.x) {
      return void 0;
    }
    return this.x.workspaceFolders.slice(0);
  }
  async getWorkspaceFolders2() {
    await this.k.wait();
    if (!this.x) {
      return void 0;
    }
    return this.x.workspaceFolders.slice(0);
  }
  updateWorkspaceFolders(extension, index, deleteCount, ...workspaceFoldersToAdd) {
    const validatedDistinctWorkspaceFoldersToAdd = [];
    if (Array.isArray(workspaceFoldersToAdd)) {
      workspaceFoldersToAdd.forEach((folderToAdd) => {
        if (URI.isUri(folderToAdd.uri) && !validatedDistinctWorkspaceFoldersToAdd.some((f) => isFolderEqual(f.uri, folderToAdd.uri, this.s))) {
          validatedDistinctWorkspaceFoldersToAdd.push({ uri: folderToAdd.uri, name: folderToAdd.name || $rh(folderToAdd.uri) });
        }
      });
    }
    if (!!this.n) {
      return false;
    }
    if ([index, deleteCount].some((i) => typeof i !== "number" || i < 0)) {
      return false;
    }
    if (deleteCount === 0 && validatedDistinctWorkspaceFoldersToAdd.length === 0) {
      return false;
    }
    const currentWorkspaceFolders = this.x ? this.x.workspaceFolders : [];
    if (index + deleteCount > currentWorkspaceFolders.length) {
      return false;
    }
    const newWorkspaceFolders = currentWorkspaceFolders.slice(0);
    newWorkspaceFolders.splice(index, deleteCount, ...validatedDistinctWorkspaceFoldersToAdd.map((f) => ({
      uri: f.uri,
      name: f.name || $rh(f.uri),
      index: void 0
      /* fixed later */
    })));
    for (let i = 0; i < newWorkspaceFolders.length; i++) {
      const folder = newWorkspaceFolders[i];
      if (newWorkspaceFolders.some((otherFolder, index2) => index2 !== i && isFolderEqual(folder.uri, otherFolder.uri, this.s))) {
        return false;
      }
    }
    newWorkspaceFolders.forEach((f, index2) => f.index = index2);
    const { added, removed } = delta(currentWorkspaceFolders, newWorkspaceFolders, compareWorkspaceFolderByUriAndNameAndIndex, this.s);
    if (added.length === 0 && removed.length === 0) {
      return false;
    }
    if (this.o) {
      const extName = extension.displayName || extension.name;
      this.o.$updateWorkspaceFolders(extName, index, deleteCount, validatedDistinctWorkspaceFoldersToAdd).then(void 0, (error) => {
        this.n = void 0;
        const options2 = { source: { identifier: extension.identifier, label: extension.displayName || extension.name } };
        this.q.$showMessage(Severity2.Error, localize(2772, null, extName, error.toString()), options2, []);
      });
    }
    this.y(newWorkspaceFolders);
    return true;
  }
  getWorkspaceFolder(uri, resolveParent) {
    if (!this.x) {
      return void 0;
    }
    return this.x.getWorkspaceFolder(uri, resolveParent);
  }
  async getWorkspaceFolder2(uri, resolveParent) {
    await this.k.wait();
    if (!this.x) {
      return void 0;
    }
    return this.x.getWorkspaceFolder(uri, resolveParent);
  }
  async resolveWorkspaceFolder(uri) {
    await this.k.wait();
    if (!this.x) {
      return void 0;
    }
    return this.x.resolveWorkspaceFolder(uri);
  }
  getPath() {
    if (!this.x) {
      return void 0;
    }
    const { folders } = this.x;
    if (folders.length === 0) {
      return void 0;
    }
    return folders[0].uri.fsPath;
  }
  getRelativePath(pathOrUri, includeWorkspace) {
    let resource;
    let path = "";
    if (typeof pathOrUri === "string") {
      resource = URI.file(pathOrUri);
      path = pathOrUri;
    } else if (typeof pathOrUri !== "undefined") {
      resource = pathOrUri;
      path = pathOrUri.fsPath;
    }
    if (!resource) {
      return path;
    }
    const folder = this.getWorkspaceFolder(resource, true);
    if (!folder) {
      return path;
    }
    if (typeof includeWorkspace === "undefined" && this.x) {
      includeWorkspace = this.x.folders.length > 1;
    }
    let result = $xh(folder.uri, resource);
    if (includeWorkspace && folder.name) {
      result = `${folder.name}/${result}`;
    }
    return result;
  }
  y(folders) {
    if (this.x) {
      this.n = ExtHostWorkspaceImpl.toExtHostWorkspace({
        id: this.x.id,
        name: this.x.name,
        configuration: this.x.configuration,
        folders,
        isUntitled: this.x.isUntitled
      }, this.x, void 0, this.s).workspace || void 0;
    }
  }
  $acceptWorkspaceData(data) {
    const { workspace, added, removed } = ExtHostWorkspaceImpl.toExtHostWorkspace(data, this.l, this.n, this.s);
    this.l = workspace || void 0;
    this.n = void 0;
    this.c.fire(Object.freeze({
      added,
      removed
    }));
  }
  // --- search ---
  /**
   * Note, null/undefined have different and important meanings for "exclude"
   */
  findFiles(include, exclude, maxResults, extensionId, token = CancellationToken.None) {
    this.h.trace(`extHostWorkspace#findFiles: fileSearch, extension: ${extensionId.value}, entryPoint: findFiles`);
    let excludeString = "";
    let useFileExcludes = true;
    if (exclude === null) {
      useFileExcludes = false;
    } else if (exclude !== void 0) {
      if (typeof exclude === "string") {
        excludeString = exclude;
      } else {
        excludeString = exclude.pattern;
      }
    }
    return this.z(include, void 0, {
      exclude: [excludeString],
      maxResults,
      useExcludeSettings: useFileExcludes ? ExcludeSettingOptions.FilesExclude : ExcludeSettingOptions.None,
      useIgnoreFiles: {
        local: false
      }
    }, token);
  }
  findFiles2(filePatterns, options2 = {}, extensionId, token = CancellationToken.None) {
    this.h.trace(`extHostWorkspace#findFiles2New: fileSearch, extension: ${extensionId.value}, entryPoint: findFiles2New`);
    return this.z(void 0, filePatterns, options2, token);
  }
  async z(include, filePatterns, options2, token = CancellationToken.None) {
    if (token && token.isCancellationRequested) {
      return Promise.resolve([]);
    }
    const filePatternsToUse = include !== void 0 ? [include] : filePatterns;
    const queryOptions = filePatternsToUse?.map((filePattern) => {
      const excludePatterns = globsToISearchPatternBuilder(options2.exclude);
      const fileQueries = {
        ignoreSymlinks: typeof options2.followSymlinks === "boolean" ? !options2.followSymlinks : void 0,
        disregardIgnoreFiles: typeof options2.useIgnoreFiles?.local === "boolean" ? !options2.useIgnoreFiles.local : void 0,
        disregardGlobalIgnoreFiles: typeof options2.useIgnoreFiles?.global === "boolean" ? !options2.useIgnoreFiles.global : void 0,
        disregardParentIgnoreFiles: typeof options2.useIgnoreFiles?.parent === "boolean" ? !options2.useIgnoreFiles.parent : void 0,
        disregardExcludeSettings: options2.useExcludeSettings !== void 0 && options2.useExcludeSettings === ExcludeSettingOptions.None,
        disregardSearchExcludeSettings: options2.useExcludeSettings !== void 0 && options2.useExcludeSettings !== ExcludeSettingOptions.SearchAndFilesExclude,
        maxResults: options2.maxResults,
        excludePattern: excludePatterns.length > 0 ? excludePatterns : void 0,
        _reason: "startFileSearch",
        shouldGlobSearch: include ? void 0 : true
      };
      const parseInclude = parseSearchExcludeInclude(GlobPattern.from(filePattern));
      const folderToUse = parseInclude?.folder;
      if (include) {
        fileQueries.includePattern = parseInclude?.pattern;
      } else {
        fileQueries.filePattern = parseInclude?.pattern;
      }
      return {
        folder: folderToUse,
        options: fileQueries
      };
    }) ?? [];
    return this.A(queryOptions, token);
  }
  async A(queryOptions, token) {
    const result = await Promise.all(queryOptions?.map((option) => this.o.$startFileSearch(option.folder ?? null, option.options, token).then((data) => Array.isArray(data) ? data.map((d) => URI.revive(d)) : [])) ?? []);
    return result.flat();
  }
  findTextInFiles2(query, options2, extensionId, token = CancellationToken.None) {
    this.h.trace(`extHostWorkspace#findTextInFiles2: textSearch, extension: ${extensionId.value}, entryPoint: findTextInFiles2`);
    const getOptions = (include) => {
      if (!options2) {
        return {
          folder: void 0,
          options: {}
        };
      }
      const parsedInclude = include ? parseSearchExcludeInclude(GlobPattern.from(include)) : void 0;
      const excludePatterns = options2.exclude ? globsToISearchPatternBuilder(options2.exclude) : void 0;
      return {
        options: {
          ignoreSymlinks: typeof options2.followSymlinks === "boolean" ? !options2.followSymlinks : void 0,
          disregardIgnoreFiles: typeof options2.useIgnoreFiles === "boolean" ? !options2.useIgnoreFiles : void 0,
          disregardGlobalIgnoreFiles: typeof options2.useIgnoreFiles?.global === "boolean" ? !options2.useIgnoreFiles?.global : void 0,
          disregardParentIgnoreFiles: typeof options2.useIgnoreFiles?.parent === "boolean" ? !options2.useIgnoreFiles?.parent : void 0,
          disregardExcludeSettings: options2.useExcludeSettings !== void 0 && options2.useExcludeSettings === ExcludeSettingOptions.None,
          disregardSearchExcludeSettings: options2.useExcludeSettings !== void 0 && options2.useExcludeSettings !== ExcludeSettingOptions.SearchAndFilesExclude,
          fileEncoding: options2.encoding,
          maxResults: options2.maxResults,
          previewOptions: options2.previewOptions ? {
            matchLines: options2.previewOptions?.numMatchLines ?? 100,
            charsPerLine: options2.previewOptions?.charsPerLine ?? 1e4
          } : void 0,
          surroundingContext: options2.surroundingContext,
          includePattern: parsedInclude?.pattern,
          excludePattern: excludePatterns
        },
        folder: parsedInclude?.folder
      };
    };
    const queryOptionsRaw = options2?.include?.map((include) => getOptions(include)) ?? [getOptions(void 0)];
    const queryOptions = queryOptionsRaw.filter((queryOps) => !!queryOps);
    const disposables = new $2c();
    const progressEmitter = disposables.add(new $ze());
    const complete = this.findTextInFilesBase(query, queryOptions, (result, uri) => progressEmitter.fire({ result, uri }), token);
    const asyncIterable = new $ji(async (emitter) => {
      disposables.add(progressEmitter.event((e) => {
        const result = e.result;
        const uri = e.uri;
        if ($UN(result)) {
          emitter.emitOne(new $LN(uri, result.rangeLocations.map((range) => ({
            previewRange: new $BT(range.preview.startLineNumber, range.preview.startColumn, range.preview.endLineNumber, range.preview.endColumn),
            sourceRange: new $BT(range.source.startLineNumber, range.source.startColumn, range.source.endLineNumber, range.source.endColumn)
          })), result.previewText));
        } else {
          emitter.emitOne(new $MN(uri, result.text, result.lineNumber));
        }
      }));
      await complete;
    });
    return {
      results: asyncIterable,
      complete: complete.then((e) => {
        disposables.dispose();
        return {
          limitHit: e?.limitHit ?? false
        };
      })
    };
  }
  async findTextInFilesBase(query, queryOptions, callback, token = CancellationToken.None) {
    const requestId = this.j.getNext();
    let isCanceled = false;
    token.onCancellationRequested((_) => {
      isCanceled = true;
    });
    this.u[requestId] = (p) => {
      if (isCanceled) {
        return;
      }
      const uri = URI.revive(p.resource);
      p.results.forEach((rawResult) => {
        const result = $cu(rawResult);
        callback(result, uri);
      });
    };
    if (token.isCancellationRequested) {
      return {};
    }
    try {
      const result = await Promise.all(queryOptions?.map((option) => this.o.$startTextSearch(query, option.folder ?? null, option.options, requestId, token) || {}) ?? []);
      delete this.u[requestId];
      return result.reduce((acc, val) => {
        return {
          limitHit: acc?.limitHit || (val?.limitHit ?? false),
          message: [acc?.message ?? [], val?.message ?? []].flat()
        };
      }, {}) ?? { limitHit: false };
    } catch (err) {
      delete this.u[requestId];
      throw err;
    }
  }
  async findTextInFiles(query, options2, callback, extensionId, token = CancellationToken.None) {
    this.h.trace(`extHostWorkspace#findTextInFiles: textSearch, extension: ${extensionId.value}, entryPoint: findTextInFiles`);
    const previewOptions = typeof options2.previewOptions === "undefined" ? {
      matchLines: 100,
      charsPerLine: 1e4
    } : options2.previewOptions;
    const parsedInclude = parseSearchExcludeInclude(GlobPattern.from(options2.include));
    const excludePattern = typeof options2.exclude === "string" ? options2.exclude : options2.exclude ? options2.exclude.pattern : void 0;
    const queryOptions = {
      ignoreSymlinks: typeof options2.followSymlinks === "boolean" ? !options2.followSymlinks : void 0,
      disregardIgnoreFiles: typeof options2.useIgnoreFiles === "boolean" ? !options2.useIgnoreFiles : void 0,
      disregardGlobalIgnoreFiles: typeof options2.useGlobalIgnoreFiles === "boolean" ? !options2.useGlobalIgnoreFiles : void 0,
      disregardParentIgnoreFiles: typeof options2.useParentIgnoreFiles === "boolean" ? !options2.useParentIgnoreFiles : void 0,
      disregardExcludeSettings: typeof options2.useDefaultExcludes === "boolean" ? !options2.useDefaultExcludes : true,
      disregardSearchExcludeSettings: typeof options2.useSearchExclude === "boolean" ? !options2.useSearchExclude : true,
      fileEncoding: options2.encoding,
      maxResults: options2.maxResults,
      previewOptions,
      surroundingContext: options2.afterContext,
      // TODO: remove ability to have before/after context separately
      includePattern: parsedInclude?.pattern,
      excludePattern: excludePattern ? [{ pattern: excludePattern }] : void 0
    };
    const progress = (result, uri) => {
      if ($UN(result)) {
        callback({
          uri,
          preview: {
            text: result.previewText,
            matches: $4b(result.rangeLocations, (m) => new $BT(m.preview.startLineNumber, m.preview.startColumn, m.preview.endLineNumber, m.preview.endColumn))
          },
          ranges: $4b(result.rangeLocations, (r) => new $BT(r.source.startLineNumber, r.source.startColumn, r.source.endLineNumber, r.source.endColumn))
        });
      } else {
        callback({
          uri,
          text: result.text,
          lineNumber: result.lineNumber
        });
      }
    };
    return this.findTextInFilesBase(query, [{ options: queryOptions, folder: parsedInclude?.folder }], progress, token);
  }
  $handleTextSearchResult(result, requestId) {
    this.u[requestId]?.(result);
  }
  async save(uri) {
    const result = await this.o.$save(uri, { saveAs: false });
    return URI.revive(result);
  }
  async saveAs(uri) {
    const result = await this.o.$save(uri, { saveAs: true });
    return URI.revive(result);
  }
  saveAll(includeUntitled) {
    return this.o.$saveAll(includeUntitled);
  }
  resolveProxy(url) {
    return this.o.$resolveProxy(url);
  }
  lookupAuthorization(authInfo) {
    return this.o.$lookupAuthorization(authInfo);
  }
  lookupKerberosAuthorization(url) {
    return this.o.$lookupKerberosAuthorization(url);
  }
  loadCertificates() {
    return this.o.$loadCertificates();
  }
  // --- trust ---
  get trusted() {
    return this.v;
  }
  requestWorkspaceTrust(options2) {
    return this.o.$requestWorkspaceTrust(options2);
  }
  $onDidGrantWorkspaceTrust() {
    if (!this.v) {
      this.v = true;
      this.g.fire();
    }
  }
  // called by ext host
  registerEditSessionIdentityProvider(scheme, provider) {
    if (this.w.has(scheme)) {
      throw new Error(`A provider has already been registered for scheme ${scheme}`);
    }
    this.w.set(scheme, provider);
    const outgoingScheme = this.t.transformOutgoingScheme(scheme);
    const handle = this.B++;
    this.o.$registerEditSessionIdentityProvider(handle, outgoingScheme);
    return $1c(() => {
      this.w.delete(scheme);
      this.o.$unregisterEditSessionIdentityProvider(handle);
    });
  }
  // called by main thread
  async $getEditSessionIdentifier(workspaceFolder, cancellationToken) {
    this.h.info("Getting edit session identifier for workspaceFolder", workspaceFolder);
    const folder = await this.resolveWorkspaceFolder(URI.revive(workspaceFolder));
    if (!folder) {
      this.h.warn("Unable to resolve workspace folder");
      return void 0;
    }
    this.h.info("Invoking #provideEditSessionIdentity for workspaceFolder", folder);
    const provider = this.w.get(folder.uri.scheme);
    this.h.info(`Provider for scheme ${folder.uri.scheme} is defined: `, !!provider);
    if (!provider) {
      return void 0;
    }
    const result = await provider.provideEditSessionIdentity(folder, cancellationToken);
    this.h.info("Provider returned edit session identifier: ", result);
    if (!result) {
      return void 0;
    }
    return result;
  }
  async $provideEditSessionIdentityMatch(workspaceFolder, identity1, identity2, cancellationToken) {
    this.h.info("Getting edit session identifier for workspaceFolder", workspaceFolder);
    const folder = await this.resolveWorkspaceFolder(URI.revive(workspaceFolder));
    if (!folder) {
      this.h.warn("Unable to resolve workspace folder");
      return void 0;
    }
    this.h.info("Invoking #provideEditSessionIdentity for workspaceFolder", folder);
    const provider = this.w.get(folder.uri.scheme);
    this.h.info(`Provider for scheme ${folder.uri.scheme} is defined: `, !!provider);
    if (!provider) {
      return void 0;
    }
    const result = await provider.provideEditSessionIdentityMatch?.(identity1, identity2, cancellationToken);
    this.h.info("Provider returned edit session identifier match result: ", result);
    if (!result) {
      return void 0;
    }
    return result;
  }
  getOnWillCreateEditSessionIdentityEvent(extension) {
    return (listener, thisArg, disposables) => {
      const wrappedListener = function wrapped(e) {
        listener.call(thisArg, e);
      };
      wrappedListener.extension = extension;
      return this.C.event(wrappedListener, void 0, disposables);
    };
  }
  // main thread calls this to trigger participants
  async $onWillCreateEditSessionIdentity(workspaceFolder, token, timeout) {
    const folder = await this.resolveWorkspaceFolder(URI.revive(workspaceFolder));
    if (folder === void 0) {
      throw new Error("Unable to resolve workspace folder");
    }
    await this.C.fireAsync({ workspaceFolder: folder }, token, async (thenable, listener) => {
      const now = Date.now();
      await Promise.resolve(thenable);
      if (Date.now() - now > timeout) {
        this.h.warn("SLOW edit session create-participant", listener.extension.identifier);
      }
    });
    if (token.isCancellationRequested) {
      return void 0;
    }
  }
  // called by ext host
  registerCanonicalUriProvider(scheme, provider) {
    if (this.D.has(scheme)) {
      throw new Error(`A provider has already been registered for scheme ${scheme}`);
    }
    this.D.set(scheme, provider);
    const outgoingScheme = this.t.transformOutgoingScheme(scheme);
    const handle = this.B++;
    this.o.$registerCanonicalUriProvider(handle, outgoingScheme);
    return $1c(() => {
      this.D.delete(scheme);
      this.o.$unregisterCanonicalUriProvider(handle);
    });
  }
  async provideCanonicalUri(uri, options2, cancellationToken) {
    const provider = this.D.get(uri.scheme);
    if (!provider) {
      return void 0;
    }
    const result = await provider.provideCanonicalUri?.(URI.revive(uri), options2, cancellationToken);
    if (!result) {
      return void 0;
    }
    return result;
  }
  // called by main thread
  async $provideCanonicalUri(uri, targetScheme, cancellationToken) {
    return this.provideCanonicalUri(URI.revive(uri), { targetScheme }, cancellationToken);
  }
};
$9wc = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $Pwc),
  __param(3, $wn),
  __param(4, $7wc)
], $9wc);
var $0wc = $Qk("IExtHostWorkspace");
function parseSearchExcludeInclude(include) {
  let pattern;
  let includeFolder;
  if (include) {
    if (typeof include === "string") {
      pattern = include;
    } else {
      pattern = include.pattern;
      includeFolder = URI.revive(include.baseUri);
    }
    return {
      pattern,
      folder: includeFolder
    };
  }
  return void 0;
}
function globsToISearchPatternBuilder(excludes) {
  return (excludes?.map((exclude) => {
    if (typeof exclude === "string") {
      if (exclude === "") {
        return void 0;
      }
      return {
        pattern: exclude,
        uri: void 0
      };
    } else {
      const parsedExclude = parseSearchExcludeInclude(exclude);
      if (!parsedExclude) {
        return void 0;
      }
      return {
        pattern: parsedExclude.pattern,
        uri: parsedExclude.folder
      };
    }
  }) ?? []).filter((e) => !!e);
}

// out-build/vs/base/common/json.js
var ScanError;
(function(ScanError2) {
  ScanError2[ScanError2["None"] = 0] = "None";
  ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
  ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
  ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
  ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
  ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
  ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
})(ScanError || (ScanError = {}));
var SyntaxKind;
(function(SyntaxKind2) {
  SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
  SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
  SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
  SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
  SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
  SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
  SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
  SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
  SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
  SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
  SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
  SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
  SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
  SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
  SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
  SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
  SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
})(SyntaxKind || (SyntaxKind = {}));
var ParseErrorCode;
(function(ParseErrorCode2) {
  ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
  ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
  ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
  ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
  ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
  ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
  ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
  ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
  ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
  ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
  ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
  ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
  ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
})(ParseErrorCode || (ParseErrorCode = {}));
var ParseOptions;
(function(ParseOptions2) {
  ParseOptions2.DEFAULT = {
    allowTrailingComma: true
  };
})(ParseOptions || (ParseOptions = {}));
function $ww(text, ignoreTrivia = false) {
  let pos = 0;
  const len = text.length;
  let value = "";
  let tokenOffset = 0;
  let token = 16;
  let scanError = 0;
  function scanHexDigits(count) {
    let digits = 0;
    let hexValue = 0;
    while (digits < count) {
      const ch = text.charCodeAt(pos);
      if (ch >= 48 && ch <= 57) {
        hexValue = hexValue * 16 + ch - 48;
      } else if (ch >= 65 && ch <= 70) {
        hexValue = hexValue * 16 + ch - 65 + 10;
      } else if (ch >= 97 && ch <= 102) {
        hexValue = hexValue * 16 + ch - 97 + 10;
      } else {
        break;
      }
      pos++;
      digits++;
    }
    if (digits < count) {
      hexValue = -1;
    }
    return hexValue;
  }
  function setPosition(newPosition) {
    pos = newPosition;
    value = "";
    tokenOffset = 0;
    token = 16;
    scanError = 0;
  }
  function scanNumber() {
    const start = pos;
    if (text.charCodeAt(pos) === 48) {
      pos++;
    } else {
      pos++;
      while (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
      }
    }
    if (pos < text.length && text.charCodeAt(pos) === 46) {
      pos++;
      if (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit(text.charCodeAt(pos))) {
          pos++;
        }
      } else {
        scanError = 3;
        return text.substring(start, pos);
      }
    }
    let end = pos;
    if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
      pos++;
      if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
        pos++;
      }
      if (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit(text.charCodeAt(pos))) {
          pos++;
        }
        end = pos;
      } else {
        scanError = 3;
      }
    }
    return text.substring(start, end);
  }
  function scanString() {
    let result = "", start = pos;
    while (true) {
      if (pos >= len) {
        result += text.substring(start, pos);
        scanError = 2;
        break;
      }
      const ch = text.charCodeAt(pos);
      if (ch === 34) {
        result += text.substring(start, pos);
        pos++;
        break;
      }
      if (ch === 92) {
        result += text.substring(start, pos);
        pos++;
        if (pos >= len) {
          scanError = 2;
          break;
        }
        const ch2 = text.charCodeAt(pos++);
        switch (ch2) {
          case 34:
            result += '"';
            break;
          case 92:
            result += "\\";
            break;
          case 47:
            result += "/";
            break;
          case 98:
            result += "\b";
            break;
          case 102:
            result += "\f";
            break;
          case 110:
            result += "\n";
            break;
          case 114:
            result += "\r";
            break;
          case 116:
            result += "	";
            break;
          case 117: {
            const ch3 = scanHexDigits(4);
            if (ch3 >= 0) {
              result += String.fromCharCode(ch3);
            } else {
              scanError = 4;
            }
            break;
          }
          default:
            scanError = 5;
        }
        start = pos;
        continue;
      }
      if (ch >= 0 && ch <= 31) {
        if (isLineBreak(ch)) {
          result += text.substring(start, pos);
          scanError = 2;
          break;
        } else {
          scanError = 6;
        }
      }
      pos++;
    }
    return result;
  }
  function scanNext() {
    value = "";
    scanError = 0;
    tokenOffset = pos;
    if (pos >= len) {
      tokenOffset = len;
      return token = 17;
    }
    let code = text.charCodeAt(pos);
    if (isWhitespace2(code)) {
      do {
        pos++;
        value += String.fromCharCode(code);
        code = text.charCodeAt(pos);
      } while (isWhitespace2(code));
      return token = 15;
    }
    if (isLineBreak(code)) {
      pos++;
      value += String.fromCharCode(code);
      if (code === 13 && text.charCodeAt(pos) === 10) {
        pos++;
        value += "\n";
      }
      return token = 14;
    }
    switch (code) {
      case 123:
        pos++;
        return token = 1;
      case 125:
        pos++;
        return token = 2;
      case 91:
        pos++;
        return token = 3;
      case 93:
        pos++;
        return token = 4;
      case 58:
        pos++;
        return token = 6;
      case 44:
        pos++;
        return token = 5;
      case 34:
        pos++;
        value = scanString();
        return token = 10;
      case 47: {
        const start = pos - 1;
        if (text.charCodeAt(pos + 1) === 47) {
          pos += 2;
          while (pos < len) {
            if (isLineBreak(text.charCodeAt(pos))) {
              break;
            }
            pos++;
          }
          value = text.substring(start, pos);
          return token = 12;
        }
        if (text.charCodeAt(pos + 1) === 42) {
          pos += 2;
          const safeLength = len - 1;
          let commentClosed = false;
          while (pos < safeLength) {
            const ch = text.charCodeAt(pos);
            if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
              pos += 2;
              commentClosed = true;
              break;
            }
            pos++;
          }
          if (!commentClosed) {
            pos++;
            scanError = 1;
          }
          value = text.substring(start, pos);
          return token = 13;
        }
        value += String.fromCharCode(code);
        pos++;
        return token = 16;
      }
      case 45:
        value += String.fromCharCode(code);
        pos++;
        if (pos === len || !isDigit(text.charCodeAt(pos))) {
          return token = 16;
        }
      case 48:
      case 49:
      case 50:
      case 51:
      case 52:
      case 53:
      case 54:
      case 55:
      case 56:
      case 57:
        value += scanNumber();
        return token = 11;
      default:
        while (pos < len && isUnknownContentCharacter(code)) {
          pos++;
          code = text.charCodeAt(pos);
        }
        if (tokenOffset !== pos) {
          value = text.substring(tokenOffset, pos);
          switch (value) {
            case "true":
              return token = 8;
            case "false":
              return token = 9;
            case "null":
              return token = 7;
          }
          return token = 16;
        }
        value += String.fromCharCode(code);
        pos++;
        return token = 16;
    }
  }
  function isUnknownContentCharacter(code) {
    if (isWhitespace2(code) || isLineBreak(code)) {
      return false;
    }
    switch (code) {
      case 125:
      case 93:
      case 123:
      case 91:
      case 34:
      case 58:
      case 44:
      case 47:
        return false;
    }
    return true;
  }
  function scanNextNonTrivia() {
    let result;
    do {
      result = scanNext();
    } while (result >= 12 && result <= 15);
    return result;
  }
  return {
    setPosition,
    getPosition: () => pos,
    scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
    getToken: () => token,
    getTokenValue: () => value,
    getTokenOffset: () => tokenOffset,
    getTokenLength: () => pos - tokenOffset,
    getTokenError: () => scanError
  };
}
function isWhitespace2(ch) {
  return ch === 32 || ch === 9 || ch === 11 || ch === 12 || ch === 160 || ch === 5760 || ch >= 8192 && ch <= 8203 || ch === 8239 || ch === 8287 || ch === 12288 || ch === 65279;
}
function isLineBreak(ch) {
  return ch === 10 || ch === 13 || ch === 8232 || ch === 8233;
}
function isDigit(ch) {
  return ch >= 48 && ch <= 57;
}
var CharacterCodes;
(function(CharacterCodes2) {
  CharacterCodes2[CharacterCodes2["nullCharacter"] = 0] = "nullCharacter";
  CharacterCodes2[CharacterCodes2["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
  CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
  CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
  CharacterCodes2[CharacterCodes2["lineSeparator"] = 8232] = "lineSeparator";
  CharacterCodes2[CharacterCodes2["paragraphSeparator"] = 8233] = "paragraphSeparator";
  CharacterCodes2[CharacterCodes2["nextLine"] = 133] = "nextLine";
  CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
  CharacterCodes2[CharacterCodes2["nonBreakingSpace"] = 160] = "nonBreakingSpace";
  CharacterCodes2[CharacterCodes2["enQuad"] = 8192] = "enQuad";
  CharacterCodes2[CharacterCodes2["emQuad"] = 8193] = "emQuad";
  CharacterCodes2[CharacterCodes2["enSpace"] = 8194] = "enSpace";
  CharacterCodes2[CharacterCodes2["emSpace"] = 8195] = "emSpace";
  CharacterCodes2[CharacterCodes2["threePerEmSpace"] = 8196] = "threePerEmSpace";
  CharacterCodes2[CharacterCodes2["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
  CharacterCodes2[CharacterCodes2["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
  CharacterCodes2[CharacterCodes2["figureSpace"] = 8199] = "figureSpace";
  CharacterCodes2[CharacterCodes2["punctuationSpace"] = 8200] = "punctuationSpace";
  CharacterCodes2[CharacterCodes2["thinSpace"] = 8201] = "thinSpace";
  CharacterCodes2[CharacterCodes2["hairSpace"] = 8202] = "hairSpace";
  CharacterCodes2[CharacterCodes2["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
  CharacterCodes2[CharacterCodes2["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
  CharacterCodes2[CharacterCodes2["ideographicSpace"] = 12288] = "ideographicSpace";
  CharacterCodes2[CharacterCodes2["mathematicalSpace"] = 8287] = "mathematicalSpace";
  CharacterCodes2[CharacterCodes2["ogham"] = 5760] = "ogham";
  CharacterCodes2[CharacterCodes2["_"] = 95] = "_";
  CharacterCodes2[CharacterCodes2["$"] = 36] = "$";
  CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
  CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
  CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
  CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
  CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
  CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
  CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
  CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
  CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
  CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
  CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
  CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
  CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
  CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
  CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
  CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
  CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
  CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
  CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
  CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
  CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
  CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
  CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
  CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
  CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
  CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
  CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
  CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
  CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
  CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
  CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
  CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
  CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
  CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
  CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
  CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
  CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
  CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
  CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
  CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
  CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
  CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
  CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
  CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
  CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
  CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
  CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
  CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
  CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
  CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
  CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
  CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
  CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
  CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
  CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
  CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
  CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
  CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
  CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
  CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
  CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
  CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
  CharacterCodes2[CharacterCodes2["ampersand"] = 38] = "ampersand";
  CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
  CharacterCodes2[CharacterCodes2["at"] = 64] = "at";
  CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
  CharacterCodes2[CharacterCodes2["bar"] = 124] = "bar";
  CharacterCodes2[CharacterCodes2["caret"] = 94] = "caret";
  CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
  CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
  CharacterCodes2[CharacterCodes2["closeParen"] = 41] = "closeParen";
  CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
  CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
  CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
  CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
  CharacterCodes2[CharacterCodes2["equals"] = 61] = "equals";
  CharacterCodes2[CharacterCodes2["exclamation"] = 33] = "exclamation";
  CharacterCodes2[CharacterCodes2["greaterThan"] = 62] = "greaterThan";
  CharacterCodes2[CharacterCodes2["lessThan"] = 60] = "lessThan";
  CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
  CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
  CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
  CharacterCodes2[CharacterCodes2["openParen"] = 40] = "openParen";
  CharacterCodes2[CharacterCodes2["percent"] = 37] = "percent";
  CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
  CharacterCodes2[CharacterCodes2["question"] = 63] = "question";
  CharacterCodes2[CharacterCodes2["semicolon"] = 59] = "semicolon";
  CharacterCodes2[CharacterCodes2["singleQuote"] = 39] = "singleQuote";
  CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
  CharacterCodes2[CharacterCodes2["tilde"] = 126] = "tilde";
  CharacterCodes2[CharacterCodes2["backspace"] = 8] = "backspace";
  CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
  CharacterCodes2[CharacterCodes2["byteOrderMark"] = 65279] = "byteOrderMark";
  CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
  CharacterCodes2[CharacterCodes2["verticalTab"] = 11] = "verticalTab";
})(CharacterCodes || (CharacterCodes = {}));
function $Fw(text, visitor, options2 = ParseOptions.DEFAULT) {
  const _scanner = $ww(text, false);
  function toNoArgVisit(visitFunction) {
    return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true;
  }
  function toOneArgVisit(visitFunction) {
    return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true;
  }
  const onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
  const disallowComments = options2 && options2.disallowComments;
  const allowTrailingComma = options2 && options2.allowTrailingComma;
  function scanNext() {
    while (true) {
      const token = _scanner.scan();
      switch (_scanner.getTokenError()) {
        case 4:
          handleError(
            14
            /* ParseErrorCode.InvalidUnicode */
          );
          break;
        case 5:
          handleError(
            15
            /* ParseErrorCode.InvalidEscapeCharacter */
          );
          break;
        case 3:
          handleError(
            13
            /* ParseErrorCode.UnexpectedEndOfNumber */
          );
          break;
        case 1:
          if (!disallowComments) {
            handleError(
              11
              /* ParseErrorCode.UnexpectedEndOfComment */
            );
          }
          break;
        case 2:
          handleError(
            12
            /* ParseErrorCode.UnexpectedEndOfString */
          );
          break;
        case 6:
          handleError(
            16
            /* ParseErrorCode.InvalidCharacter */
          );
          break;
      }
      switch (token) {
        case 12:
        case 13:
          if (disallowComments) {
            handleError(
              10
              /* ParseErrorCode.InvalidCommentToken */
            );
          } else {
            onComment();
          }
          break;
        case 16:
          handleError(
            1
            /* ParseErrorCode.InvalidSymbol */
          );
          break;
        case 15:
        case 14:
          break;
        default:
          return token;
      }
    }
  }
  function handleError(error, skipUntilAfter = [], skipUntil = []) {
    onError(error);
    if (skipUntilAfter.length + skipUntil.length > 0) {
      let token = _scanner.getToken();
      while (token !== 17) {
        if (skipUntilAfter.indexOf(token) !== -1) {
          scanNext();
          break;
        } else if (skipUntil.indexOf(token) !== -1) {
          break;
        }
        token = scanNext();
      }
    }
  }
  function parseString(isValue) {
    const value = _scanner.getTokenValue();
    if (isValue) {
      onLiteralValue(value);
    } else {
      onObjectProperty(value);
    }
    scanNext();
    return true;
  }
  function parseLiteral() {
    switch (_scanner.getToken()) {
      case 11: {
        let value = 0;
        try {
          value = JSON.parse(_scanner.getTokenValue());
          if (typeof value !== "number") {
            handleError(
              2
              /* ParseErrorCode.InvalidNumberFormat */
            );
            value = 0;
          }
        } catch (e) {
          handleError(
            2
            /* ParseErrorCode.InvalidNumberFormat */
          );
        }
        onLiteralValue(value);
        break;
      }
      case 7:
        onLiteralValue(null);
        break;
      case 8:
        onLiteralValue(true);
        break;
      case 9:
        onLiteralValue(false);
        break;
      default:
        return false;
    }
    scanNext();
    return true;
  }
  function parseProperty() {
    if (_scanner.getToken() !== 10) {
      handleError(3, [], [
        2,
        5
        /* SyntaxKind.CommaToken */
      ]);
      return false;
    }
    parseString(false);
    if (_scanner.getToken() === 6) {
      onSeparator(":");
      scanNext();
      if (!parseValue()) {
        handleError(4, [], [
          2,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
    } else {
      handleError(5, [], [
        2,
        5
        /* SyntaxKind.CommaToken */
      ]);
    }
    return true;
  }
  function parseObject() {
    onObjectBegin();
    scanNext();
    let needsComma = false;
    while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) {
          handleError(4, [], []);
        }
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 2 && allowTrailingComma) {
          break;
        }
      } else if (needsComma) {
        handleError(6, [], []);
      }
      if (!parseProperty()) {
        handleError(4, [], [
          2,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
      needsComma = true;
    }
    onObjectEnd();
    if (_scanner.getToken() !== 2) {
      handleError(7, [
        2
        /* SyntaxKind.CloseBraceToken */
      ], []);
    } else {
      scanNext();
    }
    return true;
  }
  function parseArray() {
    onArrayBegin();
    scanNext();
    let needsComma = false;
    while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) {
          handleError(4, [], []);
        }
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 4 && allowTrailingComma) {
          break;
        }
      } else if (needsComma) {
        handleError(6, [], []);
      }
      if (!parseValue()) {
        handleError(4, [], [
          4,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
      needsComma = true;
    }
    onArrayEnd();
    if (_scanner.getToken() !== 4) {
      handleError(8, [
        4
        /* SyntaxKind.CloseBracketToken */
      ], []);
    } else {
      scanNext();
    }
    return true;
  }
  function parseValue() {
    switch (_scanner.getToken()) {
      case 3:
        return parseArray();
      case 1:
        return parseObject();
      case 10:
        return parseString(true);
      default:
        return parseLiteral();
    }
  }
  scanNext();
  if (_scanner.getToken() === 17) {
    if (options2.allowEmptyContent) {
      return true;
    }
    handleError(4, [], []);
    return false;
  }
  if (!parseValue()) {
    handleError(4, [], []);
    return false;
  }
  if (_scanner.getToken() !== 17) {
    handleError(9, [], []);
  }
  return true;
}

// out-build/vs/platform/configuration/common/configurationModels.js
function freeze(data) {
  return Object.isFrozen(data) ? data : $Mv(data);
}
var $SB = class _$SB {
  static createEmptyModel(logService) {
    return new _$SB({}, [], [], void 0, logService);
  }
  constructor(b, c, d, raw, f) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.raw = raw;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
  }
  get rawConfiguration() {
    if (!this.g) {
      if (this.raw?.length) {
        const rawConfigurationModels = this.raw.map((raw) => {
          if (raw instanceof _$SB) {
            return raw;
          }
          const parser2 = new $TB("", this.f);
          parser2.parseRaw(raw);
          return parser2.configurationModel;
        });
        this.g = rawConfigurationModels.reduce((previous, current) => current === previous ? current : previous.merge(current), rawConfigurationModels[0]);
      } else {
        this.g = this;
      }
    }
    return this.g;
  }
  get contents() {
    return this.b;
  }
  get overrides() {
    return this.d;
  }
  get keys() {
    return this.c;
  }
  isEmpty() {
    return this.c.length === 0 && Object.keys(this.b).length === 0 && this.d.length === 0;
  }
  getValue(section) {
    return section ? $sl(this.contents, section) : this.contents;
  }
  inspect(section, overrideIdentifier) {
    const that = this;
    return {
      get value() {
        return freeze(that.rawConfiguration.getValue(section));
      },
      get override() {
        return overrideIdentifier ? freeze(that.rawConfiguration.getOverrideValue(section, overrideIdentifier)) : void 0;
      },
      get merged() {
        return freeze(overrideIdentifier ? that.rawConfiguration.override(overrideIdentifier).getValue(section) : that.rawConfiguration.getValue(section));
      },
      get overrides() {
        const overrides = [];
        for (const { contents, identifiers: identifiers2, keys } of that.rawConfiguration.overrides) {
          const value = new _$SB(contents, keys, [], void 0, that.f).getValue(section);
          if (value !== void 0) {
            overrides.push({ identifiers: identifiers2, value });
          }
        }
        return overrides.length ? freeze(overrides) : void 0;
      }
    };
  }
  getOverrideValue(section, overrideIdentifier) {
    const overrideContents = this.j(overrideIdentifier);
    return overrideContents ? section ? $sl(overrideContents, section) : overrideContents : void 0;
  }
  getKeysForOverrideIdentifier(identifier) {
    const keys = [];
    for (const override of this.overrides) {
      if (override.identifiers.includes(identifier)) {
        keys.push(...override.keys);
      }
    }
    return $Rb(keys);
  }
  getAllOverrideIdentifiers() {
    const result = [];
    for (const override of this.overrides) {
      result.push(...override.identifiers);
    }
    return $Rb(result);
  }
  override(identifier) {
    let overrideConfigurationModel = this.a.get(identifier);
    if (!overrideConfigurationModel) {
      overrideConfigurationModel = this.h(identifier);
      this.a.set(identifier, overrideConfigurationModel);
    }
    return overrideConfigurationModel;
  }
  merge(...others) {
    const contents = $Lv(this.contents);
    const overrides = $Lv(this.overrides);
    const keys = [...this.keys];
    const raws = this.raw?.length ? [...this.raw] : [this];
    for (const other of others) {
      raws.push(...other.raw?.length ? other.raw : [other]);
      if (other.isEmpty()) {
        continue;
      }
      this.i(contents, other.contents);
      for (const otherOverride of other.overrides) {
        const [override] = overrides.filter((o) => $zb(o.identifiers, otherOverride.identifiers));
        if (override) {
          this.i(override.contents, otherOverride.contents);
          override.keys.push(...otherOverride.keys);
          override.keys = $Rb(override.keys);
        } else {
          overrides.push($Lv(otherOverride));
        }
      }
      for (const key of other.keys) {
        if (keys.indexOf(key) === -1) {
          keys.push(key);
        }
      }
    }
    return new _$SB(contents, keys, overrides, raws.every((raw) => raw instanceof _$SB) ? void 0 : raws, this.f);
  }
  h(identifier) {
    const overrideContents = this.j(identifier);
    if (!overrideContents || typeof overrideContents !== "object" || !Object.keys(overrideContents).length) {
      return this;
    }
    const contents = {};
    for (const key of $Rb([...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 = $Lv(contentsForKey);
          this.i(contentsForKey, overrideContentsForKey);
        } else {
          contentsForKey = overrideContentsForKey;
        }
      }
      contents[key] = contentsForKey;
    }
    return new _$SB(contents, this.keys, this.overrides, void 0, this.f);
  }
  i(source, target) {
    for (const key of Object.keys(target)) {
      if (key in source) {
        if ($Bg(source[key]) && $Bg(target[key])) {
          this.i(source[key], target[key]);
          continue;
        }
      }
      source[key] = $Lv(target[key]);
    }
  }
  j(identifier) {
    let contentsForIdentifierOnly = null;
    let contents = null;
    const mergeContents = (contentsToMerge) => {
      if (contentsToMerge) {
        if (contents) {
          this.i(contents, contentsToMerge);
        } else {
          contents = $Lv(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.k(key, value, true);
  }
  setValue(key, value) {
    this.k(key, value, false);
  }
  removeValue(key) {
    const index = this.keys.indexOf(key);
    if (index === -1) {
      return;
    }
    this.keys.splice(index, 1);
    $rl(this.contents, key);
    if ($Rt.test(key)) {
      this.overrides.splice(this.overrides.findIndex((o) => $zb(o.identifiers, $St(key))), 1);
    }
  }
  k(key, value, add) {
    $ql(this.contents, key, value, (e) => this.f.error(e));
    add = add || this.keys.indexOf(key) === -1;
    if (add) {
      this.keys.push(key);
    }
    if ($Rt.test(key)) {
      const identifiers2 = $St(key);
      const override = {
        identifiers: identifiers2,
        keys: Object.keys(this.contents[key]),
        contents: $pl(this.contents[key], (message) => this.f.error(message))
      };
      const index = this.overrides.findIndex((o) => $zb(o.identifiers, identifiers2));
      if (index !== -1) {
        this.overrides[index] = override;
      } else {
        this.overrides.push(override);
      }
    }
  }
};
var $TB = class {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.a = null;
    this.b = null;
    this.c = [];
    this.d = [];
  }
  get configurationModel() {
    return this.b || $SB.createEmptyModel(this.g);
  }
  get restrictedConfigurations() {
    return this.c;
  }
  get errors() {
    return this.d;
  }
  parse(content, options2) {
    if (!$Ig(content)) {
      const raw = this.h(content);
      this.parseRaw(raw, options2);
    }
  }
  reparse(options2) {
    if (this.a) {
      this.parseRaw(this.a, options2);
    }
  }
  parseRaw(raw, options2) {
    this.a = raw;
    const { contents, keys, overrides, restricted, hasExcludedProperties } = this.i(raw, options2);
    this.b = new $SB(contents, keys, overrides, hasExcludedProperties ? [raw] : void 0, this.g);
    this.c = restricted || [];
  }
  h(content) {
    let raw = {};
    let currentProperty = null;
    let currentParent = [];
    const previousParents = [];
    const parseErrors = [];
    function onValue(value) {
      if (Array.isArray(currentParent)) {
        currentParent.push(value);
      } else if (currentProperty !== null) {
        currentParent[currentProperty] = value;
      }
    }
    const visitor = {
      onObjectBegin: () => {
        const object = {};
        onValue(object);
        previousParents.push(currentParent);
        currentParent = object;
        currentProperty = null;
      },
      onObjectProperty: (name) => {
        currentProperty = name;
      },
      onObjectEnd: () => {
        currentParent = previousParents.pop();
      },
      onArrayBegin: () => {
        const array = [];
        onValue(array);
        previousParents.push(currentParent);
        currentParent = array;
        currentProperty = null;
      },
      onArrayEnd: () => {
        currentParent = previousParents.pop();
      },
      onLiteralValue: onValue,
      onError: (error, offset, length) => {
        parseErrors.push({ error, offset, length });
      }
    };
    if (content) {
      try {
        $Fw(content, visitor);
        raw = currentParent[0] || {};
      } catch (e) {
        this.g.error(`Error while parsing settings file ${this.f}: ${e}`);
        this.d = [e];
      }
    }
    return raw;
  }
  i(raw, options2) {
    const configurationProperties = $Wn.as($Ht.Configuration).getConfigurationProperties();
    const filtered = this.j(raw, configurationProperties, true, options2);
    raw = filtered.raw;
    const contents = $pl(raw, (message) => this.g.error(`Conflict in settings file ${this.f}: ${message}`));
    const keys = Object.keys(raw);
    const overrides = this.m(raw, (message) => this.g.error(`Conflict in settings file ${this.f}: ${message}`));
    return { contents, keys, overrides, restricted: filtered.restricted, hasExcludedProperties: filtered.hasExcludedProperties };
  }
  j(properties, configurationProperties, filterOverriddenProperties, options2) {
    let hasExcludedProperties = false;
    if (!options2?.scopes && !options2?.skipRestricted && !options2?.exclude?.length) {
      return { raw: properties, restricted: [], hasExcludedProperties };
    }
    const raw = {};
    const restricted = [];
    for (const key in properties) {
      if ($Rt.test(key) && filterOverriddenProperties) {
        const result = this.j(properties[key], configurationProperties, false, options2);
        raw[key] = result.raw;
        hasExcludedProperties = hasExcludedProperties || result.hasExcludedProperties;
        restricted.push(...result.restricted);
      } else {
        const propertySchema = configurationProperties[key];
        if (propertySchema?.restricted) {
          restricted.push(key);
        }
        if (this.l(key, propertySchema, options2)) {
          raw[key] = properties[key];
        } else {
          hasExcludedProperties = true;
        }
      }
    }
    return { raw, restricted, hasExcludedProperties };
  }
  l(key, propertySchema, options2) {
    if (options2.exclude?.includes(key)) {
      return false;
    }
    if (options2.include?.includes(key)) {
      return true;
    }
    if (options2.skipRestricted && propertySchema?.restricted) {
      return false;
    }
    if (options2.skipUnregistered && !propertySchema) {
      return false;
    }
    const scope = propertySchema ? typeof propertySchema.scope !== "undefined" ? propertySchema.scope : 3 : void 0;
    if (scope === void 0 || options2.scopes === void 0) {
      return true;
    }
    return options2.scopes.includes(scope);
  }
  m(raw, conflictReporter) {
    const overrides = [];
    for (const key of Object.keys(raw)) {
      if ($Rt.test(key)) {
        const overrideRaw = {};
        for (const keyInOverrideRaw in raw[key]) {
          overrideRaw[keyInOverrideRaw] = raw[key][keyInOverrideRaw];
        }
        overrides.push({
          identifiers: $St(key),
          keys: Object.keys(overrideRaw),
          contents: $pl(overrideRaw, conflictReporter)
        });
      }
    }
    return overrides;
  }
};
var ConfigurationInspectValue = class {
  constructor(a, b, c, overrideIdentifiers, d, f, g, h, i, j, k, l, m) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.overrideIdentifiers = overrideIdentifiers;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
  }
  get value() {
    return freeze(this.c);
  }
  n(inspectValue) {
    return inspectValue?.value !== void 0 || inspectValue?.override !== void 0 || inspectValue?.overrides !== void 0 ? inspectValue : void 0;
  }
  get q() {
    if (!this.p) {
      this.p = this.d.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.p;
  }
  get defaultValue() {
    return this.q.merged;
  }
  get default() {
    return this.n(this.q);
  }
  get s() {
    if (this.r === void 0) {
      this.r = this.f ? this.f.inspect(this.a) : null;
    }
    return this.r;
  }
  get policyValue() {
    return this.s?.merged;
  }
  get policy() {
    return this.s?.value !== void 0 ? { value: this.s.value } : void 0;
  }
  get u() {
    if (this.t === void 0) {
      this.t = this.g ? this.g.inspect(this.a) : null;
    }
    return this.t;
  }
  get applicationValue() {
    return this.u?.merged;
  }
  get application() {
    return this.n(this.u);
  }
  get w() {
    if (!this.v) {
      this.v = this.h.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.v;
  }
  get userValue() {
    return this.w.merged;
  }
  get user() {
    return this.n(this.w);
  }
  get y() {
    if (!this.x) {
      this.x = this.i.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.x;
  }
  get userLocalValue() {
    return this.y.merged;
  }
  get userLocal() {
    return this.n(this.y);
  }
  get A() {
    if (!this.z) {
      this.z = this.j.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.z;
  }
  get userRemoteValue() {
    return this.A.merged;
  }
  get userRemote() {
    return this.n(this.A);
  }
  get D() {
    if (this.B === void 0) {
      this.B = this.k ? this.k.inspect(this.a, this.b.overrideIdentifier) : null;
    }
    return this.B;
  }
  get workspaceValue() {
    return this.D?.merged;
  }
  get workspace() {
    return this.n(this.D);
  }
  get F() {
    if (this.E === void 0) {
      this.E = this.l ? this.l.inspect(this.a, this.b.overrideIdentifier) : null;
    }
    return this.E;
  }
  get workspaceFolderValue() {
    return this.F?.merged;
  }
  get workspaceFolder() {
    return this.n(this.F);
  }
  get H() {
    if (this.G === void 0) {
      this.G = this.m.inspect(this.a, this.b.overrideIdentifier);
    }
    return this.G;
  }
  get memoryValue() {
    return this.H.merged;
  }
  get memory() {
    return this.n(this.H);
  }
};
var $VB = class _$VB {
  constructor(j, l, m, n, p, q, r, s, t, u) {
    this.j = j;
    this.l = l;
    this.m = m;
    this.n = n;
    this.p = p;
    this.q = q;
    this.r = r;
    this.s = s;
    this.t = t;
    this.u = u;
    this.h = null;
    this.i = new $Ec();
    this.v = null;
  }
  getValue(section, overrides, workspace) {
    const consolidateConfigurationModel = this.w(section, overrides, workspace);
    return consolidateConfigurationModel.getValue(section);
  }
  updateValue(key, value, overrides = {}) {
    let memoryConfiguration;
    if (overrides.resource) {
      memoryConfiguration = this.t.get(overrides.resource);
      if (!memoryConfiguration) {
        memoryConfiguration = $SB.createEmptyModel(this.u);
        this.t.set(overrides.resource, memoryConfiguration);
      }
    } else {
      memoryConfiguration = this.s;
    }
    if (value === void 0) {
      memoryConfiguration.removeValue(key);
    } else {
      memoryConfiguration.setValue(key, value);
    }
    if (!overrides.resource) {
      this.h = null;
    }
  }
  inspect(key, overrides, workspace) {
    const consolidateConfigurationModel = this.w(key, overrides, workspace);
    const folderConfigurationModel = this.A(overrides.resource, workspace);
    const memoryConfigurationModel = overrides.resource ? this.t.get(overrides.resource) || this.s : this.s;
    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.j, this.l.isEmpty() ? void 0 : this.l, this.applicationConfiguration.isEmpty() ? void 0 : this.applicationConfiguration, this.userConfiguration, this.localUserConfiguration, this.remoteUserConfiguration, workspace ? this.q : void 0, folderConfigurationModel ? folderConfigurationModel : void 0, memoryConfigurationModel);
  }
  keys(workspace) {
    const folderConfigurationModel = this.A(void 0, workspace);
    return {
      default: this.j.keys.slice(0),
      user: this.userConfiguration.keys.slice(0),
      workspace: this.q.keys.slice(0),
      workspaceFolder: folderConfigurationModel ? folderConfigurationModel.keys.slice(0) : []
    };
  }
  updateDefaultConfiguration(defaultConfiguration) {
    this.j = defaultConfiguration;
    this.h = null;
    this.i.clear();
  }
  updatePolicyConfiguration(policyConfiguration) {
    this.l = policyConfiguration;
  }
  updateApplicationConfiguration(applicationConfiguration) {
    this.m = applicationConfiguration;
    this.h = null;
    this.i.clear();
  }
  updateLocalUserConfiguration(localUserConfiguration) {
    this.n = localUserConfiguration;
    this.v = null;
    this.h = null;
    this.i.clear();
  }
  updateRemoteUserConfiguration(remoteUserConfiguration) {
    this.p = remoteUserConfiguration;
    this.v = null;
    this.h = null;
    this.i.clear();
  }
  updateWorkspaceConfiguration(workspaceConfiguration) {
    this.q = workspaceConfiguration;
    this.h = null;
    this.i.clear();
  }
  updateFolderConfiguration(resource, configuration) {
    this.r.set(resource, configuration);
    this.i.delete(resource);
  }
  deleteFolderConfiguration(resource) {
    this.folderConfigurations.delete(resource);
    this.i.delete(resource);
  }
  compareAndUpdateDefaultConfiguration(defaults, keys) {
    const overrides = [];
    if (!keys) {
      const { added, updated, removed } = compare(this.j, defaults);
      keys = [...added, ...updated, ...removed];
    }
    for (const key of keys) {
      for (const overrideIdentifier of $St(key)) {
        const fromKeys = this.j.getKeysForOverrideIdentifier(overrideIdentifier);
        const toKeys = defaults.getKeysForOverrideIdentifier(overrideIdentifier);
        const keys2 = [
          ...toKeys.filter((key2) => fromKeys.indexOf(key2) === -1),
          ...fromKeys.filter((key2) => toKeys.indexOf(key2) === -1),
          ...fromKeys.filter((key2) => !$Pv(this.j.override(overrideIdentifier).getValue(key2), defaults.override(overrideIdentifier).getValue(key2)))
        ];
        overrides.push([overrideIdentifier, keys2]);
      }
    }
    this.updateDefaultConfiguration(defaults);
    return { keys, overrides };
  }
  compareAndUpdatePolicyConfiguration(policyConfiguration) {
    const { added, updated, removed } = compare(this.l, policyConfiguration);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updatePolicyConfiguration(policyConfiguration);
    }
    return { keys, overrides: [] };
  }
  compareAndUpdateApplicationConfiguration(application) {
    const { added, updated, removed, overrides } = compare(this.applicationConfiguration, application);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateApplicationConfiguration(application);
    }
    return { keys, overrides };
  }
  compareAndUpdateLocalUserConfiguration(user) {
    const { added, updated, removed, overrides } = compare(this.localUserConfiguration, user);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateLocalUserConfiguration(user);
    }
    return { keys, overrides };
  }
  compareAndUpdateRemoteUserConfiguration(user) {
    const { added, updated, removed, overrides } = compare(this.remoteUserConfiguration, user);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateRemoteUserConfiguration(user);
    }
    return { keys, overrides };
  }
  compareAndUpdateWorkspaceConfiguration(workspaceConfiguration) {
    const { added, updated, removed, overrides } = compare(this.workspaceConfiguration, workspaceConfiguration);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateWorkspaceConfiguration(workspaceConfiguration);
    }
    return { keys, overrides };
  }
  compareAndUpdateFolderConfiguration(resource, folderConfiguration) {
    const currentFolderConfiguration = this.folderConfigurations.get(resource);
    const { added, updated, removed, overrides } = compare(currentFolderConfiguration, folderConfiguration);
    const keys = [...added, ...updated, ...removed];
    if (keys.length || !currentFolderConfiguration) {
      this.updateFolderConfiguration(resource, folderConfiguration);
    }
    return { keys, overrides };
  }
  compareAndDeleteFolderConfiguration(folder) {
    const folderConfig = this.folderConfigurations.get(folder);
    if (!folderConfig) {
      throw new Error("Unknown folder");
    }
    this.deleteFolderConfiguration(folder);
    const { added, updated, removed, overrides } = compare(folderConfig, void 0);
    return { keys: [...added, ...updated, ...removed], overrides };
  }
  get defaults() {
    return this.j;
  }
  get applicationConfiguration() {
    return this.m;
  }
  get userConfiguration() {
    if (!this.v) {
      this.v = this.p.isEmpty() ? this.n : this.n.merge(this.p);
    }
    return this.v;
  }
  get localUserConfiguration() {
    return this.n;
  }
  get remoteUserConfiguration() {
    return this.p;
  }
  get workspaceConfiguration() {
    return this.q;
  }
  get folderConfigurations() {
    return this.r;
  }
  w(section, overrides, workspace) {
    let configurationModel = this.x(overrides, workspace);
    if (overrides.overrideIdentifier) {
      configurationModel = configurationModel.override(overrides.overrideIdentifier);
    }
    if (!this.l.isEmpty() && this.l.getValue(section) !== void 0) {
      configurationModel = configurationModel.merge(this.l);
    }
    return configurationModel;
  }
  x({ resource }, workspace) {
    let consolidateConfiguration = this.y();
    if (workspace && resource) {
      const root = workspace.getFolder(resource);
      if (root) {
        consolidateConfiguration = this.z(root.uri) || consolidateConfiguration;
      }
      const memoryConfigurationForResource = this.t.get(resource);
      if (memoryConfigurationForResource) {
        consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
      }
    }
    return consolidateConfiguration;
  }
  y() {
    if (!this.h) {
      this.h = this.j.merge(this.applicationConfiguration, this.userConfiguration, this.q, this.s);
    }
    return this.h;
  }
  z(folder) {
    let folderConsolidatedConfiguration = this.i.get(folder);
    if (!folderConsolidatedConfiguration) {
      const workspaceConsolidateConfiguration = this.y();
      const folderConfiguration = this.r.get(folder);
      if (folderConfiguration) {
        folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
        this.i.set(folder, folderConsolidatedConfiguration);
      } else {
        folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
      }
    }
    return folderConsolidatedConfiguration;
  }
  A(resource, workspace) {
    if (workspace && resource) {
      const root = workspace.getFolder(resource);
      if (root) {
        return this.r.get(root.uri);
      }
    }
    return void 0;
  }
  toData() {
    return {
      defaults: {
        contents: this.j.contents,
        overrides: this.j.overrides,
        keys: this.j.keys
      },
      policy: {
        contents: this.l.contents,
        overrides: this.l.overrides,
        keys: this.l.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.q.contents,
        overrides: this.q.overrides,
        keys: this.q.keys
      },
      folders: [...this.r.keys()].reduce((result, folder) => {
        const { contents, overrides, keys } = this.r.get(folder);
        result.push([folder, { contents, overrides, keys }]);
        return result;
      }, [])
    };
  }
  allKeys() {
    const keys = /* @__PURE__ */ new Set();
    this.j.keys.forEach((key) => keys.add(key));
    this.userConfiguration.keys.forEach((key) => keys.add(key));
    this.q.keys.forEach((key) => keys.add(key));
    this.r.forEach((folderConfiguration) => folderConfiguration.keys.forEach((key) => keys.add(key)));
    return [...keys.values()];
  }
  B() {
    const keys = /* @__PURE__ */ new Set();
    this.j.getAllOverrideIdentifiers().forEach((key) => keys.add(key));
    this.userConfiguration.getAllOverrideIdentifiers().forEach((key) => keys.add(key));
    this.q.getAllOverrideIdentifiers().forEach((key) => keys.add(key));
    this.r.forEach((folderConfiguration) => folderConfiguration.getAllOverrideIdentifiers().forEach((key) => keys.add(key)));
    return [...keys.values()];
  }
  D(overrideIdentifier) {
    const keys = /* @__PURE__ */ new Set();
    this.j.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key) => keys.add(key));
    this.userConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key) => keys.add(key));
    this.q.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key) => keys.add(key));
    this.r.forEach((folderConfiguration) => folderConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key) => keys.add(key)));
    return [...keys.values()];
  }
  static parse(data, logService) {
    const defaultConfiguration = this.E(data.defaults, logService);
    const policyConfiguration = this.E(data.policy, logService);
    const applicationConfiguration = this.E(data.application, logService);
    const userConfiguration = this.E(data.user, logService);
    const workspaceConfiguration = this.E(data.workspace, logService);
    const folders = data.folders.reduce((result, value) => {
      result.set(URI.revive(value[0]), this.E(value[1], logService));
      return result;
    }, new $Ec());
    return new _$VB(defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, $SB.createEmptyModel(logService), workspaceConfiguration, folders, $SB.createEmptyModel(logService), new $Ec(), logService);
  }
  static E(model, logService) {
    return new $SB(model.contents, model.keys, model.overrides, void 0, logService);
  }
};
var $XB = class {
  constructor(change, f, g, h, i) {
    this.change = change;
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.a = "\n";
    this.b = this.a.charCodeAt(0);
    this.c = ".".charCodeAt(0);
    this.affectedKeys = /* @__PURE__ */ new Set();
    this.j = 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.d = this.a;
    for (const key of this.affectedKeys) {
      this.d += key + this.a;
    }
  }
  get previousConfiguration() {
    if (!this.j && this.f) {
      this.j = $VB.parse(this.f.data, this.i);
    }
    return this.j;
  }
  affectsConfiguration(section, overrides) {
    const needle = this.a + section;
    const idx = this.d.indexOf(needle);
    if (idx < 0) {
      return false;
    }
    const pos = idx + needle.length;
    if (pos >= this.d.length) {
      return false;
    }
    const code = this.d.charCodeAt(pos);
    if (code !== this.b && code !== this.c) {
      return false;
    }
    if (overrides) {
      const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, this.f?.workspace) : void 0;
      const value2 = this.g.getValue(section, overrides, this.h);
      return !$Pv(value1, value2);
    }
    return true;
  }
};
function compare(from, to) {
  const { added, removed, updated } = compareConfigurationContents(to?.rawConfiguration, from?.rawConfiguration);
  const overrides = [];
  const fromOverrideIdentifiers = from?.getAllOverrideIdentifiers() || [];
  const toOverrideIdentifiers = to?.getAllOverrideIdentifiers() || [];
  if (to) {
    const addedOverrideIdentifiers = toOverrideIdentifiers.filter((key) => !fromOverrideIdentifiers.includes(key));
    for (const identifier of addedOverrideIdentifiers) {
      overrides.push([identifier, to.getKeysForOverrideIdentifier(identifier)]);
    }
  }
  if (from) {
    const removedOverrideIdentifiers = fromOverrideIdentifiers.filter((key) => !toOverrideIdentifiers.includes(key));
    for (const identifier of removedOverrideIdentifiers) {
      overrides.push([identifier, from.getKeysForOverrideIdentifier(identifier)]);
    }
  }
  if (to && from) {
    for (const identifier of fromOverrideIdentifiers) {
      if (toOverrideIdentifiers.includes(identifier)) {
        const result = compareConfigurationContents({ contents: from.getOverrideValue(void 0, identifier) || {}, keys: from.getKeysForOverrideIdentifier(identifier) }, { contents: to.getOverrideValue(void 0, identifier) || {}, keys: to.getKeysForOverrideIdentifier(identifier) });
        overrides.push([identifier, [...result.added, ...result.removed, ...result.updated]]);
      }
    }
  }
  return { added, removed, updated, overrides };
}
function compareConfigurationContents(to, from) {
  const added = to ? from ? to.keys.filter((key) => from.keys.indexOf(key) === -1) : [...to.keys] : [];
  const removed = from ? to ? from.keys.filter((key) => to.keys.indexOf(key) === -1) : [...from.keys] : [];
  const updated = [];
  if (to && from) {
    for (const key of from.keys) {
      if (to.keys.indexOf(key) !== -1) {
        const value1 = $sl(from.contents, key);
        const value2 = $sl(to.contents, key);
        if (!$Pv(value1, value2)) {
          updated.push(key);
        }
      }
    }
  }
  return { added, removed, updated };
}

// out-build/vs/workbench/api/common/extHostConfiguration.js
function lookUp(tree, key) {
  if (key) {
    const parts = key.split(".");
    let node = tree;
    for (let i = 0; node && i < parts.length; i++) {
      node = node[parts[i]];
    }
    return node;
  }
}
function isUri(thing) {
  return thing instanceof URI;
}
function isResourceLanguage(thing) {
  return thing && thing.uri instanceof URI && (thing.languageId && typeof thing.languageId === "string");
}
function isLanguage(thing) {
  return thing && !thing.uri && (thing.languageId && typeof thing.languageId === "string");
}
function isWorkspaceFolder(thing) {
  return thing && thing.uri instanceof URI && (!thing.name || typeof thing.name === "string") && (!thing.index || typeof thing.index === "number");
}
function scopeToOverrides(scope) {
  if (isUri(scope)) {
    return { resource: scope };
  }
  if (isResourceLanguage(scope)) {
    return { resource: scope.uri, overrideIdentifier: scope.languageId };
  }
  if (isLanguage(scope)) {
    return { overrideIdentifier: scope.languageId };
  }
  if (isWorkspaceFolder(scope)) {
    return { resource: scope.uri };
  }
  if (scope === null) {
    return { resource: null };
  }
  return void 0;
}
var $$wc = class $$wc2 {
  constructor(extHostRpc, extHostWorkspace, logService) {
    this.a = extHostRpc.getProxy($xT.MainThreadConfiguration);
    this.c = extHostWorkspace;
    this.b = logService;
    this.d = new $Uh();
    this.e = null;
  }
  getConfigProvider() {
    return this.d.wait().then((_) => this.e);
  }
  $initializeConfiguration(data) {
    this.e = new $_wc(this.a, this.c, data, this.b);
    this.d.open();
  }
  $acceptConfigurationChanged(data, change) {
    this.getConfigProvider().then((provider) => provider.$acceptConfigurationChanged(data, change));
  }
};
$$wc = __decorate([
  __param(0, $gW),
  __param(1, $0wc),
  __param(2, $wn)
], $$wc);
var $_wc = class {
  constructor(proxy, extHostWorkspace, data, logService) {
    this.a = new $ze();
    this.b = proxy;
    this.f = logService;
    this.c = extHostWorkspace;
    this.e = $VB.parse(data, logService);
    this.d = this.k(data.configurationScopes);
  }
  get onDidChangeConfiguration() {
    return this.a && this.a.event;
  }
  $acceptConfigurationChanged(data, change) {
    const previous = { data: this.e.toData(), workspace: this.c.workspace };
    this.e = $VB.parse(data, this.f);
    this.d = this.k(data.configurationScopes);
    this.a.fire(this.j(change, previous));
  }
  getConfiguration(section, scope, extensionDescription) {
    const overrides = scopeToOverrides(scope) || {};
    const config = this.g(section ? lookUp(this.e.getValue(void 0, overrides, this.c.workspace), section) : this.e.getValue(void 0, overrides, this.c.workspace));
    if (section) {
      this.h(section, overrides, extensionDescription?.identifier);
    }
    function parseConfigurationTarget(arg) {
      if (arg === void 0 || arg === null) {
        return null;
      }
      if (typeof arg === "boolean") {
        return arg ? 2 : 5;
      }
      switch (arg) {
        case ConfigurationTarget2.Global:
          return 2;
        case ConfigurationTarget2.Workspace:
          return 5;
        case ConfigurationTarget2.WorkspaceFolder:
          return 6;
      }
    }
    const result = {
      has(key) {
        return typeof lookUp(config, key) !== "undefined";
      },
      get: (key, defaultValue) => {
        this.h(section ? `${section}.${key}` : key, overrides, extensionDescription?.identifier);
        let result2 = lookUp(config, key);
        if (typeof result2 === "undefined") {
          result2 = defaultValue;
        } else {
          let clonedConfig = void 0;
          const cloneOnWriteProxy = (target, accessor) => {
            if ($Bg(target)) {
              let clonedTarget = void 0;
              const cloneTarget = () => {
                clonedConfig = clonedConfig ? clonedConfig : $Lv(config);
                clonedTarget = clonedTarget ? clonedTarget : lookUp(clonedConfig, accessor);
              };
              return new Proxy(target, {
                get: (target2, property) => {
                  if (typeof property === "string" && property.toLowerCase() === "tojson") {
                    cloneTarget();
                    return () => clonedTarget;
                  }
                  if (clonedConfig) {
                    clonedTarget = clonedTarget ? clonedTarget : lookUp(clonedConfig, accessor);
                    return clonedTarget[property];
                  }
                  const result3 = target2[property];
                  if (typeof property === "string") {
                    return cloneOnWriteProxy(result3, `${accessor}.${property}`);
                  }
                  return result3;
                },
                set: (_target, property, value) => {
                  cloneTarget();
                  if (clonedTarget) {
                    clonedTarget[property] = value;
                  }
                  return true;
                },
                deleteProperty: (_target, property) => {
                  cloneTarget();
                  if (clonedTarget) {
                    delete clonedTarget[property];
                  }
                  return true;
                },
                defineProperty: (_target, property, descriptor) => {
                  cloneTarget();
                  if (clonedTarget) {
                    Object.defineProperty(clonedTarget, property, descriptor);
                  }
                  return true;
                }
              });
            }
            if (Array.isArray(target)) {
              return $Lv(target);
            }
            return target;
          };
          result2 = cloneOnWriteProxy(result2, key);
        }
        return result2;
      },
      update: (key, value, extHostConfigurationTarget, scopeToLanguage) => {
        key = section ? `${section}.${key}` : key;
        const target = parseConfigurationTarget(extHostConfigurationTarget);
        if (value !== void 0) {
          return this.b.$updateConfigurationOption(target, key, value, overrides, scopeToLanguage);
        } else {
          return this.b.$removeConfigurationOption(target, key, overrides, scopeToLanguage);
        }
      },
      inspect: (key) => {
        key = section ? `${section}.${key}` : key;
        const config2 = this.e.inspect(key, overrides, this.c.workspace);
        if (config2) {
          return {
            key,
            defaultValue: $Lv(config2.policy?.value ?? config2.default?.value),
            globalValue: $Lv(config2.user?.value ?? config2.application?.value),
            workspaceValue: $Lv(config2.workspace?.value),
            workspaceFolderValue: $Lv(config2.workspaceFolder?.value),
            defaultLanguageValue: $Lv(config2.default?.override),
            globalLanguageValue: $Lv(config2.user?.override ?? config2.application?.override),
            workspaceLanguageValue: $Lv(config2.workspace?.override),
            workspaceFolderLanguageValue: $Lv(config2.workspaceFolder?.override),
            languageIds: $Lv(config2.overrideIdentifiers)
          };
        }
        return void 0;
      }
    };
    if (typeof config === "object") {
      $Ov(result, config, false);
    }
    return Object.freeze(result);
  }
  g(result) {
    const readonlyProxy = (target) => {
      return $Bg(target) ? new Proxy(target, {
        get: (target2, property) => readonlyProxy(target2[property]),
        set: (_target, property, _value) => {
          throw new Error(`TypeError: Cannot assign to read only property '${String(property)}' of object`);
        },
        deleteProperty: (_target, property) => {
          throw new Error(`TypeError: Cannot delete read only property '${String(property)}' of object`);
        },
        defineProperty: (_target, property) => {
          throw new Error(`TypeError: Cannot define property '${String(property)}' for a readonly object`);
        },
        setPrototypeOf: (_target) => {
          throw new Error(`TypeError: Cannot set prototype for a readonly object`);
        },
        isExtensible: () => false,
        preventExtensions: () => true
      }) : target;
    };
    return readonlyProxy(result);
  }
  h(key, overrides, extensionId) {
    const scope = $Rt.test(key) ? 4 : this.d.get(key);
    const extensionIdText = extensionId ? `[${extensionId.value}] ` : "";
    if (4 === scope) {
      if (typeof overrides?.resource === "undefined") {
        this.f.warn(`${extensionIdText}Accessing a resource scoped configuration without providing a resource is not expected. To get the effective value for '${key}', provide the URI of a resource or 'null' for any resource.`);
      }
      return;
    }
    if (3 === scope) {
      if (overrides?.resource) {
        this.f.warn(`${extensionIdText}Accessing a window scoped configuration for a resource is not expected. To associate '${key}' to a resource, define its scope to 'resource' in configuration contributions in 'package.json'.`);
      }
      return;
    }
  }
  j(change, previous) {
    const event = new $XB(change, previous, this.e, this.c.workspace, this.f);
    return Object.freeze({
      affectsConfiguration: (section, scope) => event.affectsConfiguration(section, scopeToOverrides(scope))
    });
  }
  k(scopes) {
    return scopes.reduce((result, scope) => {
      result.set(scope[0], scope[1]);
      return result;
    }, /* @__PURE__ */ new Map());
  }
};
var $axc = $Qk("IExtHostConfiguration");

// out-build/vs/workbench/services/extensions/common/extensionDescriptionRegistry.js
var $hnc = class {
  constructor(versionId, removedDueToLooping) {
    this.versionId = versionId;
    this.removedDueToLooping = removedDueToLooping;
  }
};
var $inc = class _$inc {
  static isHostExtension(extensionId, myRegistry, globalRegistry) {
    if (myRegistry.getExtensionDescription(extensionId)) {
      return false;
    }
    const extensionDescription = globalRegistry.getExtensionDescription(extensionId);
    if (!extensionDescription) {
      return false;
    }
    if ((extensionDescription.main || extensionDescription.browser) && extensionDescription.api === "none") {
      return true;
    }
    return false;
  }
  constructor(j, extensionDescriptions) {
    this.j = j;
    this.c = new $ze();
    this.onDidChange = this.c.event;
    this.d = 0;
    this.e = extensionDescriptions;
    this.k();
  }
  k() {
    this.e.sort(extensionCmp);
    this.f = new $7z();
    this.g = [];
    this.h = /* @__PURE__ */ new Map();
    for (const extensionDescription of this.e) {
      if (this.f.has(extensionDescription.identifier)) {
        console.error("Extension `" + extensionDescription.identifier.value + "` is already registered");
        continue;
      }
      this.f.set(extensionDescription.identifier, extensionDescription);
      this.g.push(extensionDescription);
      const activationEvents = this.j.readActivationEvents(extensionDescription);
      for (const activationEvent of activationEvents) {
        if (!this.h.has(activationEvent)) {
          this.h.set(activationEvent, []);
        }
        this.h.get(activationEvent).push(extensionDescription);
      }
    }
  }
  set(extensionDescriptions) {
    this.e = extensionDescriptions;
    this.k();
    this.d++;
    this.c.fire(void 0);
    return {
      versionId: this.d
    };
  }
  deltaExtensions(toAdd, toRemove) {
    this.e = removeExtensions(this.e, toRemove);
    this.e = this.e.concat(toAdd);
    const looping = _$inc.l(this.e);
    this.e = removeExtensions(this.e, looping.map((ext) => ext.identifier));
    this.k();
    this.d++;
    this.c.fire(void 0);
    return new $hnc(this.d, looping);
  }
  static l(extensionDescriptions) {
    const G = new class {
      constructor() {
        this.c = /* @__PURE__ */ new Map();
        this.d = /* @__PURE__ */ new Set();
        this.e = [];
      }
      addNode(id2) {
        if (!this.d.has(id2)) {
          this.d.add(id2);
          this.e.push(id2);
        }
      }
      addArc(from, to) {
        this.addNode(from);
        this.addNode(to);
        if (this.c.has(from)) {
          this.c.get(from).push(to);
        } else {
          this.c.set(from, [to]);
        }
      }
      getArcs(id2) {
        if (this.c.has(id2)) {
          return this.c.get(id2);
        }
        return [];
      }
      hasOnlyGoodArcs(id2, good2) {
        const dependencies = G.getArcs(id2);
        for (let i = 0; i < dependencies.length; i++) {
          if (!good2.has(dependencies[i])) {
            return false;
          }
        }
        return true;
      }
      getNodes() {
        return this.e;
      }
    }();
    const descs = new $7z();
    for (const extensionDescription of extensionDescriptions) {
      descs.set(extensionDescription.identifier, extensionDescription);
      if (extensionDescription.extensionDependencies) {
        for (const depId of extensionDescription.extensionDependencies) {
          G.addArc($5z.toKey(extensionDescription.identifier), $5z.toKey(depId));
        }
      }
    }
    const good = /* @__PURE__ */ new Set();
    G.getNodes().filter((id2) => G.getArcs(id2).length === 0).forEach((id2) => good.add(id2));
    const nodes = G.getNodes().filter((id2) => !good.has(id2));
    let madeProgress;
    do {
      madeProgress = false;
      for (let i = 0; i < nodes.length; i++) {
        const id2 = nodes[i];
        if (G.hasOnlyGoodArcs(id2, good)) {
          nodes.splice(i, 1);
          i--;
          good.add(id2);
          madeProgress = true;
        }
      }
    } while (madeProgress);
    return nodes.map((id2) => descs.get(id2));
  }
  containsActivationEvent(activationEvent) {
    return this.h.has(activationEvent);
  }
  containsExtension(extensionId) {
    return this.f.has(extensionId);
  }
  getExtensionDescriptionsForActivationEvent(activationEvent) {
    const extensions = this.h.get(activationEvent);
    return extensions ? extensions.slice(0) : [];
  }
  getAllExtensionDescriptions() {
    return this.g.slice(0);
  }
  getSnapshot() {
    return new $jnc(this.d, this.getAllExtensionDescriptions());
  }
  getExtensionDescription(extensionId) {
    const extension = this.f.get(extensionId);
    return extension ? extension : void 0;
  }
  getExtensionDescriptionByUUID(uuid) {
    for (const extensionDescription of this.g) {
      if (extensionDescription.uuid === uuid) {
        return extensionDescription;
      }
    }
    return void 0;
  }
  getExtensionDescriptionByIdOrUUID(extensionId, uuid) {
    return this.getExtensionDescription(extensionId) ?? (uuid ? this.getExtensionDescriptionByUUID(uuid) : void 0);
  }
};
var $jnc = class {
  constructor(versionId, extensions) {
    this.versionId = versionId;
    this.extensions = extensions;
  }
};
var SortBucket;
(function(SortBucket2) {
  SortBucket2[SortBucket2["Builtin"] = 0] = "Builtin";
  SortBucket2[SortBucket2["User"] = 1] = "User";
  SortBucket2[SortBucket2["Dev"] = 2] = "Dev";
})(SortBucket || (SortBucket = {}));
function extensionCmp(a, b) {
  const aSortBucket = a.isBuiltin ? 0 : a.isUnderDevelopment ? 2 : 1;
  const bSortBucket = b.isBuiltin ? 0 : b.isUnderDevelopment ? 2 : 1;
  if (aSortBucket !== bSortBucket) {
    return aSortBucket - bSortBucket;
  }
  const aLastSegment = $kc.basename(a.extensionLocation.path);
  const bLastSegment = $kc.basename(b.extensionLocation.path);
  if (aLastSegment < bLastSegment) {
    return -1;
  }
  if (aLastSegment > bLastSegment) {
    return 1;
  }
  return 0;
}
function removeExtensions(arr, toRemove) {
  const toRemoveSet = new $6z(toRemove);
  return arr.filter((extension) => !toRemoveSet.has(extension.identifier));
}

// out-build/vs/platform/extensionManagement/common/extensionManagement.js
var $cA = "^([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$";
var $dA = new RegExp($cA);
var ExtensionInstallSource;
(function(ExtensionInstallSource2) {
  ExtensionInstallSource2["COMMAND"] = "command";
  ExtensionInstallSource2["SETTINGS_SYNC"] = "settingsSync";
})(ExtensionInstallSource || (ExtensionInstallSource = {}));
var SortBy;
(function(SortBy2) {
  SortBy2[SortBy2["NoneOrRelevance"] = 0] = "NoneOrRelevance";
  SortBy2[SortBy2["LastUpdatedDate"] = 1] = "LastUpdatedDate";
  SortBy2[SortBy2["Title"] = 2] = "Title";
  SortBy2[SortBy2["PublisherName"] = 3] = "PublisherName";
  SortBy2[SortBy2["InstallCount"] = 4] = "InstallCount";
  SortBy2[SortBy2["PublishedDate"] = 10] = "PublishedDate";
  SortBy2[SortBy2["AverageRating"] = 6] = "AverageRating";
  SortBy2[SortBy2["WeightedRating"] = 12] = "WeightedRating";
})(SortBy || (SortBy = {}));
var SortOrder;
(function(SortOrder2) {
  SortOrder2[SortOrder2["Default"] = 0] = "Default";
  SortOrder2[SortOrder2["Ascending"] = 1] = "Ascending";
  SortOrder2[SortOrder2["Descending"] = 2] = "Descending";
})(SortOrder || (SortOrder = {}));
var StatisticType;
(function(StatisticType2) {
  StatisticType2["Install"] = "install";
  StatisticType2["Uninstall"] = "uninstall";
})(StatisticType || (StatisticType = {}));
var InstallOperation;
(function(InstallOperation2) {
  InstallOperation2[InstallOperation2["None"] = 1] = "None";
  InstallOperation2[InstallOperation2["Install"] = 2] = "Install";
  InstallOperation2[InstallOperation2["Update"] = 3] = "Update";
  InstallOperation2[InstallOperation2["Migrate"] = 4] = "Migrate";
})(InstallOperation || (InstallOperation = {}));
var $pA = $Qk("extensionGalleryService");
var ExtensionGalleryErrorCode;
(function(ExtensionGalleryErrorCode2) {
  ExtensionGalleryErrorCode2["Timeout"] = "Timeout";
  ExtensionGalleryErrorCode2["Cancelled"] = "Cancelled";
  ExtensionGalleryErrorCode2["Failed"] = "Failed";
  ExtensionGalleryErrorCode2["DownloadFailedWriting"] = "DownloadFailedWriting";
  ExtensionGalleryErrorCode2["Offline"] = "Offline";
})(ExtensionGalleryErrorCode || (ExtensionGalleryErrorCode = {}));
var ExtensionManagementErrorCode;
(function(ExtensionManagementErrorCode2) {
  ExtensionManagementErrorCode2["Unsupported"] = "Unsupported";
  ExtensionManagementErrorCode2["Deprecated"] = "Deprecated";
  ExtensionManagementErrorCode2["Malicious"] = "Malicious";
  ExtensionManagementErrorCode2["Incompatible"] = "Incompatible";
  ExtensionManagementErrorCode2["IncompatibleApi"] = "IncompatibleApi";
  ExtensionManagementErrorCode2["IncompatibleTargetPlatform"] = "IncompatibleTargetPlatform";
  ExtensionManagementErrorCode2["ReleaseVersionNotFound"] = "ReleaseVersionNotFound";
  ExtensionManagementErrorCode2["Invalid"] = "Invalid";
  ExtensionManagementErrorCode2["Download"] = "Download";
  ExtensionManagementErrorCode2["DownloadSignature"] = "DownloadSignature";
  ExtensionManagementErrorCode2["DownloadFailedWriting"] = "DownloadFailedWriting";
  ExtensionManagementErrorCode2["UpdateMetadata"] = "UpdateMetadata";
  ExtensionManagementErrorCode2["Extract"] = "Extract";
  ExtensionManagementErrorCode2["Scanning"] = "Scanning";
  ExtensionManagementErrorCode2["ScanningExtension"] = "ScanningExtension";
  ExtensionManagementErrorCode2["ReadUninstalled"] = "ReadUninstalled";
  ExtensionManagementErrorCode2["UnsetUninstalled"] = "UnsetUninstalled";
  ExtensionManagementErrorCode2["Delete"] = "Delete";
  ExtensionManagementErrorCode2["Rename"] = "Rename";
  ExtensionManagementErrorCode2["IntializeDefaultProfile"] = "IntializeDefaultProfile";
  ExtensionManagementErrorCode2["AddToProfile"] = "AddToProfile";
  ExtensionManagementErrorCode2["InstalledExtensionNotFound"] = "InstalledExtensionNotFound";
  ExtensionManagementErrorCode2["PostInstall"] = "PostInstall";
  ExtensionManagementErrorCode2["CorruptZip"] = "CorruptZip";
  ExtensionManagementErrorCode2["IncompleteZip"] = "IncompleteZip";
  ExtensionManagementErrorCode2["PackageNotSigned"] = "PackageNotSigned";
  ExtensionManagementErrorCode2["SignatureVerificationInternal"] = "SignatureVerificationInternal";
  ExtensionManagementErrorCode2["SignatureVerificationFailed"] = "SignatureVerificationFailed";
  ExtensionManagementErrorCode2["NotAllowed"] = "NotAllowed";
  ExtensionManagementErrorCode2["Gallery"] = "Gallery";
  ExtensionManagementErrorCode2["Cancelled"] = "Cancelled";
  ExtensionManagementErrorCode2["Unknown"] = "Unknown";
  ExtensionManagementErrorCode2["Internal"] = "Internal";
})(ExtensionManagementErrorCode || (ExtensionManagementErrorCode = {}));
var ExtensionSignatureVerificationCode;
(function(ExtensionSignatureVerificationCode2) {
  ExtensionSignatureVerificationCode2["NotSigned"] = "NotSigned";
  ExtensionSignatureVerificationCode2["Success"] = "Success";
  ExtensionSignatureVerificationCode2["RequiredArgumentMissing"] = "RequiredArgumentMissing";
  ExtensionSignatureVerificationCode2["InvalidArgument"] = "InvalidArgument";
  ExtensionSignatureVerificationCode2["PackageIsUnreadable"] = "PackageIsUnreadable";
  ExtensionSignatureVerificationCode2["UnhandledException"] = "UnhandledException";
  ExtensionSignatureVerificationCode2["SignatureManifestIsMissing"] = "SignatureManifestIsMissing";
  ExtensionSignatureVerificationCode2["SignatureManifestIsUnreadable"] = "SignatureManifestIsUnreadable";
  ExtensionSignatureVerificationCode2["SignatureIsMissing"] = "SignatureIsMissing";
  ExtensionSignatureVerificationCode2["SignatureIsUnreadable"] = "SignatureIsUnreadable";
  ExtensionSignatureVerificationCode2["CertificateIsUnreadable"] = "CertificateIsUnreadable";
  ExtensionSignatureVerificationCode2["SignatureArchiveIsUnreadable"] = "SignatureArchiveIsUnreadable";
  ExtensionSignatureVerificationCode2["FileAlreadyExists"] = "FileAlreadyExists";
  ExtensionSignatureVerificationCode2["SignatureArchiveIsInvalidZip"] = "SignatureArchiveIsInvalidZip";
  ExtensionSignatureVerificationCode2["SignatureArchiveHasSameSignatureFile"] = "SignatureArchiveHasSameSignatureFile";
  ExtensionSignatureVerificationCode2["PackageIntegrityCheckFailed"] = "PackageIntegrityCheckFailed";
  ExtensionSignatureVerificationCode2["SignatureIsInvalid"] = "SignatureIsInvalid";
  ExtensionSignatureVerificationCode2["SignatureManifestIsInvalid"] = "SignatureManifestIsInvalid";
  ExtensionSignatureVerificationCode2["SignatureIntegrityCheckFailed"] = "SignatureIntegrityCheckFailed";
  ExtensionSignatureVerificationCode2["EntryIsMissing"] = "EntryIsMissing";
  ExtensionSignatureVerificationCode2["EntryIsTampered"] = "EntryIsTampered";
  ExtensionSignatureVerificationCode2["Untrusted"] = "Untrusted";
  ExtensionSignatureVerificationCode2["CertificateRevoked"] = "CertificateRevoked";
  ExtensionSignatureVerificationCode2["SignatureIsNotValid"] = "SignatureIsNotValid";
  ExtensionSignatureVerificationCode2["UnknownError"] = "UnknownError";
  ExtensionSignatureVerificationCode2["PackageIsInvalidZip"] = "PackageIsInvalidZip";
  ExtensionSignatureVerificationCode2["SignatureArchiveHasTooManyEntries"] = "SignatureArchiveHasTooManyEntries";
})(ExtensionSignatureVerificationCode || (ExtensionSignatureVerificationCode = {}));
var $sA = $Qk("extensionManagementService");
var $vA = $Qk("IGlobalExtensionEnablementService");
var $wA = $Qk("IExtensionTipsService");
var $xA = $Qk("IAllowedExtensionsService");
var $zA = localize2(1820, "Extensions");
var $AA = localize2(1821, "Preferences");

// out-build/vs/platform/telemetry/common/telemetry.js
var $zv = $Qk("telemetryService");
var $Av = $Qk("customEndpointTelemetryService");
var TelemetryLevel;
(function(TelemetryLevel2) {
  TelemetryLevel2[TelemetryLevel2["NONE"] = 0] = "NONE";
  TelemetryLevel2[TelemetryLevel2["CRASH"] = 1] = "CRASH";
  TelemetryLevel2[TelemetryLevel2["ERROR"] = 2] = "ERROR";
  TelemetryLevel2[TelemetryLevel2["USAGE"] = 3] = "USAGE";
})(TelemetryLevel || (TelemetryLevel = {}));
var TelemetryConfiguration;
(function(TelemetryConfiguration2) {
  TelemetryConfiguration2["OFF"] = "off";
  TelemetryConfiguration2["CRASH"] = "crash";
  TelemetryConfiguration2["ERROR"] = "error";
  TelemetryConfiguration2["ON"] = "all";
})(TelemetryConfiguration || (TelemetryConfiguration = {}));

// out-build/vs/platform/telemetry/common/telemetryUtils.js
var $bw = class {
  constructor(value) {
    this.value = value;
    this.isTrustedTelemetryValue = true;
  }
};
var $cw = class {
  constructor() {
    this.telemetryLevel = 0;
    this.sessionId = "someValue.sessionId";
    this.machineId = "someValue.machineId";
    this.sqmId = "someValue.sqmId";
    this.devDeviceId = "someValue.devDeviceId";
    this.firstSessionDate = "someValue.firstSessionDate";
    this.sendErrorTelemetry = false;
  }
  publicLog() {
  }
  publicLog2() {
  }
  publicLogError() {
  }
  publicLogError2() {
  }
  setExperimentProperty() {
  }
};
var $dw = new $cw();
var $gw = "extensionTelemetryLog";
var telemetryAllowedAuthorities = /* @__PURE__ */ new Set(["ssh-remote", "dev-container", "attached-container", "wsl", "tunnel", "codespaces", "amlext"]);
function $mw(remoteAuthority) {
  if (!remoteAuthority) {
    return "none";
  }
  const remoteName = $9v(remoteAuthority);
  return telemetryAllowedAuthorities.has(remoteName) ? remoteName : "other";
}
function anonymizeFilePaths(stack, cleanupPatterns) {
  if (!stack || !stack.includes("/") && !stack.includes("\\")) {
    return stack;
  }
  let updatedStack = stack;
  const cleanUpIndexes = [];
  for (const regexp of cleanupPatterns) {
    while (true) {
      const result = regexp.exec(stack);
      if (!result) {
        break;
      }
      cleanUpIndexes.push([result.index, regexp.lastIndex]);
    }
  }
  const nodeModulesRegex = /^[\\\/]?(node_modules|node_modules\.asar)[\\\/]/;
  const fileRegex = /(file:\/\/)?([a-zA-Z]:(\\\\|\\|\/)|(\\\\|\\|\/))?([\w-\._]+(\\\\|\\|\/))+[\w-\._]*/g;
  let lastIndex = 0;
  updatedStack = "";
  while (true) {
    const result = fileRegex.exec(stack);
    if (!result) {
      break;
    }
    const overlappingRange = cleanUpIndexes.some(([start, end]) => result.index < end && start < fileRegex.lastIndex);
    if (!nodeModulesRegex.test(result[0]) && !overlappingRange) {
      updatedStack += stack.substring(lastIndex, result.index) + "<REDACTED: user-file-path>";
      lastIndex = fileRegex.lastIndex;
    }
  }
  if (lastIndex < stack.length) {
    updatedStack += stack.substr(lastIndex);
  }
  return updatedStack;
}
function removePropertiesWithPossibleUserInfo(property) {
  if (!property) {
    return property;
  }
  const userDataRegexes = [
    { label: "Google API Key", regex: /AIza[A-Za-z0-9_\\\-]{35}/ },
    { label: "Slack Token", regex: /xox[pbar]\-[A-Za-z0-9]/ },
    { label: "GitHub Token", regex: /(gh[psuro]_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})/ },
    { label: "Generic Secret", regex: /(key|token|sig|secret|signature|password|passwd|pwd|android:value)[^a-zA-Z0-9]/i },
    { label: "CLI Credentials", regex: /((login|psexec|(certutil|psexec)\.exe).{1,50}(\s-u(ser(name)?)?\s+.{3,100})?\s-(admin|user|vm|root)?p(ass(word)?)?\s+["']?[^$\-\/\s]|(^|[\s\r\n\\])net(\.exe)?.{1,5}(user\s+|share\s+\/user:| user -? secrets ? set) \s + [^ $\s \/])/ },
    { label: "Microsoft Entra ID", regex: /eyJ(?:0eXAiOiJKV1Qi|hbGci|[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.)/ },
    { label: "Email", regex: /@[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+/ }
    // Regex which matches @*.site
  ];
  for (const secretRegex of userDataRegexes) {
    if (secretRegex.regex.test(property)) {
      return `<REDACTED: ${secretRegex.label}>`;
    }
  }
  return property;
}
function $pw(data, cleanUpPatterns) {
  return $Nv(data, (value) => {
    if (value instanceof $bw || Object.hasOwnProperty.call(value, "isTrustedTelemetryValue")) {
      return value.value;
    }
    if (typeof value === "string") {
      let updatedProperty = value.replaceAll("%20", " ");
      updatedProperty = anonymizeFilePaths(updatedProperty, cleanUpPatterns);
      for (const regexp of cleanUpPatterns) {
        updatedProperty = updatedProperty.replace(regexp, "");
      }
      updatedProperty = removePropertiesWithPossibleUserInfo(updatedProperty);
      return updatedProperty;
    }
    return void 0;
  });
}

// out-build/vs/platform/extensionManagement/common/extensionManagementUtil.js
var $MA = new $5z("pprice.better-merge");

// out-build/vs/platform/extensionManagement/common/implicitActivationEvents.js
var $eN = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new WeakMap();
  }
  register(extensionPointName, generator) {
    this.a.set(extensionPointName, generator);
  }
  /**
   * This can run correctly only on the renderer process because that is the only place
   * where all extension points and all implicit activation events generators are known.
   */
  readActivationEvents(extensionDescription) {
    if (!this.b.has(extensionDescription)) {
      this.b.set(extensionDescription, this.c(extensionDescription));
    }
    return this.b.get(extensionDescription);
  }
  /**
   * This can run correctly only on the renderer process because that is the only place
   * where all extension points and all implicit activation events generators are known.
   */
  createActivationEventsMap(extensionDescriptions) {
    const result = /* @__PURE__ */ Object.create(null);
    for (const extensionDescription of extensionDescriptions) {
      const activationEvents = this.readActivationEvents(extensionDescription);
      if (activationEvents.length > 0) {
        result[$5z.toKey(extensionDescription.identifier)] = activationEvents;
      }
    }
    return result;
  }
  c(desc) {
    if (typeof desc.main === "undefined" && typeof desc.browser === "undefined") {
      return [];
    }
    const activationEvents = Array.isArray(desc.activationEvents) ? desc.activationEvents.slice(0) : [];
    for (let i = 0; i < activationEvents.length; i++) {
      if (activationEvents[i] === "onUri") {
        activationEvents[i] = `onUri:${$5z.toKey(desc.identifier)}`;
      }
    }
    if (!desc.contributes) {
      return activationEvents;
    }
    for (const extPointName in desc.contributes) {
      const generator = this.a.get(extPointName);
      if (!generator) {
        continue;
      }
      const contrib = desc.contributes[extPointName];
      const contribArr = Array.isArray(contrib) ? contrib : [contrib];
      try {
        generator(contribArr, activationEvents);
      } catch (err) {
        $gb(err);
      }
    }
    return activationEvents;
  }
};
var $fN = new $eN();

// out-build/vs/workbench/services/extensions/common/extensions.js
var $uN = Object.freeze({
  identifier: new $5z("nullExtensionDescription"),
  name: "Null Extension Description",
  version: "0.0.0",
  publisher: "vscode",
  engines: { vscode: "" },
  extensionLocation: URI.parse("void:location"),
  isBuiltin: false,
  targetPlatform: "undefined",
  isUserBuiltin: false,
  isUnderDevelopment: false,
  preRelease: false
});
var $wN = $Qk("extensionService");
var $xN = class {
  constructor(dependency) {
    this.dependency = dependency;
  }
};
var ExtensionHostStartup;
(function(ExtensionHostStartup2) {
  ExtensionHostStartup2[ExtensionHostStartup2["EagerAutoStart"] = 1] = "EagerAutoStart";
  ExtensionHostStartup2[ExtensionHostStartup2["EagerManualStart"] = 2] = "EagerManualStart";
  ExtensionHostStartup2[ExtensionHostStartup2["Lazy"] = 3] = "Lazy";
})(ExtensionHostStartup || (ExtensionHostStartup = {}));
function $zN(extension, proposal) {
  return true;
}
function $AN(extension, proposal) {
  if (!$zN(extension, proposal)) {
    throw new Error(`Extension '${extension.identifier.value}' CANNOT use API proposal: ${proposal}.
Its package.json#enabledApiProposals-property declares: ${extension.enabledApiProposals?.join(", ") ?? "[]"} but NOT ${proposal}.
 The missing proposal MUST be added and you must start in extension development mode or use the following command line switch: --enable-proposed-api ${extension.identifier.value}`);
  }
}
var ActivationKind;
(function(ActivationKind2) {
  ActivationKind2[ActivationKind2["Normal"] = 0] = "Normal";
  ActivationKind2[ActivationKind2["Immediate"] = 1] = "Immediate";
})(ActivationKind || (ActivationKind = {}));

// out-build/vs/workbench/api/common/extHostExtensionActivator.js
var $oxc = class _$oxc {
  static {
    this.NONE = new _$oxc(false, -1, -1, -1);
  }
  constructor(startup, codeLoadingTime, activateCallTime, activateResolvedTime) {
    this.startup = startup;
    this.codeLoadingTime = codeLoadingTime;
    this.activateCallTime = activateCallTime;
    this.activateResolvedTime = activateResolvedTime;
  }
};
var $pxc = class {
  constructor(startup) {
    this.a = startup;
    this.b = -1;
    this.c = -1;
    this.d = -1;
    this.f = -1;
    this.g = -1;
    this.h = -1;
  }
  j(start, stop) {
    if (start === -1 || stop === -1) {
      return -1;
    }
    return stop - start;
  }
  build() {
    return new $oxc(this.a, this.j(this.b, this.c), this.j(this.d, this.f), this.j(this.g, this.h));
  }
  codeLoadingStart() {
    this.b = Date.now();
  }
  codeLoadingStop() {
    this.c = Date.now();
  }
  activateCallStart() {
    this.d = Date.now();
  }
  activateCallStop() {
    this.f = Date.now();
  }
  activateResolveStart() {
    this.g = Date.now();
  }
  activateResolveStop() {
    this.h = Date.now();
  }
};
var $qxc = class {
  constructor(activationFailed, activationFailedError, activationTimes, module2, exports2, disposable) {
    this.activationFailed = activationFailed;
    this.activationFailedError = activationFailedError;
    this.activationTimes = activationTimes;
    this.module = module2;
    this.exports = exports2;
    this.disposable = disposable;
  }
};
var $rxc = class extends $qxc {
  constructor(activationTimes) {
    super(false, null, activationTimes, { activate: void 0, deactivate: void 0 }, void 0, $3c.None);
  }
};
var $sxc = class extends $qxc {
  constructor() {
    super(false, null, $oxc.NONE, { activate: void 0, deactivate: void 0 }, void 0, $3c.None);
  }
};
var FailedExtension = class extends $qxc {
  constructor(activationError) {
    super(true, activationError, $oxc.NONE, { activate: void 0, deactivate: void 0 }, void 0, $3c.None);
  }
};
var $txc = class $txc2 {
  constructor(registry, globalRegistry, host, g) {
    this.g = g;
    this.a = registry;
    this.b = globalRegistry;
    this.c = host;
    this.d = new $7z();
    this.f = /* @__PURE__ */ Object.create(null);
  }
  dispose() {
    for (const [_, op] of this.d) {
      op.dispose();
    }
  }
  async waitForActivatingExtensions() {
    const res = [];
    for (const [_, op] of this.d) {
      res.push(op.wait());
    }
    await Promise.all(res);
  }
  isActivated(extensionId) {
    const op = this.d.get(extensionId);
    return Boolean(op && op.value);
  }
  getActivatedExtension(extensionId) {
    const op = this.d.get(extensionId);
    if (!op || !op.value) {
      throw new Error(`Extension '${extensionId.value}' is not known or not activated`);
    }
    return op.value;
  }
  async activateByEvent(activationEvent, startup) {
    if (this.f[activationEvent]) {
      return;
    }
    const activateExtensions = this.a.getExtensionDescriptionsForActivationEvent(activationEvent);
    await this.h(activateExtensions.map((e) => ({
      id: e.identifier,
      reason: { startup, extensionId: e.identifier, activationEvent }
    })));
    this.f[activationEvent] = true;
  }
  activateById(extensionId, reason) {
    const desc = this.a.getExtensionDescription(extensionId);
    if (!desc) {
      throw new Error(`Extension '${extensionId.value}' is not known`);
    }
    return this.h([{ id: desc.identifier, reason }]);
  }
  async h(extensions) {
    const operations = extensions.filter((p) => !this.isActivated(p.id)).map((ext) => this.j(ext));
    await Promise.all(operations.map((op) => op.wait()));
  }
  /**
   * Handle semantics related to dependencies for `currentExtension`.
   * We don't need to worry about dependency loops because they are handled by the registry.
   */
  j(currentActivation) {
    if (this.d.has(currentActivation.id)) {
      return this.d.get(currentActivation.id);
    }
    if (this.l(currentActivation.id)) {
      return this.k(currentActivation, null, [], null);
    }
    const currentExtension = this.a.getExtensionDescription(currentActivation.id);
    if (!currentExtension) {
      const error = new Error(`Cannot activate unknown extension '${currentActivation.id.value}'`);
      const result = this.k(currentActivation, null, [], new FailedExtension(error));
      this.c.onExtensionActivationError(currentActivation.id, error, new $xN(currentActivation.id.value));
      return result;
    }
    const deps = [];
    const depIds = typeof currentExtension.extensionDependencies === "undefined" ? [] : currentExtension.extensionDependencies;
    for (const depId of depIds) {
      if (this.m(depId)) {
        continue;
      }
      const dep = this.d.get(depId);
      if (dep) {
        deps.push(dep);
        continue;
      }
      if (this.l(depId)) {
        deps.push(this.j({
          id: this.b.getExtensionDescription(depId).identifier,
          reason: currentActivation.reason
        }));
        continue;
      }
      const depDesc = this.a.getExtensionDescription(depId);
      if (depDesc) {
        if (!depDesc.main && !depDesc.browser) {
          continue;
        }
        deps.push(this.j({
          id: depDesc.identifier,
          reason: currentActivation.reason
        }));
        continue;
      }
      const currentExtensionFriendlyName = currentExtension.displayName || currentExtension.identifier.value;
      const error = new Error(`Cannot activate the '${currentExtensionFriendlyName}' extension because it depends on unknown extension '${depId}'`);
      const result = this.k(currentActivation, currentExtension.displayName, [], new FailedExtension(error));
      this.c.onExtensionActivationError(currentExtension.identifier, error, new $xN(depId));
      return result;
    }
    return this.k(currentActivation, currentExtension.displayName, deps, null);
  }
  k(activation, displayName, deps, value) {
    const operation = new ActivationOperation(activation.id, displayName, activation.reason, deps, value, this.c, this.g);
    this.d.set(activation.id, operation);
    return operation;
  }
  l(extensionId) {
    return $inc.isHostExtension(extensionId, this.a, this.b);
  }
  m(extensionId) {
    const extensionDescription = this.b.getExtensionDescription(extensionId);
    if (!extensionDescription) {
      return false;
    }
    return !extensionDescription.main && !extensionDescription.browser;
  }
};
$txc = __decorate([
  __param(3, $wn)
], $txc);
var ActivationOperation = class ActivationOperation2 {
  get value() {
    return this.h;
  }
  get friendlyName() {
    return this.d || this.c.value;
  }
  constructor(c, d, f, g, h, j, k) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.k = k;
    this.a = new $Uh();
    this.b = false;
    this.l();
  }
  dispose() {
    this.b = true;
  }
  wait() {
    return this.a.wait();
  }
  async l() {
    await this.m();
    this.a.open();
  }
  async m() {
    if (this.h) {
      return;
    }
    while (this.g.length > 0) {
      for (let i = 0; i < this.g.length; i++) {
        const dep = this.g[i];
        if (dep.value && !dep.value.activationFailed) {
          this.g.splice(i, 1);
          i--;
          continue;
        }
        if (dep.value && dep.value.activationFailed) {
          const error = new Error(`Cannot activate the '${this.friendlyName}' extension because its dependency '${dep.friendlyName}' failed to activate`);
          error.detail = dep.value.activationFailedError;
          this.h = new FailedExtension(error);
          this.j.onExtensionActivationError(this.c, error, null);
          return;
        }
      }
      if (this.g.length > 0) {
        await Promise.race(this.g.map((dep) => dep.wait()));
      }
    }
    await this.n();
  }
  async n() {
    try {
      this.h = await this.j.actualActivateExtension(this.c, this.f);
    } catch (err) {
      const error = new Error();
      if (err && err.name) {
        error.name = err.name;
      }
      if (err && err.message) {
        error.message = `Activating extension '${this.c.value}' failed: ${err.message}.`;
      } else {
        error.message = `Activating extension '${this.c.value}' failed: ${err}.`;
      }
      if (err && err.stack) {
        error.stack = err.stack;
      }
      this.h = new FailedExtension(error);
      if (this.b && $kb(err)) {
        return;
      }
      this.j.onExtensionActivationError(this.c, error, null);
      this.k.error(`Activating extension ${this.c.value} failed due to an error:`);
      this.k.error(err);
    }
  }
};
ActivationOperation = __decorate([
  __param(6, $wn)
], ActivationOperation);

// out-build/vs/workbench/api/common/extHostStorage.js
var $uxc = class {
  constructor(mainContext, c) {
    this.c = c;
    this.b = new $ze();
    this.onDidChangeStorage = this.b.event;
    this.a = mainContext.getProxy($xT.MainThreadStorage);
  }
  registerExtensionStorageKeysToSync(extension, keys) {
    this.a.$registerExtensionStorageKeysToSync(extension, keys);
  }
  async initializeExtensionStorage(shared, key, defaultValue) {
    const value = await this.a.$initializeExtensionStorage(shared, key);
    let parsedValue;
    if (value) {
      parsedValue = this.d(shared, key, value);
    }
    return parsedValue || defaultValue;
  }
  setValue(shared, key, value) {
    return this.a.$setValue(shared, key, value);
  }
  $acceptValue(shared, key, value) {
    const parsedValue = this.d(shared, key, value);
    if (parsedValue) {
      this.b.fire({ shared, key, value: parsedValue });
    }
  }
  d(shared, key, value) {
    try {
      return JSON.parse(value);
    } catch (error) {
      this.c.error(`[extHostStorage] unexpected error parsing storage contents (extensionId: ${key}, global: ${shared}): ${error}`);
    }
    return void 0;
  }
};
var $vxc = $Qk("IExtHostStorage");

// out-build/vs/workbench/api/common/extHostMemento.js
var $wxc = class {
  constructor(id2, global2, storage) {
    this.h = /* @__PURE__ */ new Map();
    this.a = id2;
    this.b = global2;
    this.c = storage;
    this.d = this.c.initializeExtensionStorage(this.b, this.a, /* @__PURE__ */ Object.create(null)).then((value) => {
      this.f = value;
      return this;
    });
    this.g = this.c.onDidChangeStorage((e) => {
      if (e.shared === this.b && e.key === this.a) {
        this.f = e.value;
      }
    });
    this.i = new $8h(() => {
      const records = this.h;
      this.h = /* @__PURE__ */ new Map();
      (async () => {
        try {
          await this.c.setValue(this.b, this.a, this.f);
          for (const value of records.values()) {
            value.complete();
          }
        } catch (e) {
          for (const value of records.values()) {
            value.error(e);
          }
        }
      })();
    }, 0);
  }
  keys() {
    return Object.entries(this.f ?? {}).filter(([, value]) => value !== void 0).map(([key]) => key);
  }
  get whenReady() {
    return this.d;
  }
  get(key, defaultValue) {
    let value = this.f[key];
    if (typeof value === "undefined") {
      value = defaultValue;
    }
    return value;
  }
  update(key, value) {
    this.f[key] = value;
    const record = this.h.get(key);
    if (record !== void 0) {
      return record.p;
    }
    const promise = new $gi();
    this.h.set(key, promise);
    if (!this.i.isScheduled()) {
      this.i.schedule();
    }
    return promise.p;
  }
  dispose() {
    this.g.dispose();
  }
};
var $xxc = class extends $wxc {
  setKeysForSync(keys) {
    this.c.registerExtensionStorageKeysToSync({ id: this.a, version: this.j.version }, keys);
  }
  constructor(extensionDescription, storage) {
    super(extensionDescription.identifier.value, true, storage);
    this.j = extensionDescription;
  }
};

// out-build/vs/workbench/api/common/extHostFileSystemConsumer.js
var $bxc_1;
var $bxc = $bxc_1 = class $bxc2 {
  constructor(extHostRpc, fileSystemInfo) {
    this.b = /* @__PURE__ */ new Map();
    this.c = new $5h();
    this.a = extHostRpc.getProxy($xT.MainThreadFileSystem);
    const that = this;
    this.value = Object.freeze({
      async stat(uri) {
        try {
          let stat2;
          const provider = that.b.get(uri.scheme);
          if (provider) {
            await that.a.$ensureActivation(uri.scheme);
            stat2 = await provider.impl.stat(uri);
          } else {
            stat2 = await that.a.$stat(uri);
          }
          return {
            type: stat2.type,
            ctime: stat2.ctime,
            mtime: stat2.mtime,
            size: stat2.size,
            permissions: stat2.permissions === FilePermission.Readonly ? 1 : void 0
          };
        } catch (err) {
          $bxc_1.e(err);
        }
      },
      async readDirectory(uri) {
        try {
          const provider = that.b.get(uri.scheme);
          if (provider) {
            await that.a.$ensureActivation(uri.scheme);
            return (await provider.impl.readDirectory(uri)).slice();
          } else {
            return await that.a.$readdir(uri);
          }
        } catch (err) {
          return $bxc_1.e(err);
        }
      },
      async createDirectory(uri) {
        try {
          const provider = that.b.get(uri.scheme);
          if (provider && !provider.isReadonly) {
            await that.a.$ensureActivation(uri.scheme);
            return await that.d(provider.impl, provider.extUri, uri);
          } else {
            return await that.a.$mkdir(uri);
          }
        } catch (err) {
          return $bxc_1.e(err);
        }
      },
      async readFile(uri) {
        try {
          const provider = that.b.get(uri.scheme);
          if (provider) {
            await that.a.$ensureActivation(uri.scheme);
            return (await provider.impl.readFile(uri)).slice();
          } else {
            const buff = await that.a.$readFile(uri);
            return buff.buffer;
          }
        } catch (err) {
          return $bxc_1.e(err);
        }
      },
      async writeFile(uri, content) {
        try {
          const provider = that.b.get(uri.scheme);
          if (provider && !provider.isReadonly) {
            await that.a.$ensureActivation(uri.scheme);
            await that.d(provider.impl, provider.extUri, provider.extUri.dirname(uri));
            return await that.c.queueFor(uri, () => Promise.resolve(provider.impl.writeFile(uri, content, { create: true, overwrite: true })));
          } else {
            return await that.a.$writeFile(uri, $Ci.wrap(content));
          }
        } catch (err) {
          return $bxc_1.e(err);
        }
      },
      async delete(uri, options2) {
        try {
          const provider = that.b.get(uri.scheme);
          if (provider && !provider.isReadonly && !options2?.useTrash) {
            await that.a.$ensureActivation(uri.scheme);
            return await provider.impl.delete(uri, { recursive: false, ...options2 });
          } else {
            return await that.a.$delete(uri, { recursive: false, useTrash: false, atomic: false, ...options2 });
          }
        } catch (err) {
          return $bxc_1.e(err);
        }
      },
      async rename(oldUri, newUri, options2) {
        try {
          return await that.a.$rename(oldUri, newUri, { ...{ overwrite: false }, ...options2 });
        } catch (err) {
          return $bxc_1.e(err);
        }
      },
      async copy(source, destination, options2) {
        try {
          return await that.a.$copy(source, destination, { ...{ overwrite: false }, ...options2 });
        } catch (err) {
          return $bxc_1.e(err);
        }
      },
      isWritableFileSystem(scheme) {
        const capabilities = fileSystemInfo.getCapabilities(scheme);
        if (typeof capabilities === "number") {
          return !(capabilities & 2048);
        }
        return void 0;
      }
    });
  }
  async d(provider, providerExtUri, directory) {
    const directoriesToCreate = [];
    while (!providerExtUri.isEqual(directory, providerExtUri.dirname(directory))) {
      try {
        const stat2 = await provider.stat(directory);
        if ((stat2.type & FileType.Directory) === 0) {
          throw $UU.FileExists(`Unable to create folder '${directory.scheme === Schemas.file ? directory.fsPath : directory.toString(true)}' that already exists but is not a directory`);
        }
        break;
      } catch (error) {
        if ($Am(error) !== FileSystemProviderErrorCode.FileNotFound) {
          throw error;
        }
        directoriesToCreate.push(providerExtUri.basename(directory));
        directory = providerExtUri.dirname(directory);
      }
    }
    for (let i = directoriesToCreate.length - 1; i >= 0; i--) {
      directory = providerExtUri.joinPath(directory, directoriesToCreate[i]);
      try {
        await provider.createDirectory(directory);
      } catch (error) {
        if ($Am(error) !== FileSystemProviderErrorCode.FileExists) {
          throw error;
        }
      }
    }
  }
  static e(err) {
    if (err instanceof $UU) {
      throw err;
    }
    if (err instanceof $wm) {
      switch (err.code) {
        case FileSystemProviderErrorCode.FileExists:
          throw $UU.FileExists(err.message);
        case FileSystemProviderErrorCode.FileNotFound:
          throw $UU.FileNotFound(err.message);
        case FileSystemProviderErrorCode.FileNotADirectory:
          throw $UU.FileNotADirectory(err.message);
        case FileSystemProviderErrorCode.FileIsADirectory:
          throw $UU.FileIsADirectory(err.message);
        case FileSystemProviderErrorCode.NoPermissions:
          throw $UU.NoPermissions(err.message);
        case FileSystemProviderErrorCode.Unavailable:
          throw $UU.Unavailable(err.message);
        default:
          throw new $UU(err.message, err.name);
      }
    }
    if (!(err instanceof Error)) {
      throw new $UU(String(err));
    }
    if (err.name === "ENOPRO" || err.message.includes("ENOPRO")) {
      throw $UU.Unavailable(err.message);
    }
    switch (err.name) {
      case FileSystemProviderErrorCode.FileExists:
        throw $UU.FileExists(err.message);
      case FileSystemProviderErrorCode.FileNotFound:
        throw $UU.FileNotFound(err.message);
      case FileSystemProviderErrorCode.FileNotADirectory:
        throw $UU.FileNotADirectory(err.message);
      case FileSystemProviderErrorCode.FileIsADirectory:
        throw $UU.FileIsADirectory(err.message);
      case FileSystemProviderErrorCode.NoPermissions:
        throw $UU.NoPermissions(err.message);
      case FileSystemProviderErrorCode.Unavailable:
        throw $UU.Unavailable(err.message);
      default:
        throw new $UU(err.message, err.name);
    }
  }
  // ---
  addFileSystemProvider(scheme, provider, options2) {
    this.b.set(scheme, { impl: provider, extUri: options2?.isCaseSensitive ? $lh : $nh, isReadonly: !!options2?.isReadonly });
    return $1c(() => this.b.delete(scheme));
  }
  getFileSystemProviderExtUri(scheme) {
    return this.b.get(scheme)?.extUri ?? $lh;
  }
};
$bxc = $bxc_1 = __decorate([
  __param(0, $gW),
  __param(1, $Pwc)
], $bxc);
var $cxc = $Qk("IExtHostConsumerFileSystem");

// out-build/vs/workbench/api/common/extHostStoragePaths.js
var $dxc = $Qk("IExtensionStoragePaths");
var $exc = class $exc2 {
  constructor(initData, d, f) {
    this.d = d;
    this.f = f;
    this.a = initData.workspace ?? void 0;
    this.b = initData.environment;
    this.whenReady = this.h().then((value) => this.c = value);
  }
  async g(storageName) {
    return URI.joinPath(this.b.workspaceStorageHome, storageName);
  }
  async h() {
    if (!this.a) {
      return Promise.resolve(void 0);
    }
    const storageName = this.a.id;
    const storageUri = await this.g(storageName);
    try {
      await this.f.value.stat(storageUri);
      this.d.trace("[ExtHostStorage] storage dir already exists", storageUri);
      return storageUri;
    } catch {
    }
    try {
      this.d.trace("[ExtHostStorage] creating dir and metadata-file", storageUri);
      await this.f.value.createDirectory(storageUri);
      await this.f.value.writeFile(URI.joinPath(storageUri, "meta.json"), new TextEncoder().encode(JSON.stringify({
        id: this.a.id,
        configuration: URI.revive(this.a.configuration)?.toString(),
        name: this.a.name
      }, void 0, 2)));
      return storageUri;
    } catch (e) {
      this.d.error("[ExtHostStorage]", e);
      return void 0;
    }
  }
  workspaceValue(extension) {
    if (this.c) {
      return URI.joinPath(this.c, extension.identifier.value);
    }
    return void 0;
  }
  globalValue(extension) {
    return URI.joinPath(this.b.globalStorageHome, extension.identifier.value.toLowerCase());
  }
  onWillDeactivateAll() {
  }
};
$exc = __decorate([
  __param(0, $wW),
  __param(1, $wn),
  __param(2, $cxc)
], $exc);

// out-build/vs/platform/tunnel/common/tunnel.js
var $tC = $Qk("tunnelService");
var $uC = $Qk("sharedTunnelsService");
var TunnelProtocol;
(function(TunnelProtocol2) {
  TunnelProtocol2["Http"] = "http";
  TunnelProtocol2["Https"] = "https";
})(TunnelProtocol || (TunnelProtocol = {}));
var TunnelPrivacyId;
(function(TunnelPrivacyId2) {
  TunnelPrivacyId2["ConstantPrivate"] = "constantPrivate";
  TunnelPrivacyId2["Private"] = "private";
  TunnelPrivacyId2["Public"] = "public";
})(TunnelPrivacyId || (TunnelPrivacyId = {}));
function $vC(addressOrTunnelProvider) {
  return !!addressOrTunnelProvider.forwardPort;
}
var ProvidedOnAutoForward;
(function(ProvidedOnAutoForward2) {
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["Notify"] = 1] = "Notify";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["OpenBrowser"] = 2] = "OpenBrowser";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["OpenPreview"] = 3] = "OpenPreview";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["Silent"] = 4] = "Silent";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["Ignore"] = 5] = "Ignore";
  ProvidedOnAutoForward2[ProvidedOnAutoForward2["OpenBrowserOnce"] = 6] = "OpenBrowserOnce";
})(ProvidedOnAutoForward || (ProvidedOnAutoForward = {}));
function $wC(uri) {
  if (uri.scheme !== "http" && uri.scheme !== "https") {
    return void 0;
  }
  const localhostMatch = /^(localhost|127\.0\.0\.1|0\.0\.0\.0):(\d+)$/.exec(uri.authority);
  if (!localhostMatch) {
    return void 0;
  }
  return {
    address: localhostMatch[1],
    port: +localhostMatch[2]
  };
}
var $yC = ["localhost", "127.0.0.1", "0:0:0:0:0:0:0:1", "::1"];
function $zC(host) {
  return $yC.indexOf(host) >= 0;
}
var $AC = ["0.0.0.0", "0:0:0:0:0:0:0:0", "::"];
function $BC(host) {
  return $AC.indexOf(host) >= 0;
}
function $CC(port, host, os3, osRelease) {
  if (os3 === 1) {
    return false;
  }
  if (os3 === 2) {
    if ($BC(host)) {
      const osVersion = /(\d+)\.(\d+)\.(\d+)/g.exec(osRelease);
      if (osVersion?.length === 4) {
        const major2 = parseInt(osVersion[1]);
        if (major2 >= 18) {
          return false;
        }
      }
    }
  }
  return port < 1024;
}
var $DC = class {
  constructor(remoteAddress, localAddress, b) {
    this.remoteAddress = remoteAddress;
    this.localAddress = localAddress;
    this.b = b;
    this.a = new $ze();
    this.onDidDispose = this.a.event;
  }
  dispose() {
    this.a.fire();
    return this.b();
  }
};
var $EC = class $EC2 extends $3c {
  constructor(r, s) {
    super();
    this.r = r;
    this.s = s;
    this.a = new $ze();
    this.onTunnelOpened = this.a.event;
    this.b = new $ze();
    this.onTunnelClosed = this.b.event;
    this.c = new $ze();
    this.onAddedTunnelProvider = this.c.event;
    this.f = /* @__PURE__ */ new Map();
    this.h = false;
    this.j = true;
    this.m = [];
    this.n = /* @__PURE__ */ new Set();
  }
  get hasTunnelProvider() {
    return !!this.g;
  }
  get t() {
    const settingValue = this.s.getValue("remote.localPortHost");
    return !settingValue || settingValue === "localhost" ? "127.0.0.1" : "0.0.0.0";
  }
  setTunnelProvider(provider) {
    this.g = provider;
    if (!provider) {
      this.h = false;
      this.m = [];
      this.c.fire();
      return {
        dispose: () => {
        }
      };
    }
    this.c.fire();
    return {
      dispose: () => {
        this.g = void 0;
        this.h = false;
        this.m = [];
      }
    };
  }
  setTunnelFeatures(features) {
    this.h = features.elevation;
    this.m = features.privacyOptions;
    this.j = features.protocol;
  }
  get canChangeProtocol() {
    return this.j;
  }
  get canElevate() {
    return this.h;
  }
  get canChangePrivacy() {
    return this.m.length > 0;
  }
  get privacyOptions() {
    return this.m;
  }
  get tunnels() {
    return this.u();
  }
  async u() {
    const tunnels = [];
    const tunnelArray = Array.from(this.f.values());
    for (const portMap of tunnelArray) {
      const portArray = Array.from(portMap.values());
      for (const x of portArray) {
        const tunnelValue = await x.value;
        if (tunnelValue && typeof tunnelValue !== "string") {
          tunnels.push(tunnelValue);
        }
      }
    }
    return tunnels;
  }
  async dispose() {
    super.dispose();
    for (const portMap of this.f.values()) {
      for (const { value } of portMap.values()) {
        await value.then((tunnel) => typeof tunnel !== "string" ? tunnel?.dispose() : void 0);
      }
      portMap.clear();
    }
    this.f.clear();
  }
  setEnvironmentTunnel(remoteHost, remotePort, localAddress, privacy, protocol) {
    this.z(remoteHost, remotePort, Promise.resolve({
      tunnelRemoteHost: remoteHost,
      tunnelRemotePort: remotePort,
      localAddress,
      privacy,
      protocol,
      dispose: () => Promise.resolve()
    }));
  }
  async getExistingTunnel(remoteHost, remotePort) {
    if ($BC(remoteHost) || $zC(remoteHost)) {
      remoteHost = $yC[0];
    }
    const existing = this.D(remoteHost, remotePort);
    if (existing) {
      ++existing.refcount;
      return existing.value;
    }
    return void 0;
  }
  openTunnel(addressProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded = false, privacy, protocol) {
    this.r.trace(`ForwardedPorts: (TunnelService) openTunnel request for ${remoteHost}:${remotePort} on local port ${localPort}.`);
    const addressOrTunnelProvider = this.g ?? addressProvider;
    if (!addressOrTunnelProvider) {
      return void 0;
    }
    if (!remoteHost) {
      remoteHost = "localhost";
    }
    if (!localHost) {
      localHost = this.t;
    }
    if (this.g && this.n.has(remotePort)) {
      this.r.debug(`ForwardedPorts: (TunnelService) Another call to create a tunnel with the same address has occurred before the last one completed. This call will be ignored.`);
      return;
    }
    const resolvedTunnel = this.F(addressOrTunnelProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol);
    if (!resolvedTunnel) {
      this.r.trace(`ForwardedPorts: (TunnelService) Tunnel was not created.`);
      return resolvedTunnel;
    }
    return resolvedTunnel.then((tunnel) => {
      if (!tunnel) {
        this.r.trace("ForwardedPorts: (TunnelService) New tunnel is undefined.");
        this.C(remoteHost, remotePort);
        return void 0;
      } else if (typeof tunnel === "string") {
        this.r.trace("ForwardedPorts: (TunnelService) The tunnel provider returned an error when creating the tunnel.");
        this.C(remoteHost, remotePort);
        return tunnel;
      }
      this.r.trace("ForwardedPorts: (TunnelService) New tunnel established.");
      const newTunnel = this.w(tunnel);
      if (tunnel.tunnelRemoteHost !== remoteHost || tunnel.tunnelRemotePort !== remotePort) {
        this.r.warn("ForwardedPorts: (TunnelService) Created tunnel does not match requirements of requested tunnel. Host or port mismatch.");
      }
      if (privacy && tunnel.privacy !== privacy) {
        this.r.warn("ForwardedPorts: (TunnelService) Created tunnel does not match requirements of requested tunnel. Privacy mismatch.");
      }
      this.a.fire(newTunnel);
      return newTunnel;
    });
  }
  w(tunnel) {
    return {
      tunnelRemotePort: tunnel.tunnelRemotePort,
      tunnelRemoteHost: tunnel.tunnelRemoteHost,
      tunnelLocalPort: tunnel.tunnelLocalPort,
      localAddress: tunnel.localAddress,
      privacy: tunnel.privacy,
      protocol: tunnel.protocol,
      dispose: async () => {
        this.r.trace(`ForwardedPorts: (TunnelService) dispose request for ${tunnel.tunnelRemoteHost}:${tunnel.tunnelRemotePort} `);
        const existingHost = this.f.get(tunnel.tunnelRemoteHost);
        if (existingHost) {
          const existing = existingHost.get(tunnel.tunnelRemotePort);
          if (existing) {
            existing.refcount--;
            await this.y(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort, existing);
          }
        }
      }
    };
  }
  async y(remoteHost, remotePort, tunnel) {
    if (tunnel.refcount <= 0) {
      this.r.trace(`ForwardedPorts: (TunnelService) Tunnel is being disposed ${remoteHost}:${remotePort}.`);
      const disposePromise = tunnel.value.then(async (tunnel2) => {
        if (tunnel2 && typeof tunnel2 !== "string") {
          await tunnel2.dispose(true);
          this.b.fire({ host: tunnel2.tunnelRemoteHost, port: tunnel2.tunnelRemotePort });
        }
      });
      if (this.f.has(remoteHost)) {
        this.f.get(remoteHost).delete(remotePort);
      }
      return disposePromise;
    }
  }
  async closeTunnel(remoteHost, remotePort) {
    this.r.trace(`ForwardedPorts: (TunnelService) close request for ${remoteHost}:${remotePort} `);
    const portMap = this.f.get(remoteHost);
    if (portMap && portMap.has(remotePort)) {
      const value = portMap.get(remotePort);
      value.refcount = 0;
      await this.y(remoteHost, remotePort, value);
    }
  }
  z(remoteHost, remotePort, tunnel) {
    if (!this.f.has(remoteHost)) {
      this.f.set(remoteHost, /* @__PURE__ */ new Map());
    }
    this.f.get(remoteHost).set(remotePort, { refcount: 1, value: tunnel });
  }
  async C(remoteHost, remotePort) {
    const hostMap = this.f.get(remoteHost);
    if (hostMap) {
      const tunnel = hostMap.get(remotePort);
      const tunnelResult = tunnel ? await tunnel.value : void 0;
      if (!tunnelResult || typeof tunnelResult === "string") {
        hostMap.delete(remotePort);
      }
      if (hostMap.size === 0) {
        this.f.delete(remoteHost);
      }
    }
  }
  D(remoteHost, remotePort) {
    const hosts = [remoteHost];
    if ($zC(remoteHost)) {
      hosts.push(...$yC);
      hosts.push(...$AC);
    } else if ($BC(remoteHost)) {
      hosts.push(...$AC);
    }
    const existingPortMaps = hosts.map((host) => this.f.get(host));
    for (const map of existingPortMaps) {
      const existingTunnel = map?.get(remotePort);
      if (existingTunnel) {
        return existingTunnel;
      }
    }
    return void 0;
  }
  canTunnel(uri) {
    return !!$wC(uri);
  }
  G(tunnelProvider, remoteHost, remotePort, localPort, elevateIfNeeded, privacy, protocol) {
    this.r.trace(`ForwardedPorts: (TunnelService) Creating tunnel with provider ${remoteHost}:${remotePort} on local port ${localPort}.`);
    const key = remotePort;
    this.n.add(key);
    const preferredLocalPort = localPort === void 0 ? remotePort : localPort;
    const creationInfo = { elevationRequired: elevateIfNeeded ? this.isPortPrivileged(preferredLocalPort) : false };
    const tunnelOptions = { remoteAddress: { host: remoteHost, port: remotePort }, localAddressPort: localPort, privacy, public: privacy ? privacy !== TunnelPrivacyId.Private : void 0, protocol };
    const tunnel = tunnelProvider.forwardPort(tunnelOptions, creationInfo);
    if (tunnel) {
      this.z(remoteHost, remotePort, tunnel);
      tunnel.finally(() => {
        this.r.trace("ForwardedPorts: (TunnelService) Tunnel created by provider.");
        this.n.delete(key);
      });
    } else {
      this.n.delete(key);
    }
    return tunnel;
  }
};
$EC = __decorate([
  __param(0, $wn),
  __param(1, $kl)
], $EC);

// out-build/vs/workbench/api/common/extHostTunnelService.js
var ExtensionTunnel = class extends $DC {
};
var TunnelDtoConverter;
(function(TunnelDtoConverter2) {
  function fromApiTunnel(tunnel) {
    return {
      remoteAddress: tunnel.remoteAddress,
      localAddress: tunnel.localAddress,
      public: !!tunnel.public,
      privacy: tunnel.privacy ?? (tunnel.public ? TunnelPrivacyId.Public : TunnelPrivacyId.Private),
      protocol: tunnel.protocol
    };
  }
  TunnelDtoConverter2.fromApiTunnel = fromApiTunnel;
  function fromServiceTunnel(tunnel) {
    return {
      remoteAddress: {
        host: tunnel.tunnelRemoteHost,
        port: tunnel.tunnelRemotePort
      },
      localAddress: tunnel.localAddress,
      public: tunnel.privacy !== TunnelPrivacyId.ConstantPrivate && tunnel.privacy !== TunnelPrivacyId.ConstantPrivate,
      privacy: tunnel.privacy,
      protocol: tunnel.protocol
    };
  }
  TunnelDtoConverter2.fromServiceTunnel = fromServiceTunnel;
})(TunnelDtoConverter || (TunnelDtoConverter = {}));
var $6Sb = $Qk("IExtHostTunnelService");
var $7Sb = class $7Sb2 extends $3c {
  constructor(extHostRpc, initData, s) {
    super();
    this.s = s;
    this.f = () => {
      return Promise.resolve(true);
    };
    this.g = /* @__PURE__ */ new Map();
    this.h = new $ze();
    this.onDidChangeTunnels = this.h.event;
    this.n = 0;
    this.r = /* @__PURE__ */ new Map();
    this.a = extHostRpc.getProxy($xT.MainThreadTunnelService);
  }
  async openTunnel(extension, forward) {
    this.s.trace(`ForwardedPorts: (ExtHostTunnelService) ${extension.identifier.value} called openTunnel API for ${forward.remoteAddress.host}:${forward.remoteAddress.port}.`);
    const tunnel = await this.a.$openTunnel(forward, extension.displayName);
    if (tunnel) {
      const disposableTunnel = new ExtensionTunnel(tunnel.remoteAddress, tunnel.localAddress, () => {
        return this.a.$closeTunnel(tunnel.remoteAddress);
      });
      this.B(disposableTunnel);
      return disposableTunnel;
    }
    return void 0;
  }
  async getTunnels() {
    return this.a.$getTunnels();
  }
  u() {
    return this.n++;
  }
  registerPortsAttributesProvider(portSelector, provider) {
    if (portSelector.portRange === void 0 && portSelector.commandPattern === void 0) {
      this.s.error("PortAttributesProvider must specify either a portRange or a commandPattern");
    }
    const providerHandle = this.u();
    this.r.set(providerHandle, { selector: portSelector, provider });
    this.a.$registerPortsAttributesProvider(portSelector, providerHandle);
    return new $zT(() => {
      this.r.delete(providerHandle);
      this.a.$unregisterPortsAttributesProvider(providerHandle);
    });
  }
  async $providePortAttributes(handles, ports, pid, commandLine, cancellationToken) {
    const providedAttributes = [];
    for (const handle of handles) {
      const provider = this.r.get(handle);
      if (!provider) {
        return [];
      }
      providedAttributes.push(...await Promise.all(ports.map(async (port) => {
        let providedAttributes2;
        try {
          providedAttributes2 = await provider.provider.providePortAttributes({ port, pid, commandLine }, cancellationToken);
        } catch (e) {
          providedAttributes2 = await provider.provider.providePortAttributes(port, pid, commandLine, cancellationToken);
        }
        return { providedAttributes: providedAttributes2, port };
      })));
    }
    const allAttributes = providedAttributes.filter((attribute) => !!attribute.providedAttributes);
    return allAttributes.length > 0 ? allAttributes.map((attributes) => {
      return {
        autoForwardAction: attributes.providedAttributes.autoForwardAction,
        port: attributes.port
      };
    }) : [];
  }
  async $registerCandidateFinder(_enable) {
  }
  registerTunnelProvider(provider, information) {
    if (this.b) {
      throw new Error("A tunnel provider has already been registered. Only the first tunnel provider to be registered will be used.");
    }
    this.b = async (tunnelOptions, tunnelCreationOptions) => {
      const result = await provider.provideTunnel(tunnelOptions, tunnelCreationOptions, CancellationToken.None);
      return result ?? void 0;
    };
    const tunnelFeatures = information.tunnelFeatures ? {
      elevation: !!information.tunnelFeatures?.elevation,
      privacyOptions: information.tunnelFeatures?.privacyOptions,
      protocol: information.tunnelFeatures.protocol === void 0 ? true : information.tunnelFeatures.protocol
    } : void 0;
    this.a.$setTunnelProvider(tunnelFeatures, true);
    return Promise.resolve($1c(() => {
      this.b = void 0;
      this.a.$setTunnelProvider(void 0, false);
    }));
  }
  /**
   * Applies the tunnel metadata and factory found in the remote authority
   * resolver to the tunnel system.
   *
   * `managedRemoteAuthority` should be be passed if the resolver returned on.
   * If this is the case, the tunnel cannot be connected to via a websocket from
   * the share process, so a synethic tunnel factory is used as a default.
   */
  async setTunnelFactory(provider, managedRemoteAuthority) {
    if (provider) {
      if (provider.candidatePortSource !== void 0) {
        this.a.$setCandidatePortSource(provider.candidatePortSource);
      }
      if (provider.showCandidatePort) {
        this.f = provider.showCandidatePort;
        this.a.$setCandidateFilter();
      }
      const tunnelFactory = provider.tunnelFactory ?? (managedRemoteAuthority ? this.w(managedRemoteAuthority) : void 0);
      if (tunnelFactory) {
        this.b = tunnelFactory;
        let privacyOptions = provider.tunnelFeatures?.privacyOptions ?? [];
        if (provider.tunnelFeatures?.public && privacyOptions.length === 0) {
          privacyOptions = [
            {
              id: "private",
              label: localize(2770, null),
              themeIcon: "lock"
            },
            {
              id: "public",
              label: localize(2771, null),
              themeIcon: "eye"
            }
          ];
        }
        const tunnelFeatures = provider.tunnelFeatures ? {
          elevation: !!provider.tunnelFeatures?.elevation,
          public: !!provider.tunnelFeatures?.public,
          privacyOptions,
          protocol: true
        } : void 0;
        this.a.$setTunnelProvider(tunnelFeatures, !!provider.tunnelFactory);
      }
    } else {
      this.b = void 0;
    }
    return $1c(() => {
      this.b = void 0;
    });
  }
  w(_authority) {
    return void 0;
  }
  async $closeTunnel(remote, silent) {
    if (this.g.has(remote.host)) {
      const hostMap = this.g.get(remote.host);
      if (hostMap.has(remote.port)) {
        if (silent) {
          hostMap.get(remote.port).disposeListener.dispose();
        }
        await hostMap.get(remote.port).tunnel.dispose();
        hostMap.delete(remote.port);
      }
    }
  }
  async $onDidTunnelsChange() {
    this.h.fire();
  }
  async $forwardPort(tunnelOptions, tunnelCreationOptions) {
    if (this.b) {
      try {
        this.s.trace("ForwardedPorts: (ExtHostTunnelService) Getting tunnel from provider.");
        const providedPort = this.b(tunnelOptions, tunnelCreationOptions);
        this.s.trace("ForwardedPorts: (ExtHostTunnelService) Got tunnel promise from provider.");
        if (providedPort !== void 0) {
          const tunnel = await providedPort;
          this.s.trace("ForwardedPorts: (ExtHostTunnelService) Successfully awaited tunnel from provider.");
          if (tunnel === void 0) {
            this.s.error("ForwardedPorts: (ExtHostTunnelService) Resolved tunnel is undefined");
            return void 0;
          }
          if (!this.g.has(tunnelOptions.remoteAddress.host)) {
            this.g.set(tunnelOptions.remoteAddress.host, /* @__PURE__ */ new Map());
          }
          const disposeListener = this.B(tunnel.onDidDispose(() => {
            this.s.trace("ForwardedPorts: (ExtHostTunnelService) Extension fired tunnel's onDidDispose.");
            return this.a.$closeTunnel(tunnel.remoteAddress);
          }));
          this.g.get(tunnelOptions.remoteAddress.host).set(tunnelOptions.remoteAddress.port, { tunnel, disposeListener });
          return TunnelDtoConverter.fromApiTunnel(tunnel);
        } else {
          this.s.trace("ForwardedPorts: (ExtHostTunnelService) Tunnel is undefined");
        }
      } catch (e) {
        this.s.trace("ForwardedPorts: (ExtHostTunnelService) tunnel provider error");
        if (e instanceof Error) {
          return e.message;
        }
      }
    }
    return void 0;
  }
  async $applyCandidateFilter(candidates) {
    const filter = await Promise.all(candidates.map((candidate) => this.f(candidate.host, candidate.port, candidate.detail ?? "")));
    const result = candidates.filter((candidate, index) => filter[index]);
    this.s.trace(`ForwardedPorts: (ExtHostTunnelService) filtered from ${candidates.map((port) => port.port).join(", ")} to ${result.map((port) => port.port).join(", ")}`);
    return result;
  }
};
$7Sb = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $wn)
], $7Sb);

// out-build/vs/platform/terminal/common/environmentVariableShared.js
function $BB(collection) {
  return [...collection.entries()];
}
function $CB(descriptionMap) {
  return descriptionMap ? [...descriptionMap.entries()] : [];
}

// out-build/vs/platform/terminal/common/terminalDataBuffering.js
var $kRb = class {
  constructor(b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
  }
  dispose() {
    for (const buffer of this.a.values()) {
      buffer.dispose();
    }
  }
  startBuffering(id2, event, throttleBy = 5) {
    const disposable = event((e) => {
      const data = typeof e === "string" ? e : e.data;
      let buffer = this.a.get(id2);
      if (buffer) {
        buffer.data.push(data);
        return;
      }
      const timeoutId = setTimeout(() => this.flushBuffer(id2), throttleBy);
      buffer = {
        data: [data],
        timeoutId,
        dispose: () => {
          clearTimeout(timeoutId);
          this.flushBuffer(id2);
          disposable.dispose();
        }
      };
      this.a.set(id2, buffer);
    });
    return disposable;
  }
  stopBuffering(id2) {
    const buffer = this.a.get(id2);
    buffer?.dispose();
  }
  flushBuffer(id2) {
    const buffer = this.a.get(id2);
    if (buffer) {
      this.a.delete(id2);
      this.b(id2, buffer.data.join(""));
    }
  }
};

// out-build/vs/workbench/api/common/extHostTestItem.js
var testItemPropAccessor = (api, defaultValue, equals, toUpdate) => {
  let value = defaultValue;
  return {
    enumerable: true,
    configurable: false,
    get() {
      return value;
    },
    set(newValue) {
      if (!equals(value, newValue)) {
        const oldValue = value;
        value = newValue;
        api.listener?.(toUpdate(newValue, oldValue));
      }
    }
  };
};
var strictEqualComparator2 = (a, b) => a === b;
var propComparators = {
  range: (a, b) => {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.isEqual(b);
  },
  label: strictEqualComparator2,
  description: strictEqualComparator2,
  sortText: strictEqualComparator2,
  busy: strictEqualComparator2,
  error: strictEqualComparator2,
  canResolveChildren: strictEqualComparator2,
  tags: (a, b) => {
    if (a.length !== b.length) {
      return false;
    }
    if (a.some((t1) => !b.find((t2) => t1.id === t2.id))) {
      return false;
    }
    return true;
  }
};
var evSetProps = (fn) => (v) => ({ op: 4, update: fn(v) });
var makePropDescriptors = (api, label) => ({
  range: (() => {
    let value;
    const updateProps = evSetProps((r) => ({ range: $9C.lift(Range.from(r)) }));
    return {
      enumerable: true,
      configurable: false,
      get() {
        return value;
      },
      set(newValue) {
        api.listener?.({
          op: 6
          /* TestItemEventOp.DocumentSynced */
        });
        if (!propComparators.range(value, newValue)) {
          value = newValue;
          api.listener?.(updateProps(newValue));
        }
      }
    };
  })(),
  label: testItemPropAccessor(api, label, propComparators.label, evSetProps((label2) => ({ label: label2 }))),
  description: testItemPropAccessor(api, void 0, propComparators.description, evSetProps((description) => ({ description }))),
  sortText: testItemPropAccessor(api, void 0, propComparators.sortText, evSetProps((sortText) => ({ sortText }))),
  canResolveChildren: testItemPropAccessor(api, false, propComparators.canResolveChildren, (state) => ({
    op: 2,
    state
  })),
  busy: testItemPropAccessor(api, false, propComparators.busy, evSetProps((busy) => ({ busy }))),
  error: testItemPropAccessor(api, void 0, propComparators.error, evSetProps((error) => ({ error: MarkdownString.fromStrict(error) || null }))),
  tags: testItemPropAccessor(api, [], propComparators.tags, (current, previous) => ({
    op: 1,
    new: current.map(TestTag.from),
    old: previous.map(TestTag.from)
  }))
});
var toItemFromPlain = (item) => {
  const testId = $mQ.fromString(item.extId);
  const testItem = new $tW(testId.controllerId, testId.localId, item.label, URI.revive(item.uri) || void 0);
  testItem.range = Range.to(item.range || void 0);
  testItem.description = item.description || void 0;
  testItem.sortText = item.sortText || void 0;
  testItem.tags = item.tags.map((t) => TestTag.to({ id: $tQ(t).tagId }));
  return testItem;
};
var $sW = (context) => {
  let node;
  for (const test of context.tests) {
    const next = toItemFromPlain(test.item);
    $cW(next).parent = node;
    node = next;
  }
  return node;
};
var $tW = class _$tW {
  /**
   * Note that data is deprecated and here for back-compat only
   */
  constructor(controllerId, id2, label, uri) {
    if (id2.includes(
      "\0"
      /* TestIdPathParts.Delimiter */
    )) {
      throw new Error(`Test IDs may not include the ${JSON.stringify(id2)} symbol`);
    }
    const api = $bW(this, controllerId);
    Object.defineProperties(this, {
      id: {
        value: id2,
        enumerable: true,
        writable: false
      },
      uri: {
        value: uri,
        enumerable: true,
        writable: false
      },
      parent: {
        enumerable: false,
        get() {
          return api.parent instanceof $uW ? void 0 : api.parent;
        }
      },
      children: {
        value: $aW(api, $cW, _$tW),
        enumerable: true,
        writable: false
      },
      ...makePropDescriptors(api, label)
    });
  }
};
var $uW = class extends $tW {
  constructor(controllerId, label) {
    super(controllerId, controllerId, label, void 0);
    this._isRoot = true;
  }
};
var $vW = class extends $9V {
  constructor(controllerId, controllerLabel, editors) {
    super({
      controllerId,
      getDocumentVersion: (uri) => uri && editors.getDocument(uri)?.version,
      getApiFor: $cW,
      getChildren: (item) => item.children,
      root: new $uW(controllerId, controllerLabel),
      toITestItem: TestItem.from
    });
  }
};

// out-build/vs/workbench/services/extensions/common/extensionHostProtocol.js
var UIKind;
(function(UIKind2) {
  UIKind2[UIKind2["Desktop"] = 1] = "Desktop";
  UIKind2[UIKind2["Web"] = 2] = "Web";
})(UIKind || (UIKind = {}));
var ExtensionHostExitCode;
(function(ExtensionHostExitCode2) {
  ExtensionHostExitCode2[ExtensionHostExitCode2["VersionMismatch"] = 55] = "VersionMismatch";
  ExtensionHostExitCode2[ExtensionHostExitCode2["UnexpectedError"] = 81] = "UnexpectedError";
})(ExtensionHostExitCode || (ExtensionHostExitCode = {}));
var MessageType2;
(function(MessageType3) {
  MessageType3[MessageType3["Initialized"] = 0] = "Initialized";
  MessageType3[MessageType3["Ready"] = 1] = "Ready";
  MessageType3[MessageType3["Terminate"] = 2] = "Terminate";
})(MessageType2 || (MessageType2 = {}));
function $jN(type) {
  const result = $Ci.alloc(1);
  switch (type) {
    case 0:
      result.writeUInt8(1, 0);
      break;
    case 1:
      result.writeUInt8(2, 0);
      break;
    case 2:
      result.writeUInt8(3, 0);
      break;
  }
  return result;
}
function $kN(message, type) {
  if (message.byteLength !== 1) {
    return false;
  }
  switch (message.readUInt8(0)) {
    case 1:
      return type === 0;
    case 2:
      return type === 1;
    case 3:
      return type === 2;
    default:
      return false;
  }
}
var NativeLogMarkers;
(function(NativeLogMarkers2) {
  NativeLogMarkers2["Start"] = "START_NATIVE_LOG";
  NativeLogMarkers2["End"] = "END_NATIVE_LOG";
})(NativeLogMarkers || (NativeLogMarkers = {}));

// out-build/vs/workbench/api/common/extHostTelemetry.js
var $xW = class $xW2 extends $3c {
  constructor(s, t) {
    super();
    this.s = s;
    this.t = t;
    this.a = this.B(new $ze());
    this.onDidChangeTelemetryEnabled = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeTelemetryConfiguration = this.b.event;
    this.c = { usage: true, error: true };
    this.f = 0;
    this.g = false;
    this.j = false;
    this.r = /* @__PURE__ */ new Map();
    this.m = URI.revive(this.s.environment.extensionTelemetryLogResource);
    this.j = this.s.environment.isExtensionTelemetryLoggingOnly;
    this.n = t.createLogger(this.m, { id: $gw, name: localize(2767, null, this.j ? " (Not Sent)" : ""), hidden: true });
    this.B(this.n);
    this.B(t.onDidChangeLogLevel((arg) => {
      if ($yn(arg)) {
        this.u();
      }
    }));
    this.n.info("Below are logs for extension telemetry events sent to the telemetry output channel API once the log level is set to trace.");
    this.n.info("===========================================================");
  }
  u() {
    this.t.setVisibility(this.m, this.g && this.t.getLogLevel() === LogLevel.Trace);
  }
  getTelemetryConfiguration() {
    return this.f === 3;
  }
  getTelemetryDetails() {
    return {
      isCrashEnabled: this.f >= 1,
      isErrorsEnabled: this.c.error ? this.f >= 2 : false,
      isUsageEnabled: this.c.usage ? this.f >= 3 : false
    };
  }
  instantiateLogger(extension, sender, options2) {
    const telemetryDetails = this.getTelemetryDetails();
    const logger = new $yW(sender, options2, extension, this.n, this.j, this.getBuiltInCommonProperties(extension), { isUsageEnabled: telemetryDetails.isUsageEnabled, isErrorsEnabled: telemetryDetails.isErrorsEnabled });
    const loggers = this.r.get(extension.identifier.value) ?? [];
    this.r.set(extension.identifier.value, [...loggers, logger]);
    return logger.apiTelemetryLogger;
  }
  $initializeTelemetryLevel(level, supportsTelemetry, productConfig) {
    this.f = level;
    this.g = supportsTelemetry;
    this.c = productConfig ?? { usage: true, error: true };
    this.u();
  }
  getBuiltInCommonProperties(extension) {
    const commonProperties = /* @__PURE__ */ Object.create(null);
    commonProperties["common.extname"] = `${extension.publisher}.${extension.name}`;
    commonProperties["common.extversion"] = extension.version;
    commonProperties["common.vscodemachineid"] = this.s.telemetryInfo.machineId;
    commonProperties["common.vscodesessionid"] = this.s.telemetryInfo.sessionId;
    commonProperties["common.sqmid"] = this.s.telemetryInfo.sqmId;
    commonProperties["common.devDeviceId"] = this.s.telemetryInfo.devDeviceId;
    commonProperties["common.vscodeversion"] = this.s.version;
    commonProperties["common.isnewappinstall"] = $zW(this.s.telemetryInfo.firstSessionDate);
    commonProperties["common.product"] = this.s.environment.appHost;
    switch (this.s.uiKind) {
      case UIKind.Web:
        commonProperties["common.uikind"] = "web";
        break;
      case UIKind.Desktop:
        commonProperties["common.uikind"] = "desktop";
        break;
      default:
        commonProperties["common.uikind"] = "unknown";
    }
    commonProperties["common.remotename"] = $9v($mw(this.s.remote.authority));
    return commonProperties;
  }
  $onDidChangeTelemetryLevel(level) {
    this.h = this.getTelemetryConfiguration();
    this.f = level;
    const telemetryDetails = this.getTelemetryDetails();
    this.r.forEach((loggers, key) => {
      const newLoggers = loggers.filter((l) => !l.isDisposed);
      if (newLoggers.length === 0) {
        this.r.delete(key);
      } else {
        this.r.set(key, newLoggers);
      }
    });
    this.r.forEach((loggers) => {
      for (const logger of loggers) {
        logger.updateTelemetryEnablements(telemetryDetails.isUsageEnabled, telemetryDetails.isErrorsEnabled);
      }
    });
    if (this.h !== this.getTelemetryConfiguration()) {
      this.a.fire(this.getTelemetryConfiguration());
    }
    this.b.fire(this.getTelemetryDetails());
    this.u();
  }
  onExtensionError(extension, error) {
    const loggers = this.r.get(extension.value);
    const nonDisposedLoggers = loggers?.filter((l) => !l.isDisposed);
    if (!nonDisposedLoggers) {
      this.r.delete(extension.value);
      return false;
    }
    let errorEmitted = false;
    for (const logger of nonDisposedLoggers) {
      if (logger.ignoreUnhandledExtHostErrors) {
        continue;
      }
      logger.logError(error);
      errorEmitted = true;
    }
    return errorEmitted;
  }
};
$xW = __decorate([
  __param(0, $wW),
  __param(1, $xn)
], $xW);
var $yW = class {
  static validateSender(sender) {
    if (typeof sender !== "object") {
      throw new TypeError("TelemetrySender argument is invalid");
    }
    if (typeof sender.sendEventData !== "function") {
      throw new TypeError("TelemetrySender.sendEventData must be a function");
    }
    if (typeof sender.sendErrorData !== "function") {
      throw new TypeError("TelemetrySender.sendErrorData must be a function");
    }
    if (typeof sender.flush !== "undefined" && typeof sender.flush !== "function") {
      throw new TypeError("TelemetrySender.flush must be a function or undefined");
    }
  }
  constructor(sender, options2, g, h, i, j, telemetryEnablements) {
    this.g = g;
    this.h = h;
    this.i = i;
    this.j = j;
    this.a = new $ze();
    this.ignoreUnhandledExtHostErrors = options2?.ignoreUnhandledErrors ?? false;
    this.b = options2?.ignoreBuiltInCommonProperties ?? false;
    this.c = options2?.additionalCommonProperties;
    this.f = sender;
    this.d = { isUsageEnabled: telemetryEnablements.isUsageEnabled, isErrorsEnabled: telemetryEnablements.isErrorsEnabled };
  }
  updateTelemetryEnablements(isUsageEnabled, isErrorsEnabled) {
    if (this.e) {
      this.d = { isUsageEnabled, isErrorsEnabled };
      this.a.fire(this.e);
    }
  }
  mixInCommonPropsAndCleanData(data) {
    let updatedData = "properties" in data ? data.properties ?? {} : data;
    updatedData = $pw(updatedData, []);
    if (this.c) {
      updatedData = $Ov(updatedData, this.c);
    }
    if (!this.b) {
      updatedData = $Ov(updatedData, this.j);
    }
    if ("properties" in data) {
      data.properties = updatedData;
    } else {
      data = updatedData;
    }
    return data;
  }
  k(eventName, data) {
    if (!this.f) {
      return;
    }
    if (this.g.publisher === "vscode") {
      eventName = this.g.name + "/" + eventName;
    } else {
      eventName = this.g.identifier.value + "/" + eventName;
    }
    data = this.mixInCommonPropsAndCleanData(data || {});
    if (!this.i) {
      this.f?.sendEventData(eventName, data);
    }
    this.h.trace(eventName, data);
  }
  logUsage(eventName, data) {
    if (!this.d.isUsageEnabled) {
      return;
    }
    this.k(eventName, data);
  }
  logError(eventNameOrException, data) {
    if (!this.d.isErrorsEnabled || !this.f) {
      return;
    }
    if (typeof eventNameOrException === "string") {
      this.k(eventNameOrException, data);
    } else {
      const errorData = {
        name: eventNameOrException.name,
        message: eventNameOrException.message,
        stack: eventNameOrException.stack,
        cause: eventNameOrException.cause
      };
      const cleanedErrorData = $pw(errorData, []);
      const cleanedError = new Error(cleanedErrorData.message, {
        cause: cleanedErrorData.cause
      });
      cleanedError.stack = cleanedErrorData.stack;
      cleanedError.name = cleanedErrorData.name;
      data = this.mixInCommonPropsAndCleanData(data || {});
      if (!this.i) {
        this.f.sendErrorData(cleanedError, data);
      }
      this.h.trace("exception", data);
    }
  }
  get apiTelemetryLogger() {
    if (!this.e) {
      const that = this;
      const obj = {
        logUsage: that.logUsage.bind(that),
        get isUsageEnabled() {
          return that.d.isUsageEnabled;
        },
        get isErrorsEnabled() {
          return that.d.isErrorsEnabled;
        },
        logError: that.logError.bind(that),
        dispose: that.dispose.bind(that),
        onDidChangeEnableStates: that.a.event.bind(that)
      };
      this.e = Object.freeze(obj);
    }
    return this.e;
  }
  get isDisposed() {
    return !this.f;
  }
  dispose() {
    if (this.f?.flush) {
      let tempSender = this.f;
      this.f = void 0;
      Promise.resolve(tempSender.flush()).then(tempSender = void 0);
      this.e = void 0;
    } else {
      this.f = void 0;
    }
  }
};
function $zW(firstSessionDate) {
  const installAge = Date.now() - new Date(firstSessionDate).getTime();
  return isNaN(installAge) ? false : installAge < 1e3 * 60 * 60 * 24;
}
var $AW = $Qk("IExtHostTelemetry");

// out-build/vs/workbench/api/common/extHostCommands.js
var $BW = class $BW2 {
  #proxy;
  #telemetry;
  #extHostTelemetry;
  constructor(extHostRpc, logService, extHostTelemetry) {
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.#proxy = extHostRpc.getProxy($xT.MainThreadCommands);
    this.d = logService;
    this.#extHostTelemetry = extHostTelemetry;
    this.#telemetry = extHostRpc.getProxy($xT.MainThreadTelemetry);
    this.converter = new $DW(this, (id2) => {
      const candidate = this.c.get(id2);
      return candidate?.result === $FW.Void ? candidate : void 0;
    }, logService);
    this.f = [
      {
        processArgument(a) {
          return $cu(a);
        }
      },
      {
        processArgument(arg) {
          return $Nv(arg, function(obj) {
            if ($9C.isIRange(obj)) {
              return Range.to(obj);
            }
            if ($8C.isIPosition(obj)) {
              return Position.to(obj);
            }
            if ($9C.isIRange(obj.range) && URI.isUri(obj.uri)) {
              return location.to(obj);
            }
            if (obj instanceof $Ci) {
              return obj.buffer.buffer;
            }
            if (!Array.isArray(obj)) {
              return obj;
            }
          });
        }
      }
    ];
  }
  registerArgumentProcessor(processor) {
    this.f.push(processor);
  }
  registerApiCommand(apiCommand) {
    const registration = this.registerCommand(false, apiCommand.id, async (...apiArgs) => {
      const internalArgs = apiCommand.args.map((arg, i) => {
        if (!arg.validate(apiArgs[i])) {
          throw new Error(`Invalid argument '${arg.name}' when running '${apiCommand.id}', received: ${typeof apiArgs[i] === "object" ? JSON.stringify(apiArgs[i], null, "	") : apiArgs[i]} `);
        }
        return arg.convert(apiArgs[i]);
      });
      const internalResult = await this.executeCommand(apiCommand.internalId, ...internalArgs);
      return apiCommand.result.convert(internalResult, apiArgs, this.converter);
    }, void 0, {
      description: apiCommand.description,
      args: apiCommand.args,
      returns: apiCommand.result.description
    });
    this.c.set(apiCommand.id, apiCommand);
    return new $zT(() => {
      registration.dispose();
      this.c.delete(apiCommand.id);
    });
  }
  registerCommand(global2, id2, callback, thisArg, metadata, extension) {
    this.d.trace("ExtHostCommands#registerCommand", id2);
    if (!id2.trim().length) {
      throw new Error("invalid id");
    }
    if (this.b.has(id2)) {
      throw new Error(`command '${id2}' already exists`);
    }
    this.b.set(id2, { callback, thisArg, metadata, extension });
    if (global2) {
      this.#proxy.$registerCommand(id2);
    }
    return new $zT(() => {
      if (this.b.delete(id2)) {
        if (global2) {
          this.#proxy.$unregisterCommand(id2);
        }
      }
    });
  }
  executeCommand(id2, ...args2) {
    this.d.trace("ExtHostCommands#executeCommand", id2);
    return this.g(id2, args2, true);
  }
  async g(id2, args2, retry) {
    if (this.b.has(id2)) {
      this.#proxy.$fireCommandActivationEvent(id2);
      return this.h(id2, args2, false);
    } else {
      let hasBuffers = false;
      const toArgs = $Nv(args2, function(value) {
        if (value instanceof $AT) {
          return Position.from(value);
        } else if (value instanceof $BT) {
          return Range.from(value);
        } else if (value instanceof $NT) {
          return location.from(value);
        } else if ($6U.isNotebookRange(value)) {
          return NotebookRange.from(value);
        } else if (value instanceof ArrayBuffer) {
          hasBuffers = true;
          return $Ci.wrap(new Uint8Array(value));
        } else if (value instanceof Uint8Array) {
          hasBuffers = true;
          return $Ci.wrap(value);
        } else if (value instanceof $Ci) {
          hasBuffers = true;
          return value;
        }
        if (!Array.isArray(value)) {
          return value;
        }
      });
      try {
        const result = await this.#proxy.$executeCommand(id2, hasBuffers ? new $ES(toArgs) : toArgs, retry);
        return $cu(result);
      } catch (e) {
        if (e instanceof Error && e.message === "$executeCommand:retry") {
          return this.g(id2, args2, false);
        } else {
          throw e;
        }
      }
    }
  }
  async h(id2, args2, annotateError) {
    const command = this.b.get(id2);
    if (!command) {
      throw new Error("Unknown command");
    }
    const { callback, thisArg, metadata } = command;
    if (metadata?.args) {
      for (let i = 0; i < metadata.args.length; i++) {
        try {
          $Qg(args2[i], metadata.args[i].constraint);
        } catch (err) {
          throw new Error(`Running the contributed command: '${id2}' failed. Illegal argument '${metadata.args[i].name}' - ${metadata.args[i].description}`);
        }
      }
    }
    const stopWatch = $te.create();
    try {
      return await callback.apply(thisArg, args2);
    } catch (err) {
      if (id2 === this.converter.delegatingCommandId) {
        const actual = this.converter.getActualCommand(...args2);
        if (actual) {
          id2 = actual.command;
        }
      }
      this.d.error(err, id2, command.extension?.identifier);
      if (!annotateError) {
        throw err;
      }
      if (command.extension?.identifier) {
        const reported = this.#extHostTelemetry.onExtensionError(command.extension.identifier, err);
        this.d.trace("forwarded error to extension?", reported, command.extension?.identifier);
      }
      throw new class CommandError extends Error {
        constructor() {
          super($1m(err));
          this.id = id2;
          this.source = command.extension?.displayName ?? command.extension?.name;
        }
      }();
    } finally {
      this.j(command, id2, stopWatch.elapsed());
    }
  }
  j(command, id2, duration) {
    if (!command.extension) {
      return;
    }
    this.#telemetry.$publicLog2("Extension:ActionExecuted", {
      extensionId: command.extension.identifier.value,
      id: new $bw(id2),
      duration
    });
  }
  $executeContributedCommand(id2, ...args2) {
    this.d.trace("ExtHostCommands#$executeContributedCommand", id2);
    const cmdHandler = this.b.get(id2);
    if (!cmdHandler) {
      return Promise.reject(new Error(`Contributed command '${id2}' does not exist.`));
    } else {
      args2 = args2.map((arg) => this.f.reduce((r, p) => p.processArgument(r, cmdHandler.extension?.identifier), arg));
      return this.h(id2, args2, true);
    }
  }
  getCommands(filterUnderscoreCommands = false) {
    this.d.trace("ExtHostCommands#getCommands", filterUnderscoreCommands);
    return this.#proxy.$getCommands().then((result) => {
      if (filterUnderscoreCommands) {
        result = result.filter((command) => command[0] !== "_");
      }
      return result;
    });
  }
  $getContributedCommandMetadata() {
    const result = /* @__PURE__ */ Object.create(null);
    for (const [id2, command] of this.b) {
      const { metadata } = command;
      if (metadata) {
        result[id2] = metadata;
      }
    }
    return Promise.resolve(result);
  }
};
$BW = __decorate([
  __param(0, $gW),
  __param(1, $wn),
  __param(2, $AW)
], $BW);
var $CW = $Qk("IExtHostCommands");
var $DW = class {
  // --- conversion between internal and api commands
  constructor(d, f, g) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.delegatingCommandId = `__vsc${$ps()}`;
    this.b = /* @__PURE__ */ new Map();
    this.c = 0;
    this.d.registerCommand(true, this.delegatingCommandId, this.h, this);
  }
  toInternal(command, disposables) {
    if (!command) {
      return void 0;
    }
    const result = {
      $ident: void 0,
      id: command.command,
      title: command.title,
      tooltip: command.tooltip
    };
    if (!command.command) {
      return result;
    }
    const apiCommand = this.f(command.command);
    if (apiCommand) {
      result.id = apiCommand.internalId;
      result.arguments = apiCommand.args.map((arg, i) => arg.convert(command.arguments && command.arguments[i]));
    } else if ($Qb(command.arguments)) {
      const id2 = `${command.command} /${++this.c}`;
      this.b.set(id2, command);
      disposables.add($1c(() => {
        this.b.delete(id2);
        this.g.trace("CommandsConverter#DISPOSE", id2);
      }));
      result.$ident = id2;
      result.id = this.delegatingCommandId;
      result.arguments = [id2];
      this.g.trace("CommandsConverter#CREATE", command.command, id2);
    }
    return result;
  }
  fromInternal(command) {
    if (typeof command.$ident === "string") {
      return this.b.get(command.$ident);
    } else {
      return {
        command: command.id,
        title: command.title,
        arguments: command.arguments
      };
    }
  }
  getActualCommand(...args2) {
    return this.b.get(args2[0]);
  }
  h(...args2) {
    const actualCmd = this.getActualCommand(...args2);
    this.g.trace("CommandsConverter#EXECUTE", args2[0], actualCmd ? actualCmd.command : "MISSING");
    if (!actualCmd) {
      return Promise.reject(`Actual command not found, wanted to execute ${args2[0]}`);
    }
    return this.d.executeCommand(actualCmd.command, ...actualCmd.arguments || []);
  }
};
var $EW = class _$EW {
  static {
    this.Uri = new _$EW("uri", "Uri of a text document", (v) => URI.isUri(v), (v) => v);
  }
  static {
    this.Position = new _$EW("position", "A position in a text document", (v) => $AT.isPosition(v), Position.from);
  }
  static {
    this.Range = new _$EW("range", "A range in a text document", (v) => $BT.isRange(v), Range.from);
  }
  static {
    this.Selection = new _$EW("selection", "A selection in a text document", (v) => $CT.isSelection(v), Selection.from);
  }
  static {
    this.Number = new _$EW("number", "", (v) => typeof v === "number", (v) => v);
  }
  static {
    this.String = new _$EW("string", "", (v) => typeof v === "string", (v) => v);
  }
  static {
    this.StringArray = _$EW.Arr(_$EW.String);
  }
  static Arr(element) {
    return new _$EW(`${element.name}_array`, `Array of ${element.name}, ${element.description}`, (v) => Array.isArray(v) && v.every((e) => element.validate(e)), (v) => v.map((e) => element.convert(e)));
  }
  static {
    this.CallHierarchyItem = new _$EW("item", "A call hierarchy item", (v) => v instanceof $ZT, CallHierarchyItem.from);
  }
  static {
    this.TypeHierarchyItem = new _$EW("item", "A type hierarchy item", (v) => v instanceof $qV, TypeHierarchyItem.from);
  }
  static {
    this.TestItem = new _$EW("testItem", "A VS Code TestItem", (v) => v instanceof $tW, TestItem.from);
  }
  static {
    this.TestProfile = new _$EW("testProfile", "A VS Code test profile", (v) => v instanceof $fV, TestRunProfile.from);
  }
  constructor(name, description, validate, convert) {
    this.name = name;
    this.description = description;
    this.validate = validate;
    this.convert = convert;
  }
  optional() {
    return new _$EW(this.name, `(optional) ${this.description}`, (value) => value === void 0 || value === null || this.validate(value), (value) => value === void 0 ? void 0 : value === null ? null : this.convert(value));
  }
  with(name, description) {
    return new _$EW(name ?? this.name, description ?? this.description, this.validate, this.convert);
  }
};
var $FW = class _$FW {
  static {
    this.Void = new _$FW("no result", (v) => v);
  }
  constructor(description, convert) {
    this.description = description;
    this.convert = convert;
  }
};
var $GW = class {
  constructor(id2, internalId, description, args2, result) {
    this.id = id2;
    this.internalId = internalId;
    this.description = description;
    this.args = args2;
    this.result = result;
  }
};

// out-build/vs/workbench/api/common/extHostTerminalService.js
var $yxc = $Qk("IExtHostTerminalService");
var $zxc = class extends $3c {
  constructor(u, _id, w, y) {
    super();
    this.u = u;
    this._id = _id;
    this.w = w;
    this.y = y;
    this.a = false;
    this.m = { isInteractedWith: false };
    this.isOpen = false;
    this.s = this.B(new $ze());
    this.onWillDispose = this.s.event;
    this.w = Object.freeze(this.w);
    this.b = new Promise((c) => this.g = c);
    const that = this;
    this.value = {
      get name() {
        return that.y || "";
      },
      get processId() {
        return that.b;
      },
      get creationOptions() {
        return that.w;
      },
      get exitStatus() {
        return that.j;
      },
      get state() {
        return that.m;
      },
      get selection() {
        return that.n;
      },
      get shellIntegration() {
        return that.shellIntegration;
      },
      sendText(text, shouldExecute = true) {
        that.C();
        that.u.$sendText(that._id, text, shouldExecute);
      },
      show(preserveFocus) {
        that.C();
        that.u.$show(that._id, preserveFocus);
      },
      hide() {
        that.C();
        that.u.$hide(that._id);
      },
      dispose() {
        if (!that.a) {
          that.a = true;
          that.u.$dispose(that._id);
        }
      },
      get dimensions() {
        if (that.f === void 0 || that.h === void 0) {
          return void 0;
        }
        return {
          columns: that.f,
          rows: that.h
        };
      }
    };
  }
  dispose() {
    this.s.fire();
    super.dispose();
  }
  async create(options2, internalOptions) {
    if (typeof this._id !== "string") {
      throw new Error("Terminal has already been created");
    }
    await this.u.$createTerminal(this._id, {
      name: options2.name,
      shellPath: options2.shellPath ?? void 0,
      shellArgs: options2.shellArgs ?? void 0,
      cwd: options2.cwd ?? internalOptions?.cwd ?? void 0,
      env: options2.env ?? void 0,
      icon: asTerminalIcon(options2.iconPath) ?? void 0,
      color: ThemeColor.isThemeColor(options2.color) ? options2.color.id : void 0,
      initialText: options2.message ?? void 0,
      strictEnv: options2.strictEnv ?? void 0,
      hideFromUser: options2.hideFromUser ?? void 0,
      forceShellIntegration: internalOptions?.forceShellIntegration ?? void 0,
      isFeatureTerminal: internalOptions?.isFeatureTerminal ?? void 0,
      isExtensionOwnedTerminal: true,
      useShellEnvironment: internalOptions?.useShellEnvironment ?? void 0,
      location: internalOptions?.location || this.z(options2.location, internalOptions?.resolvedExtHostIdentifier),
      isTransient: options2.isTransient ?? void 0
    });
  }
  async createExtensionTerminal(location2, internalOptions, parentTerminal, iconPath, color2) {
    if (typeof this._id !== "string") {
      throw new Error("Terminal has already been created");
    }
    await this.u.$createTerminal(this._id, {
      name: this.y,
      isExtensionCustomPtyTerminal: true,
      icon: iconPath,
      color: ThemeColor.isThemeColor(color2) ? color2.id : void 0,
      location: internalOptions?.location || this.z(location2, parentTerminal),
      isTransient: true
    });
    if (typeof this._id === "string") {
      throw new Error("Terminal creation failed");
    }
    return this._id;
  }
  z(location2, parentTerminal) {
    if (typeof location2 === "object") {
      if ("parentTerminal" in location2 && location2.parentTerminal && parentTerminal) {
        return { parentTerminal };
      }
      if ("viewColumn" in location2) {
        return { viewColumn: ViewColumn2.from(location2.viewColumn), preserveFocus: location2.preserveFocus };
      }
      return void 0;
    }
    return location2;
  }
  C() {
    if (this.a) {
      throw new Error("Terminal has already been disposed");
    }
  }
  set name(name) {
    this.y = name;
  }
  setExitStatus(code, reason) {
    this.j = Object.freeze({ code, reason });
  }
  setDimensions(cols, rows) {
    if (cols === this.f && rows === this.h) {
      return false;
    }
    if (cols === 0 || rows === 0) {
      return false;
    }
    this.f = cols;
    this.h = rows;
    return true;
  }
  setInteractedWith() {
    if (!this.m.isInteractedWith) {
      this.m = { isInteractedWith: true };
      return true;
    }
    return false;
  }
  setSelection(selection) {
    this.n = selection;
  }
  _setProcessId(processId) {
    if (this.g) {
      this.g(processId);
      this.g = void 0;
    } else {
      this.b.then((pid) => {
        if (pid !== processId) {
          this.b = Promise.resolve(processId);
        }
      });
    }
  }
};
var ExtHostPseudoterminal = class {
  get onProcessReady() {
    return this.b.event;
  }
  constructor(g) {
    this.g = g;
    this.id = 0;
    this.shouldPersist = false;
    this.a = new $ze();
    this.onProcessData = this.a.event;
    this.b = new $ze();
    this.d = new $ze();
    this.onDidChangeProperty = this.d.event;
    this.f = new $ze();
    this.onProcessExit = this.f.event;
  }
  refreshProperty(property) {
    throw new Error(`refreshProperty is not suppported in extension owned terminals. property: ${property}`);
  }
  updateProperty(property, value) {
    throw new Error(`updateProperty is not suppported in extension owned terminals. property: ${property}, value: ${value}`);
  }
  async start() {
    return void 0;
  }
  shutdown() {
    this.g.close();
  }
  input(data) {
    this.g.handleInput?.(data);
  }
  resize(cols, rows) {
    this.g.setDimensions?.({ columns: cols, rows });
  }
  clearBuffer() {
  }
  async processBinary(data) {
  }
  acknowledgeDataEvent(charCount) {
  }
  async setUnicodeVersion(version) {
  }
  getInitialCwd() {
    return Promise.resolve("");
  }
  getCwd() {
    return Promise.resolve("");
  }
  startSendingEvents(initialDimensions) {
    this.g.onDidWrite((e) => this.a.fire(e));
    this.g.onDidClose?.((e = void 0) => {
      this.f.fire(e === void 0 ? void 0 : e);
    });
    this.g.onDidOverrideDimensions?.((e) => {
      if (e) {
        this.d.fire({ type: "overrideDimensions", value: { cols: e.columns, rows: e.rows } });
      }
    });
    this.g.onDidChangeName?.((title) => {
      this.d.fire({ type: "title", value: title });
    });
    this.g.open(initialDimensions ? initialDimensions : void 0);
    if (initialDimensions) {
      this.g.setDimensions?.(initialDimensions);
    }
    this.b.fire({ pid: -1, cwd: "", windowsPty: void 0 });
  }
};
var nextLinkId = 1;
var $Axc = class $Axc2 extends $3c {
  get activeTerminal() {
    return this.b?.value;
  }
  get terminals() {
    return this.f.map((term) => term.value);
  }
  constructor(supportsProcesses, R, extHostRpc) {
    super();
    this.R = R;
    this.f = [];
    this.g = /* @__PURE__ */ new Map();
    this.h = {};
    this.j = {};
    this.m = {};
    this.n = /* @__PURE__ */ new Map();
    this.w = this.B(new $4c());
    this.z = /* @__PURE__ */ new Set();
    this.C = /* @__PURE__ */ new Map();
    this.D = /* @__PURE__ */ new Map();
    this.F = /* @__PURE__ */ new Map();
    this.G = /* @__PURE__ */ new Map();
    this.H = /* @__PURE__ */ new Map();
    this.I = new $ze();
    this.onDidCloseTerminal = this.I.event;
    this.J = new $ze();
    this.onDidOpenTerminal = this.J.event;
    this.L = new $ze();
    this.onDidChangeActiveTerminal = this.L.event;
    this.M = new $ze();
    this.onDidChangeTerminalDimensions = this.M.event;
    this.N = new $ze();
    this.onDidChangeTerminalState = this.N.event;
    this.O = new $ze();
    this.onDidChangeShell = this.O.event;
    this.P = new $ze({
      onWillAddFirstListener: () => this.a.$startSendingDataEvents(),
      onDidRemoveLastListener: () => this.a.$stopSendingDataEvents()
    });
    this.onDidWriteTerminalData = this.P.event;
    this.Q = new $ze({
      onWillAddFirstListener: () => this.a.$startSendingCommandEvents(),
      onDidRemoveLastListener: () => this.a.$stopSendingCommandEvents()
    });
    this.onDidExecuteTerminalCommand = this.Q.event;
    this.a = extHostRpc.getProxy($xT.MainThreadTerminalService);
    this.y = new $kRb(this.a.$sendProcessData);
    this.a.$registerProcessSupport(supportsProcesses);
    this.R.registerArgumentProcessor({
      processArgument: (arg) => {
        const deserialize = (arg2) => {
          const cast = arg2;
          return this.getTerminalById(cast.instanceId)?.value;
        };
        switch (arg?.$mid) {
          case 15:
            return deserialize(arg);
          default: {
            if (Array.isArray(arg)) {
              for (let i = 0; i < arg.length; i++) {
                if (arg[i].$mid === 15) {
                  arg[i] = deserialize(arg[i]);
                } else {
                  break;
                }
              }
            }
            return arg;
          }
        }
      }
    });
    this.B({
      dispose: () => {
        for (const [_, terminalProcess] of this.g) {
          terminalProcess.shutdown(true);
        }
      }
    });
  }
  getDefaultShell(useAutomationShell) {
    const profile = useAutomationShell ? this.u : this.s;
    return profile?.path || "";
  }
  getDefaultShellArgs(useAutomationShell) {
    const profile = useAutomationShell ? this.u : this.s;
    return profile?.args || [];
  }
  createExtensionTerminal(options2, internalOptions) {
    const terminal = new $zxc(this.a, $ps(), options2, options2.name);
    const p = new ExtHostPseudoterminal(options2.pty);
    terminal.createExtensionTerminal(options2.location, internalOptions, this.S(options2, internalOptions).resolvedExtHostIdentifier, asTerminalIcon(options2.iconPath), asTerminalColor(options2.color)).then((id2) => {
      const disposable = this.U(id2, p);
      this.h[id2] = disposable;
    });
    this.f.push(terminal);
    return terminal.value;
  }
  S(options2, internalOptions) {
    internalOptions = internalOptions ? internalOptions : {};
    if (options2.location && typeof options2.location === "object" && "parentTerminal" in options2.location) {
      const parentTerminal = options2.location.parentTerminal;
      if (parentTerminal) {
        const parentExtHostTerminal = this.f.find((t) => t.value === parentTerminal);
        if (parentExtHostTerminal) {
          internalOptions.resolvedExtHostIdentifier = parentExtHostTerminal._id;
        }
      }
    } else if (options2.location && typeof options2.location !== "object") {
      internalOptions.location = options2.location;
    } else if (internalOptions.location && typeof internalOptions.location === "object" && "splitActiveTerminal" in internalOptions.location) {
      internalOptions.location = { splitActiveTerminal: true };
    }
    return internalOptions;
  }
  attachPtyToTerminal(id2, pty) {
    const terminal = this.getTerminalById(id2);
    if (!terminal) {
      throw new Error(`Cannot resolve terminal with id ${id2} for virtual process`);
    }
    const p = new ExtHostPseudoterminal(pty);
    const disposable = this.U(id2, p);
    this.h[id2] = disposable;
  }
  async $acceptActiveTerminalChanged(id2) {
    const original = this.b;
    if (id2 === null) {
      this.b = void 0;
      if (original !== this.b) {
        this.L.fire(this.b);
      }
      return;
    }
    const terminal = this.getTerminalById(id2);
    if (terminal) {
      this.b = terminal;
      if (original !== this.b) {
        this.L.fire(this.b.value);
      }
    }
  }
  async $acceptTerminalProcessData(id2, data) {
    const terminal = this.getTerminalById(id2);
    if (terminal) {
      this.P.fire({ terminal: terminal.value, data });
    }
  }
  async $acceptTerminalDimensions(id2, cols, rows) {
    const terminal = this.getTerminalById(id2);
    if (terminal) {
      if (terminal.setDimensions(cols, rows)) {
        this.M.fire({
          terminal: terminal.value,
          dimensions: terminal.value.dimensions
        });
      }
    }
  }
  async $acceptDidExecuteCommand(id2, command) {
    const terminal = this.getTerminalById(id2);
    if (terminal) {
      this.Q.fire({ terminal: terminal.value, ...command });
    }
  }
  async $acceptTerminalMaximumDimensions(id2, cols, rows) {
    this.g.get(id2)?.resize(cols, rows);
  }
  async $acceptTerminalTitleChange(id2, name) {
    const terminal = this.getTerminalById(id2);
    if (terminal) {
      terminal.name = name;
    }
  }
  async $acceptTerminalClosed(id2, exitCode, exitReason) {
    const index = this.Y(this.f, id2);
    if (index !== null) {
      const terminal = this.f.splice(index, 1)[0];
      terminal.setExitStatus(exitCode, exitReason);
      this.I.fire(terminal.value);
    }
  }
  $acceptTerminalOpened(id2, extHostTerminalId, name, shellLaunchConfigDto) {
    if (extHostTerminalId) {
      const index = this.Y(this.f, extHostTerminalId);
      if (index !== null) {
        this.f[index]._id = id2;
        this.J.fire(this.terminals[index]);
        this.f[index].isOpen = true;
        return;
      }
    }
    const creationOptions = {
      name: shellLaunchConfigDto.name,
      shellPath: shellLaunchConfigDto.executable,
      shellArgs: shellLaunchConfigDto.args,
      cwd: typeof shellLaunchConfigDto.cwd === "string" ? shellLaunchConfigDto.cwd : URI.revive(shellLaunchConfigDto.cwd),
      env: shellLaunchConfigDto.env,
      hideFromUser: shellLaunchConfigDto.hideFromUser
    };
    const terminal = new $zxc(this.a, id2, creationOptions, name);
    this.f.push(terminal);
    this.J.fire(terminal.value);
    terminal.isOpen = true;
  }
  async $acceptTerminalProcessId(id2, processId) {
    const terminal = this.getTerminalById(id2);
    terminal?._setProcessId(processId);
  }
  async $startExtensionTerminal(id2, initialDimensions) {
    const terminal = this.getTerminalById(id2);
    if (!terminal) {
      return { message: localize(2768, null, id2) };
    }
    if (!terminal.isOpen) {
      await new Promise((r) => {
        const listener = this.onDidOpenTerminal(async (e) => {
          if (e === terminal.value) {
            listener.dispose();
            r();
          }
        });
      });
    }
    const terminalProcess = this.g.get(id2);
    if (terminalProcess) {
      terminalProcess.startSendingEvents(initialDimensions);
    } else {
      this.j[id2] = { initialDimensions };
    }
    return void 0;
  }
  U(id2, p) {
    const disposables = new $2c();
    disposables.add(p.onProcessReady((e) => this.a.$sendProcessReady(id2, e.pid, e.cwd, e.windowsPty)));
    disposables.add(p.onDidChangeProperty((property) => this.a.$sendProcessProperty(id2, property)));
    this.y.startBuffering(id2, p.onProcessData);
    disposables.add(p.onProcessExit((exitCode) => this.W(id2, exitCode)));
    this.g.set(id2, p);
    const awaitingStart = this.j[id2];
    if (awaitingStart && p instanceof ExtHostPseudoterminal) {
      p.startSendingEvents(awaitingStart.initialDimensions);
      delete this.j[id2];
    }
    return disposables;
  }
  $acceptProcessAckDataEvent(id2, charCount) {
    this.g.get(id2)?.acknowledgeDataEvent(charCount);
  }
  $acceptProcessInput(id2, data) {
    this.g.get(id2)?.input(data);
  }
  $acceptTerminalInteraction(id2) {
    const terminal = this.getTerminalById(id2);
    if (terminal?.setInteractedWith()) {
      this.N.fire(terminal.value);
    }
  }
  $acceptTerminalSelection(id2, selection) {
    this.getTerminalById(id2)?.setSelection(selection);
  }
  $acceptProcessResize(id2, cols, rows) {
    try {
      this.g.get(id2)?.resize(cols, rows);
    } catch (error) {
      if (error.code !== "EPIPE" && error.code !== "ERR_IPC_CHANNEL_CLOSED") {
        throw error;
      }
    }
  }
  $acceptProcessShutdown(id2, immediate) {
    this.g.get(id2)?.shutdown(immediate);
  }
  $acceptProcessRequestInitialCwd(id2) {
    this.g.get(id2)?.getInitialCwd().then((initialCwd) => this.a.$sendProcessProperty(id2, { type: "initialCwd", value: initialCwd }));
  }
  $acceptProcessRequestCwd(id2) {
    this.g.get(id2)?.getCwd().then((cwd2) => this.a.$sendProcessProperty(id2, { type: "cwd", value: cwd2 }));
  }
  $acceptProcessRequestLatency(id2) {
    return Promise.resolve(id2);
  }
  registerProfileProvider(extension, id2, provider) {
    if (this.D.has(id2)) {
      throw new Error(`Terminal profile provider "${id2}" already registered`);
    }
    this.D.set(id2, provider);
    this.a.$registerProfileProvider(id2, extension.identifier.value);
    return new $zT(() => {
      this.D.delete(id2);
      this.a.$unregisterProfileProvider(id2);
    });
  }
  registerTerminalCompletionProvider(extension, provider, ...triggerCharacters) {
    if (this.C.has(provider.id)) {
      throw new Error(`Terminal completion provider "${provider.id}" already registered`);
    }
    this.C.set(provider.id, provider);
    this.a.$registerCompletionProvider(provider.id, extension.identifier.value, ...triggerCharacters);
    return new $zT(() => {
      this.C.delete(provider.id);
      this.a.$unregisterCompletionProvider(provider.id);
    });
  }
  async $provideTerminalCompletions(id2, options2) {
    const token = new $ad().token;
    if (token.isCancellationRequested || !this.activeTerminal) {
      return void 0;
    }
    const provider = this.C.get(id2);
    if (!provider) {
      return;
    }
    const completions = await provider.provideTerminalCompletions(this.activeTerminal, options2, token);
    if (completions === null || completions === void 0) {
      return;
    }
    return completions;
  }
  registerTerminalQuickFixProvider(id2, extensionId, provider) {
    if (this.F.has(id2)) {
      throw new Error(`Terminal quick fix provider "${id2}" is already registered`);
    }
    this.F.set(id2, provider);
    this.a.$registerQuickFixProvider(id2, extensionId);
    return new $zT(() => {
      this.F.delete(id2);
      this.a.$unregisterQuickFixProvider(id2);
    });
  }
  async $provideTerminalQuickFixes(id2, matchResult) {
    const token = new $ad().token;
    if (token.isCancellationRequested) {
      return;
    }
    const provider = this.F.get(id2);
    if (!provider) {
      return;
    }
    const quickFixes = await provider.provideTerminalQuickFixes(matchResult, token);
    if (quickFixes === null || Array.isArray(quickFixes) && quickFixes.length === 0) {
      return void 0;
    }
    const store = new $2c();
    this.w.value = store;
    if (!Array.isArray(quickFixes)) {
      return quickFixes ? TerminalQuickFix.from(quickFixes, this.R.converter, store) : void 0;
    }
    const result = [];
    for (const fix of quickFixes) {
      const converted = TerminalQuickFix.from(fix, this.R.converter, store);
      if (converted) {
        result.push(converted);
      }
    }
    return result;
  }
  async $createContributedProfileTerminal(id2, options2) {
    const token = new $ad().token;
    let profile = await this.D.get(id2)?.provideTerminalProfile(token);
    if (token.isCancellationRequested) {
      return;
    }
    if (profile && !("options" in profile)) {
      profile = { options: profile };
    }
    if (!profile || !("options" in profile)) {
      throw new Error(`No terminal profile options provided for id "${id2}"`);
    }
    if ("pty" in profile.options) {
      this.createExtensionTerminal(profile.options, options2);
      return;
    }
    this.createTerminalFromOptions(profile.options, options2);
  }
  registerLinkProvider(provider) {
    this.z.add(provider);
    if (this.z.size === 1) {
      this.a.$startLinkProvider();
    }
    return new $zT(() => {
      this.z.delete(provider);
      if (this.z.size === 0) {
        this.a.$stopLinkProvider();
      }
    });
  }
  async $provideLinks(terminalId, line) {
    const terminal = this.getTerminalById(terminalId);
    if (!terminal) {
      return [];
    }
    this.G.delete(terminalId);
    const oldToken = this.H.get(terminalId);
    oldToken?.dispose(true);
    const cancellationSource = new $ad();
    this.H.set(terminalId, cancellationSource);
    const result = [];
    const context = { terminal: terminal.value, line };
    const promises8 = [];
    for (const provider of this.z) {
      promises8.push(Promises.withAsyncBody(async (r) => {
        cancellationSource.token.onCancellationRequested(() => r({ provider, links: [] }));
        const links = await provider.provideTerminalLinks(context, cancellationSource.token) || [];
        if (!cancellationSource.token.isCancellationRequested) {
          r({ provider, links });
        }
      }));
    }
    const provideResults = await Promise.all(promises8);
    if (cancellationSource.token.isCancellationRequested) {
      return [];
    }
    const cacheLinkMap = /* @__PURE__ */ new Map();
    for (const provideResult of provideResults) {
      if (provideResult && provideResult.links.length > 0) {
        result.push(...provideResult.links.map((providerLink) => {
          const link2 = {
            id: nextLinkId++,
            startIndex: providerLink.startIndex,
            length: providerLink.length,
            label: providerLink.tooltip
          };
          cacheLinkMap.set(link2.id, {
            provider: provideResult.provider,
            link: providerLink
          });
          return link2;
        }));
      }
    }
    this.G.set(terminalId, cacheLinkMap);
    return result;
  }
  $activateLink(terminalId, linkId) {
    const cachedLink = this.G.get(terminalId)?.get(linkId);
    if (!cachedLink) {
      return;
    }
    cachedLink.provider.handleTerminalLink(cachedLink.link);
  }
  W(id2, exitCode) {
    this.y.stopBuffering(id2);
    this.g.delete(id2);
    delete this.j[id2];
    const processDiposable = this.h[id2];
    if (processDiposable) {
      processDiposable.dispose();
      delete this.h[id2];
    }
    this.a.$sendProcessExit(id2, exitCode);
  }
  getTerminalById(id2) {
    return this.X(this.f, id2);
  }
  getTerminalIdByApiObject(terminal) {
    const index = this.f.findIndex((item) => {
      return item.value === terminal;
    });
    return index >= 0 ? index : null;
  }
  X(array, id2) {
    const index = this.Y(array, id2);
    return index !== null ? array[index] : null;
  }
  Y(array, id2) {
    const index = array.findIndex((item) => {
      return item._id === id2;
    });
    return index >= 0 ? index : null;
  }
  getEnvironmentVariableCollection(extension) {
    let collection = this.n.get(extension.identifier.value);
    if (!collection) {
      collection = this.B(new UnifiedEnvironmentVariableCollection());
      this.$(extension.identifier.value, collection);
    }
    return collection.getScopedEnvironmentVariableCollection(void 0);
  }
  Z(extensionIdentifier, collection) {
    const serialized = $BB(collection.map);
    const serializedDescription = $CB(collection.descriptionMap);
    this.a.$setEnvironmentVariableCollection(extensionIdentifier, collection.persistent, serialized.length === 0 ? void 0 : serialized, serializedDescription);
  }
  $initEnvironmentVariableCollections(collections) {
    collections.forEach((entry) => {
      const extensionIdentifier = entry[0];
      const collection = this.B(new UnifiedEnvironmentVariableCollection(entry[1]));
      this.$(extensionIdentifier, collection);
    });
  }
  $acceptDefaultProfile(profile, automationProfile) {
    const oldProfile = this.s;
    this.s = profile;
    this.u = automationProfile;
    if (oldProfile?.path !== profile.path) {
      this.O.fire(profile.path);
    }
  }
  $(extensionIdentifier, collection) {
    this.n.set(extensionIdentifier, collection);
    this.B(collection.onDidChangeCollection(() => {
      this.Z(extensionIdentifier, collection);
    }));
  }
};
$Axc = __decorate([
  __param(1, $CW),
  __param(2, $gW)
], $Axc);
var UnifiedEnvironmentVariableCollection = class extends $3c {
  get persistent() {
    return this.b;
  }
  set persistent(value) {
    this.b = value;
    this.f.fire();
  }
  get onDidChangeCollection() {
    return this.f && this.f.event;
  }
  constructor(serialized) {
    super();
    this.map = /* @__PURE__ */ new Map();
    this.a = /* @__PURE__ */ new Map();
    this.descriptionMap = /* @__PURE__ */ new Map();
    this.b = true;
    this.f = new $ze();
    this.map = new Map(serialized);
  }
  getScopedEnvironmentVariableCollection(scope) {
    const scopedCollectionKey = this.j(scope);
    let scopedCollection = this.a.get(scopedCollectionKey);
    if (!scopedCollection) {
      scopedCollection = new ScopedEnvironmentVariableCollection(this, scope);
      this.a.set(scopedCollectionKey, scopedCollection);
      this.B(scopedCollection.onDidChangeCollection(() => this.f.fire()));
    }
    return scopedCollection;
  }
  replace(variable, value, options2, scope) {
    this.g(variable, { value, type: EnvironmentVariableMutatorType.Replace, options: options2 ?? { applyAtProcessCreation: true }, scope });
  }
  append(variable, value, options2, scope) {
    this.g(variable, { value, type: EnvironmentVariableMutatorType.Append, options: options2 ?? { applyAtProcessCreation: true }, scope });
  }
  prepend(variable, value, options2, scope) {
    this.g(variable, { value, type: EnvironmentVariableMutatorType.Prepend, options: options2 ?? { applyAtProcessCreation: true }, scope });
  }
  g(variable, mutator) {
    if (mutator.options && mutator.options.applyAtProcessCreation === false && !mutator.options.applyAtShellIntegration) {
      throw new Error("EnvironmentVariableMutatorOptions must apply at either process creation or shell integration");
    }
    const key = this.h(variable, mutator.scope);
    const current = this.map.get(key);
    const newOptions = mutator.options ? {
      applyAtProcessCreation: mutator.options.applyAtProcessCreation ?? false,
      applyAtShellIntegration: mutator.options.applyAtShellIntegration ?? false
    } : {
      applyAtProcessCreation: true
    };
    if (!current || current.value !== mutator.value || current.type !== mutator.type || current.options?.applyAtProcessCreation !== newOptions.applyAtProcessCreation || current.options?.applyAtShellIntegration !== newOptions.applyAtShellIntegration || current.scope?.workspaceFolder?.index !== mutator.scope?.workspaceFolder?.index) {
      const key2 = this.h(variable, mutator.scope);
      const value = {
        variable,
        ...mutator,
        options: newOptions
      };
      this.map.set(key2, value);
      this.f.fire();
    }
  }
  get(variable, scope) {
    const key = this.h(variable, scope);
    const value = this.map.get(key);
    return value ? convertMutator(value) : void 0;
  }
  h(variable, scope) {
    const scopeKey = this.j(scope);
    return scopeKey.length ? `${variable}:::${scopeKey}` : variable;
  }
  j(scope) {
    return this.m(scope?.workspaceFolder) ?? "";
  }
  m(workspaceFolder) {
    return workspaceFolder ? workspaceFolder.uri.toString() : void 0;
  }
  getVariableMap(scope) {
    const map = /* @__PURE__ */ new Map();
    for (const [_, value] of this.map) {
      if (this.j(value.scope) === this.j(scope)) {
        map.set(value.variable, convertMutator(value));
      }
    }
    return map;
  }
  delete(variable, scope) {
    const key = this.h(variable, scope);
    this.map.delete(key);
    this.f.fire();
  }
  clear(scope) {
    if (scope?.workspaceFolder) {
      for (const [key, mutator] of this.map) {
        if (mutator.scope?.workspaceFolder?.index === scope.workspaceFolder.index) {
          this.map.delete(key);
        }
      }
      this.n(scope);
    } else {
      this.map.clear();
      this.descriptionMap.clear();
    }
    this.f.fire();
  }
  setDescription(description, scope) {
    const key = this.j(scope);
    const current = this.descriptionMap.get(key);
    if (!current || current.description !== description) {
      let descriptionStr;
      if (typeof description === "string") {
        descriptionStr = description;
      } else {
        descriptionStr = description?.value.split("\n\n")[0];
      }
      const value = { description: descriptionStr, scope };
      this.descriptionMap.set(key, value);
      this.f.fire();
    }
  }
  getDescription(scope) {
    const key = this.j(scope);
    return this.descriptionMap.get(key)?.description;
  }
  n(scope) {
    const key = this.j(scope);
    this.descriptionMap.delete(key);
  }
};
var ScopedEnvironmentVariableCollection = class {
  get persistent() {
    return this.b.persistent;
  }
  set persistent(value) {
    this.b.persistent = value;
  }
  get onDidChangeCollection() {
    return this.a && this.a.event;
  }
  constructor(b, d) {
    this.b = b;
    this.d = d;
    this.a = new $ze();
  }
  getScoped(scope) {
    return this.b.getScopedEnvironmentVariableCollection(scope);
  }
  replace(variable, value, options2) {
    this.b.replace(variable, value, options2, this.d);
  }
  append(variable, value, options2) {
    this.b.append(variable, value, options2, this.d);
  }
  prepend(variable, value, options2) {
    this.b.prepend(variable, value, options2, this.d);
  }
  get(variable) {
    return this.b.get(variable, this.d);
  }
  forEach(callback, thisArg) {
    this.b.getVariableMap(this.d).forEach((value, variable) => callback.call(thisArg, variable, value, this), this.d);
  }
  [Symbol.iterator]() {
    return this.b.getVariableMap(this.d).entries();
  }
  delete(variable) {
    this.b.delete(variable, this.d);
    this.a.fire(void 0);
  }
  clear() {
    this.b.clear(this.d);
  }
  set description(description) {
    this.b.setDescription(description, this.d);
  }
  get description() {
    return this.b.getDescription(this.d);
  }
};
var $Bxc = class $Bxc2 extends $Axc {
  constructor(extHostCommands, extHostRpc) {
    super(false, extHostCommands, extHostRpc);
  }
  createTerminal(name, shellPath, shellArgs) {
    throw new $sb();
  }
  createTerminalFromOptions(options2, internalOptions) {
    throw new $sb();
  }
};
$Bxc = __decorate([
  __param(0, $CW),
  __param(1, $gW)
], $Bxc);
function asTerminalIcon(iconPath) {
  if (!iconPath || typeof iconPath === "string") {
    return void 0;
  }
  if (!("id" in iconPath)) {
    return iconPath;
  }
  return {
    id: iconPath.id,
    color: iconPath.color
  };
}
function asTerminalColor(color2) {
  return ThemeColor.isThemeColor(color2) ? color2 : void 0;
}
function convertMutator(mutator) {
  const newMutator = { ...mutator };
  delete newMutator.scope;
  newMutator.options = newMutator.options ?? void 0;
  delete newMutator.variable;
  return newMutator;
}

// out-build/vs/platform/progress/common/progress.js
var $TJ = $Qk("progressService");
var ProgressLocation3;
(function(ProgressLocation4) {
  ProgressLocation4[ProgressLocation4["Explorer"] = 1] = "Explorer";
  ProgressLocation4[ProgressLocation4["Scm"] = 3] = "Scm";
  ProgressLocation4[ProgressLocation4["Extensions"] = 5] = "Extensions";
  ProgressLocation4[ProgressLocation4["Window"] = 10] = "Window";
  ProgressLocation4[ProgressLocation4["Notification"] = 15] = "Notification";
  ProgressLocation4[ProgressLocation4["Dialog"] = 20] = "Dialog";
})(ProgressLocation3 || (ProgressLocation3 = {}));
var $UJ = Object.freeze({
  total() {
  },
  worked() {
  },
  done() {
  }
});
var $VJ = class {
  static {
    this.None = Object.freeze({ report() {
    } });
  }
  get value() {
    return this.a;
  }
  constructor(b) {
    this.b = b;
  }
  report(item) {
    this.a = item;
    this.b(this.a);
  }
};
var $XJ = class $XJ2 extends $3c {
  constructor(options2, progressService) {
    super();
    this.a = new $gi();
    progressService.withProgress(options2, (reporter) => {
      this.b = reporter;
      if (this.c) {
        reporter.report(this.c);
      }
      return this.a.p;
    });
    this.B($1c(() => this.a.complete()));
  }
  report(step) {
    if (this.b) {
      this.b.report(step);
    } else {
      this.c = step;
    }
  }
};
$XJ = __decorate([
  __param(1, $TJ)
], $XJ);
var $ZJ = $Qk("editorProgressService");

// out-build/vs/workbench/services/authentication/common/authentication.js
var $wS = "__";
var $xS = $Qk("IAuthenticationService");
var $yS = $Qk("IAuthenticationExtensionsService");

// out-build/vs/workbench/api/common/extHostAuthentication.js
var $Vwc = $Qk("IExtHostAuthentication");
var $Wwc = class $Wwc2 {
  constructor(extHostRpc) {
    this.b = /* @__PURE__ */ new Map();
    this.c = new $ze();
    this.d = new TaskSingler();
    this.a = extHostRpc.getProxy($xT.MainThreadAuthentication);
  }
  /**
   * This sets up an event that will fire when the auth sessions change with a built-in filter for the extensionId
   * if a session change only affects a specific extension.
   * @param extensionId The extension that is interested in the event.
   * @returns An event with a built-in filter for the extensionId
   */
  getExtensionScopedSessionsEvent(extensionId) {
    const normalizedExtensionId = extensionId.toLowerCase();
    return Event.chain(this.c.event, ($) => $.filter((e) => !e.extensionIdFilter || e.extensionIdFilter.includes(normalizedExtensionId)).map((e) => ({ provider: e.provider })));
  }
  async getSession(requestingExtension, providerId, scopes, options2 = {}) {
    const extensionId = $5z.toKey(requestingExtension.identifier);
    const sortedScopes = [...scopes].sort().join(" ");
    return await this.d.getOrCreate(`${extensionId} ${providerId} ${sortedScopes}`, async () => {
      await this.a.$ensureProvider(providerId);
      const extensionName = requestingExtension.displayName || requestingExtension.name;
      return this.a.$getSession(providerId, scopes, extensionId, extensionName, options2);
    });
  }
  async getAccounts(providerId) {
    await this.a.$ensureProvider(providerId);
    return await this.a.$getAccounts(providerId);
  }
  async removeSession(providerId, sessionId) {
    const providerData = this.b.get(providerId);
    if (!providerData) {
      return this.a.$removeSession(providerId, sessionId);
    }
    return providerData.provider.removeSession(sessionId);
  }
  registerAuthenticationProvider(id2, label, provider, options2) {
    if (this.b.get(id2)) {
      throw new Error(`An authentication provider with id '${id2}' is already registered.`);
    }
    this.b.set(id2, { label, provider, options: options2 ?? { supportsMultipleAccounts: false } });
    const listener = provider.onDidChangeSessions((e) => this.a.$sendDidChangeSessions(id2, e));
    this.a.$registerAuthenticationProvider(id2, label, options2?.supportsMultipleAccounts ?? false);
    return new $zT(() => {
      listener.dispose();
      this.b.delete(id2);
      this.a.$unregisterAuthenticationProvider(id2);
    });
  }
  async $createSession(providerId, scopes, options2) {
    const providerData = this.b.get(providerId);
    if (providerData) {
      return await providerData.provider.createSession(scopes, options2);
    }
    throw new Error(`Unable to find authentication provider with handle: ${providerId}`);
  }
  async $removeSession(providerId, sessionId) {
    const providerData = this.b.get(providerId);
    if (providerData) {
      return await providerData.provider.removeSession(sessionId);
    }
    throw new Error(`Unable to find authentication provider with handle: ${providerId}`);
  }
  async $getSessions(providerId, scopes, options2) {
    const providerData = this.b.get(providerId);
    if (providerData) {
      return await providerData.provider.getSessions(scopes, options2);
    }
    throw new Error(`Unable to find authentication provider with handle: ${providerId}`);
  }
  $onDidChangeAuthenticationSessions(id2, label, extensionIdFilter) {
    if (!id2.startsWith($wS)) {
      this.c.fire({ provider: { id: id2, label }, extensionIdFilter });
    }
    return Promise.resolve();
  }
};
$Wwc = __decorate([
  __param(0, $gW)
], $Wwc);
var TaskSingler = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  getOrCreate(key, promiseFactory) {
    const inFlight = this.a.get(key);
    if (inFlight) {
      return inFlight;
    }
    const promise = promiseFactory().finally(() => this.a.delete(key));
    this.a.set(key, promise);
    return promise;
  }
};

// out-build/vs/workbench/api/common/extHostLanguageModels.js
var $Zwc_1;
var $Ywc = $Qk("IExtHostLanguageModels");
var LanguageModelResponseStream = class {
  constructor(option, stream) {
    this.option = option;
    this.stream = new $mi();
    this.stream = stream ?? new $mi();
  }
};
var LanguageModelResponse = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = new $mi();
    this.c = false;
    const that = this;
    this.apiObject = {
      // result: promise,
      get stream() {
        return that.b.asyncIterable;
      },
      get text() {
        return $ji.map(that.b.asyncIterable, (part) => {
          if (part instanceof $1V) {
            return part.value;
          } else {
            return void 0;
          }
        }).coalesce();
      }
    };
  }
  *d() {
    if (this.a.size > 0) {
      for (const [, value] of this.a) {
        yield value.stream;
      }
    } else {
      yield this.b;
    }
  }
  handleFragment(fragment) {
    if (this.c) {
      return;
    }
    let res = this.a.get(fragment.index);
    if (!res) {
      if (this.a.size === 0) {
        res = new LanguageModelResponseStream(fragment.index, this.b);
      } else {
        res = new LanguageModelResponseStream(fragment.index);
      }
      this.a.set(fragment.index, res);
    }
    let out;
    if (fragment.part.type === "text") {
      out = new $1V(fragment.part.value);
    } else {
      out = new $ZV(fragment.part.toolCallId, fragment.part.name, fragment.part.parameters);
    }
    res.stream.emitOne(out);
  }
  reject(err) {
    this.c = true;
    for (const stream of this.d()) {
      stream.reject(err);
    }
  }
  resolve() {
    this.c = true;
    for (const stream of this.d()) {
      stream.resolve();
    }
  }
};
var $Zwc = class $Zwc2 {
  static {
    $Zwc_1 = this;
  }
  static {
    this.a = 1;
  }
  constructor(extHostRpc, k, l) {
    this.k = k;
    this.l = l;
    this.c = new $ze();
    this.d = new $ze();
    this.onDidChangeProviders = this.d.event;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.h = new $7z();
    this.i = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.t = /* @__PURE__ */ new Set();
    this.b = extHostRpc.getProxy($xT.MainThreadLanguageModels);
  }
  dispose() {
    this.c.dispose();
    this.d.dispose();
  }
  registerLanguageModel(extension, identifier, provider, metadata) {
    const handle = $Zwc_1.a++;
    this.f.set(handle, { extension: extension.identifier, provider, languageModelId: identifier });
    let auth;
    if (metadata.auth) {
      auth = {
        providerLabel: extension.displayName || extension.name,
        accountLabel: typeof metadata.auth === "object" ? metadata.auth.label : void 0
      };
    }
    this.b.$registerLanguageModelProvider(handle, `${$5z.toKey(extension.identifier)}/${identifier}`, {
      extension: extension.identifier,
      id: identifier,
      vendor: metadata.vendor ?? $5z.toKey(extension.identifier),
      name: metadata.name ?? "",
      family: metadata.family ?? "",
      version: metadata.version,
      maxInputTokens: metadata.maxInputTokens,
      maxOutputTokens: metadata.maxOutputTokens,
      auth,
      targetExtensions: metadata.extensions,
      isDefault: metadata.isDefault,
      isUserSelectable: metadata.isUserSelectable
    });
    const responseReceivedListener = provider.onDidReceiveLanguageModelResponse2?.(({ extensionId, participant, tokenCount }) => {
      this.b.$whenLanguageModelChatRequestMade(identifier, new $5z(extensionId), participant, tokenCount);
    });
    return $1c(() => {
      this.f.delete(handle);
      this.b.$unregisterProvider(handle);
      responseReceivedListener?.dispose();
    });
  }
  async $startChatRequest(handle, requestId, from, messages, options2, token) {
    const data = this.f.get(handle);
    if (!data) {
      throw new Error("Provider not found");
    }
    const progress = new $VJ(async (fragment) => {
      if (token.isCancellationRequested) {
        this.k.warn(`[CHAT](${data.extension.value}) CANNOT send progress because the REQUEST IS CANCELLED`);
        return;
      }
      let part;
      if (fragment.part instanceof $ZV) {
        part = { type: "tool_use", name: fragment.part.name, parameters: fragment.part.input, toolCallId: fragment.part.callId };
      } else if (fragment.part instanceof $1V) {
        part = { type: "text", value: fragment.part.value };
      }
      if (!part) {
        this.k.warn(`[CHAT](${data.extension.value}) UNKNOWN part ${JSON.stringify(fragment)}`);
        return;
      }
      this.b.$reportResponsePart(requestId, { index: fragment.index, part });
    });
    let p;
    if (data.provider.provideLanguageModelResponse2) {
      p = Promise.resolve(data.provider.provideLanguageModelResponse2(messages.map(LanguageModelChatMessage.to), options2, $5z.toKey(from), progress, token));
    } else {
      p = Promise.resolve(data.provider.provideLanguageModelResponse(messages.map(LanguageModelChatMessage.to), options2, $5z.toKey(from), progress, token));
    }
    p.then(() => {
      this.b.$reportResponseDone(requestId, void 0);
    }, (err) => {
      this.b.$reportResponseDone(requestId, $ib(err));
    });
  }
  //#region --- token counting
  $provideTokenLength(handle, value, token) {
    const data = this.f.get(handle);
    if (!data) {
      return Promise.resolve(0);
    }
    return Promise.resolve(data.provider.provideTokenCount(value, token));
  }
  //#region --- making request
  $acceptChatModelMetadata(data) {
    if (data.added) {
      for (const { identifier, metadata } of data.added) {
        this.g.set(identifier, { metadata, apiObjects: new $7z() });
      }
    }
    if (data.removed) {
      for (const id2 of data.removed) {
        this.g.delete(id2);
        for (const [key, value] of this.i) {
          if (value.languageModelId === id2) {
            value.res.reject(new $lb());
            this.i.delete(key);
          }
        }
      }
    }
    data.added?.forEach((added) => this.r(added.metadata));
    this.d.fire(void 0);
  }
  async getDefaultLanguageModel(extension) {
    const defaultModelId = Iterable.find(this.g.entries(), ([, value]) => !!value.metadata.isDefault)?.[0];
    if (!defaultModelId) {
      return;
    }
    return this.getLanguageModelByIdentifier(extension, defaultModelId);
  }
  async getLanguageModelByIdentifier(extension, identifier) {
    const data = this.g.get(identifier);
    if (!data) {
      return;
    }
    if (this.q(extension.identifier, data.metadata)) {
      await this.r(data.metadata);
    }
    let apiObject = data.apiObjects.get(extension.identifier);
    if (!apiObject) {
      const that = this;
      apiObject = {
        id: data.metadata.id,
        vendor: data.metadata.vendor,
        family: data.metadata.family,
        version: data.metadata.version,
        name: data.metadata.name,
        maxInputTokens: data.metadata.maxInputTokens,
        countTokens(text, token) {
          if (!that.g.has(identifier)) {
            throw $6V.NotFound(identifier);
          }
          return that.s(identifier, text, token ?? CancellationToken.None);
        },
        sendRequest(messages, options2, token) {
          if (!that.g.has(identifier)) {
            throw $6V.NotFound(identifier);
          }
          return that.m(extension, identifier, messages, options2 ?? {}, token ?? CancellationToken.None);
        }
      };
      Object.freeze(apiObject);
      data.apiObjects.set(extension.identifier, apiObject);
    }
    return apiObject;
  }
  async selectLanguageModels(extension, selector) {
    const models = await this.b.$selectChatModels({ ...selector, extension: extension.identifier });
    const result = [];
    for (const identifier of models) {
      const model = await this.getLanguageModelByIdentifier(extension, identifier);
      if (model) {
        result.push(model);
      }
    }
    return result;
  }
  async m(extension, languageModelId, messages, options2, token) {
    const internalMessages = this.n(extension, messages);
    const from = extension.identifier;
    const metadata = this.g.get(languageModelId)?.metadata;
    if (!metadata || !this.g.has(languageModelId)) {
      throw $6V.NotFound(`Language model '${languageModelId}' is unknown.`);
    }
    if (this.q(from, metadata)) {
      const success = await this.o(extension, { identifier: metadata.extension, displayName: metadata.auth.providerLabel }, options2.justification, false);
      if (!success || !this.h.get(from)?.has(metadata.extension)) {
        throw $6V.NoPermissions(`Language model '${languageModelId}' cannot be used by '${from.value}'.`);
      }
    }
    if (options2.tools) {
      options2.tools = options2.tools.map((tool) => {
        return {
          ...tool,
          inputSchema: tool.inputSchema ?? tool.parametersSchema,
          parametersSchema: tool.inputSchema ?? tool.parametersSchema
        };
      });
    }
    try {
      const requestId = Math.random() * 1e6 | 0;
      const res = new LanguageModelResponse();
      this.i.set(requestId, { languageModelId, res });
      try {
        await this.b.$tryStartChatRequest(from, languageModelId, requestId, internalMessages, options2, token);
      } catch (error) {
        this.i.delete(requestId);
        throw error;
      }
      return res.apiObject;
    } catch (error) {
      if (error.name === $6V.name) {
        throw error;
      }
      throw new $6V(`Language model '${languageModelId}' errored: ${$1m(error)}`, "Unknown", error);
    }
  }
  n(extension, messages) {
    const internalMessages = [];
    for (const message of messages) {
      if (message.role === LanguageModelChatMessageRole.System) {
        $AN(extension, "languageModelSystem");
      }
      internalMessages.push(LanguageModelChatMessage.from(message));
    }
    return internalMessages;
  }
  async $acceptResponsePart(requestId, chunk) {
    const data = this.i.get(requestId);
    if (data) {
      data.res.handleFragment(chunk);
    }
  }
  async $acceptResponseDone(requestId, error) {
    const data = this.i.get(requestId);
    if (!data) {
      return;
    }
    this.i.delete(requestId);
    if (error) {
      data.res.reject($jb(error));
    } else {
      data.res.resolve();
    }
  }
  // BIG HACK: Using AuthenticationProviders to check access to Language Models
  async o(from, to, justification, silent) {
    const providerId = $wS + to.identifier.value;
    const session = await this.l.getSession(from, providerId, [], { silent: true });
    if (session) {
      this.$updateModelAccesslist([{ from: from.identifier, to: to.identifier, enabled: true }]);
      return true;
    }
    if (silent) {
      return false;
    }
    try {
      const detail = justification ? localize(2759, null, to.displayName, justification) : void 0;
      await this.l.getSession(from, providerId, [], { forceNewSession: { detail } });
      this.$updateModelAccesslist([{ from: from.identifier, to: to.identifier, enabled: true }]);
      return true;
    } catch (err) {
      return false;
    }
  }
  q(from, toMetadata) {
    return !!toMetadata.auth && !$5z.equals(toMetadata.extension, from);
  }
  async r(metadata) {
    if (!metadata.auth) {
      return;
    }
    for (const from of this.t) {
      try {
        await this.o(from, { identifier: metadata.extension, displayName: "" }, void 0, true);
      } catch (err) {
        this.k.error("Fake Auth request failed");
        this.k.error(err);
      }
    }
  }
  async s(languageModelId, value, token) {
    const data = this.g.get(languageModelId);
    if (!data) {
      throw $6V.NotFound(`Language model '${languageModelId}' is unknown.`);
    }
    const local = Iterable.find(this.f.values(), (candidate) => candidate.languageModelId === languageModelId);
    if (local) {
      return local.provider.provideTokenCount(value, token);
    }
    return this.b.$countTokens(languageModelId, typeof value === "string" ? value : LanguageModelChatMessage.from(value), token);
  }
  $updateModelAccesslist(data) {
    const updated = new Array();
    for (const { from, to, enabled } of data) {
      const set = this.h.get(from) ?? new $6z();
      const oldValue = set.has(to);
      if (oldValue !== enabled) {
        if (enabled) {
          set.add(to);
        } else {
          set.delete(to);
        }
        this.h.set(from, set);
        const newItem = { from, to };
        updated.push(newItem);
        this.c.fire(newItem);
      }
    }
  }
  createLanguageModelAccessInformation(from) {
    this.t.add(from);
    const that = this;
    const _onDidChangeAccess = Event.signal(Event.filter(this.c.event, (e) => $5z.equals(e.from, from.identifier)));
    const _onDidAddRemove = Event.signal(this.d.event);
    return {
      get onDidChange() {
        return Event.any(_onDidChangeAccess, _onDidAddRemove);
      },
      canSendRequest(chat) {
        let metadata;
        out: for (const [_, value] of that.g) {
          for (const candidate of value.apiObjects.values()) {
            if (candidate === chat) {
              metadata = value.metadata;
              break out;
            }
          }
        }
        if (!metadata) {
          return void 0;
        }
        if (!that.q(from.identifier, metadata)) {
          return true;
        }
        const list2 = that.h.get(from.identifier);
        if (!list2) {
          return void 0;
        }
        return list2.has(metadata.extension);
      }
    };
  }
  fileIsIgnored(extension, uri, token) {
    $AN(extension, "chatParticipantAdditions");
    return this.b.$fileIsIgnored(uri, token);
  }
  async $isFileIgnored(handle, uri, token) {
    const provider = this.j.get(handle);
    if (!provider) {
      throw new Error("Unknown LanguageModelIgnoredFileProvider");
    }
    return await provider.provideFileIgnored(URI.revive(uri), token) ?? false;
  }
  registerIgnoredFileProvider(extension, provider) {
    $AN(extension, "chatParticipantPrivate");
    const handle = $Zwc_1.a++;
    this.b.$registerFileIgnoreProvider(handle);
    this.j.set(handle, provider);
    return $1c(() => {
      this.b.$unregisterFileIgnoreProvider(handle);
      this.j.delete(handle);
    });
  }
};
$Zwc = $Zwc_1 = __decorate([
  __param(0, $gW),
  __param(1, $wn),
  __param(2, $Vwc)
], $Zwc);

// out-build/vs/base/common/labels.js
function $1t(path, isWindowsOS = $l) {
  if ($5g(path, isWindowsOS)) {
    return path.charAt(0).toUpperCase() + path.slice(1);
  }
  return path;
}
function $3t(path, userHome) {
  return path.replace(/^~($|\/|\\)/, `${userHome}$1`);
}
var Type;
(function(Type2) {
  Type2[Type2["TEXT"] = 0] = "TEXT";
  Type2[Type2["VARIABLE"] = 1] = "VARIABLE";
  Type2[Type2["SEPARATOR"] = 2] = "SEPARATOR";
})(Type || (Type = {}));

// out-build/vs/base/common/date.js
var minute = 60;
var hour = minute * 60;
var day = hour * 24;
var week = day * 7;
var month = day * 30;
var year = day * 365;
function $Tu(date) {
  return date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, "0") + "-" + String(date.getDate()).padStart(2, "0") + "T" + String(date.getHours()).padStart(2, "0") + ":" + String(date.getMinutes()).padStart(2, "0") + ":" + String(date.getSeconds()).padStart(2, "0") + "." + (date.getMilliseconds() / 1e3).toFixed(3).slice(2, 5) + "Z";
}
var $Uu = {
  DateTimeFormat(locales, options2) {
    try {
      return new Intl.DateTimeFormat(locales, options2);
    } catch {
      return new Intl.DateTimeFormat(void 0, options2);
    }
  },
  Collator(locales, options2) {
    try {
      return new Intl.Collator(locales, options2);
    } catch {
      return new Intl.Collator(void 0, options2);
    }
  },
  Segmenter(locales, options2) {
    try {
      return new Intl.Segmenter(locales, options2);
    } catch {
      return new Intl.Segmenter(void 0, options2);
    }
  },
  Locale(tag2, options2) {
    try {
      return new Intl.Locale(tag2, options2);
    } catch {
      return new Intl.Locale($j, options2);
    }
  }
};

// out-build/vs/base/common/uint.js
var Constants2;
(function(Constants3) {
  Constants3[Constants3["MAX_SAFE_SMALL_INTEGER"] = 1073741824] = "MAX_SAFE_SMALL_INTEGER";
  Constants3[Constants3["MIN_SAFE_SMALL_INTEGER"] = -1073741824] = "MIN_SAFE_SMALL_INTEGER";
  Constants3[Constants3["MAX_UINT_8"] = 255] = "MAX_UINT_8";
  Constants3[Constants3["MAX_UINT_16"] = 65535] = "MAX_UINT_16";
  Constants3[Constants3["MAX_UINT_32"] = 4294967295] = "MAX_UINT_32";
  Constants3[Constants3["UNICODE_SUPPLEMENTARY_PLANE_BEGIN"] = 65536] = "UNICODE_SUPPLEMENTARY_PLANE_BEGIN";
})(Constants2 || (Constants2 = {}));
function $tf(v) {
  if (v < 0) {
    return 0;
  }
  if (v > 255) {
    return 255;
  }
  return v | 0;
}
function $uf(v) {
  if (v < 0) {
    return 0;
  }
  if (v > 4294967295) {
    return 4294967295;
  }
  return v | 0;
}

// out-build/vs/editor/common/core/characterClassifier.js
var $fE = class _$fE {
  constructor(_defaultValue) {
    const defaultValue = $tf(_defaultValue);
    this.c = defaultValue;
    this.a = _$fE.d(defaultValue);
    this.b = /* @__PURE__ */ new Map();
  }
  static d(defaultValue) {
    const asciiMap = new Uint8Array(256);
    asciiMap.fill(defaultValue);
    return asciiMap;
  }
  set(charCode, _value) {
    const value = $tf(_value);
    if (charCode >= 0 && charCode < 256) {
      this.a[charCode] = value;
    } else {
      this.b.set(charCode, value);
    }
  }
  get(charCode) {
    if (charCode >= 0 && charCode < 256) {
      return this.a[charCode];
    } else {
      return this.b.get(charCode) || this.c;
    }
  }
  clear() {
    this.a.fill(this.c);
    this.b.clear();
  }
};
var Boolean2;
(function(Boolean3) {
  Boolean3[Boolean3["False"] = 0] = "False";
  Boolean3[Boolean3["True"] = 1] = "True";
})(Boolean2 || (Boolean2 = {}));

// out-build/vs/editor/common/core/wordCharacterClassifier.js
var WordCharacterClass;
(function(WordCharacterClass2) {
  WordCharacterClass2[WordCharacterClass2["Regular"] = 0] = "Regular";
  WordCharacterClass2[WordCharacterClass2["Whitespace"] = 1] = "Whitespace";
  WordCharacterClass2[WordCharacterClass2["WordSeparator"] = 2] = "WordSeparator";
})(WordCharacterClass || (WordCharacterClass = {}));
var $hE = class extends $fE {
  constructor(wordSeparators2, intlSegmenterLocales) {
    super(
      0
      /* WordCharacterClass.Regular */
    );
    this.e = null;
    this.f = null;
    this.g = [];
    this.intlSegmenterLocales = intlSegmenterLocales;
    if (this.intlSegmenterLocales.length > 0) {
      this.e = $Uu.Segmenter(this.intlSegmenterLocales, { granularity: "word" });
    } else {
      this.e = null;
    }
    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 */
    );
  }
  findPrevIntlWordBeforeOrAtOffset(line, offset) {
    let candidate = null;
    for (const segment of this.h(line)) {
      if (segment.index > offset) {
        break;
      }
      candidate = segment;
    }
    return candidate;
  }
  findNextIntlWordAtOrAfterOffset(lineContent, offset) {
    for (const segment of this.h(lineContent)) {
      if (segment.index < offset) {
        continue;
      }
      return segment;
    }
    return null;
  }
  h(line) {
    if (!this.e) {
      return [];
    }
    if (this.f === line) {
      return this.g;
    }
    this.f = line;
    this.g = this.j(this.e.segment(line));
    return this.g;
  }
  j(segments) {
    const result = [];
    for (const segment of segments) {
      if (this.k(segment)) {
        result.push(segment);
      }
    }
    return result;
  }
  k(segment) {
    if (segment.isWordLike) {
      return true;
    }
    return false;
  }
};
var wordClassifierCache = new $Hc(10);
function $iE(wordSeparators2, intlSegmenterLocales) {
  const key = `${wordSeparators2}/${intlSegmenterLocales.join(",")}`;
  let result = wordClassifierCache.get(key);
  if (!result) {
    result = new $hE(wordSeparators2, intlSegmenterLocales);
    wordClassifierCache.set(key, result);
  }
  return result;
}

// out-build/vs/editor/common/model.js
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 GlyphMarginLane;
(function(GlyphMarginLane2) {
  GlyphMarginLane2[GlyphMarginLane2["Left"] = 1] = "Left";
  GlyphMarginLane2[GlyphMarginLane2["Center"] = 2] = "Center";
  GlyphMarginLane2[GlyphMarginLane2["Right"] = 3] = "Right";
})(GlyphMarginLane || (GlyphMarginLane = {}));
var MinimapPosition;
(function(MinimapPosition2) {
  MinimapPosition2[MinimapPosition2["Inline"] = 1] = "Inline";
  MinimapPosition2[MinimapPosition2["Gutter"] = 2] = "Gutter";
})(MinimapPosition || (MinimapPosition = {}));
var MinimapSectionHeaderStyle;
(function(MinimapSectionHeaderStyle2) {
  MinimapSectionHeaderStyle2[MinimapSectionHeaderStyle2["Normal"] = 1] = "Normal";
  MinimapSectionHeaderStyle2[MinimapSectionHeaderStyle2["Underlined"] = 2] = "Underlined";
})(MinimapSectionHeaderStyle || (MinimapSectionHeaderStyle = {}));
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 EndOfLinePreference;
(function(EndOfLinePreference2) {
  EndOfLinePreference2[EndOfLinePreference2["TextDefined"] = 0] = "TextDefined";
  EndOfLinePreference2[EndOfLinePreference2["LF"] = 1] = "LF";
  EndOfLinePreference2[EndOfLinePreference2["CRLF"] = 2] = "CRLF";
})(EndOfLinePreference || (EndOfLinePreference = {}));
var DefaultEndOfLine;
(function(DefaultEndOfLine2) {
  DefaultEndOfLine2[DefaultEndOfLine2["LF"] = 1] = "LF";
  DefaultEndOfLine2[DefaultEndOfLine2["CRLF"] = 2] = "CRLF";
})(DefaultEndOfLine || (DefaultEndOfLine = {}));
var EndOfLineSequence;
(function(EndOfLineSequence2) {
  EndOfLineSequence2[EndOfLineSequence2["LF"] = 0] = "LF";
  EndOfLineSequence2[EndOfLineSequence2["CRLF"] = 1] = "CRLF";
})(EndOfLineSequence || (EndOfLineSequence = {}));
var $eG = class {
  /**
   * @internal
   */
  constructor(range, matches) {
    this._findMatchBrand = void 0;
    this.range = range;
    this.matches = matches;
  }
};
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 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 ModelConstants;
(function(ModelConstants2) {
  ModelConstants2[ModelConstants2["FIRST_LINE_DETECTION_LENGTH_LIMIT"] = 1e3] = "FIRST_LINE_DETECTION_LENGTH_LIMIT";
})(ModelConstants || (ModelConstants = {}));
var $iG = class {
  constructor(regex, wordSeparators2, simpleSearch) {
    this.regex = regex;
    this.wordSeparators = wordSeparators2;
    this.simpleSearch = simpleSearch;
  }
};
var $jG = class {
  constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) {
    this.reverseEdits = reverseEdits;
    this.changes = changes;
    this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers;
  }
};

// out-build/vs/editor/common/model/textModelSearch.js
var $fI = class {
  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 = $gI(this.searchString);
    } else {
      multiline = this.searchString.indexOf("\n") >= 0;
    }
    let regex = null;
    try {
      regex = $Jf(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 $iG(regex, this.wordSeparators ? $iE(this.wordSeparators, []) : null, canUseSimpleSearch ? this.searchString : null);
  }
};
function $gI(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 $hI(range, rawMatches, captureMatches) {
  if (!captureMatches) {
    return new $eG(range, null);
  }
  const matches = [];
  for (let i = 0, len = rawMatches.length; i < len; i++) {
    matches[i] = rawMatches[i];
  }
  return new $eG(range, matches);
}
function leftIsWordBounday(wordSeparators2, text, textLength, matchStartIndex, matchLength) {
  if (matchStartIndex === 0) {
    return true;
  }
  const charBefore = text.charCodeAt(matchStartIndex - 1);
  if (wordSeparators2.get(charBefore) !== 0) {
    return true;
  }
  if (charBefore === 13 || charBefore === 10) {
    return true;
  }
  if (matchLength > 0) {
    const firstCharInMatch = text.charCodeAt(matchStartIndex);
    if (wordSeparators2.get(firstCharInMatch) !== 0) {
      return true;
    }
  }
  return false;
}
function rightIsWordBounday(wordSeparators2, text, textLength, matchStartIndex, matchLength) {
  if (matchStartIndex + matchLength === textLength) {
    return true;
  }
  const charAfter = text.charCodeAt(matchStartIndex + matchLength);
  if (wordSeparators2.get(charAfter) !== 0) {
    return true;
  }
  if (charAfter === 13 || charAfter === 10) {
    return true;
  }
  if (matchLength > 0) {
    const lastCharInMatch = text.charCodeAt(matchStartIndex + matchLength - 1);
    if (wordSeparators2.get(lastCharInMatch) !== 0) {
      return true;
    }
  }
  return false;
}
function $jI(wordSeparators2, text, textLength, matchStartIndex, matchLength) {
  return leftIsWordBounday(wordSeparators2, text, textLength, matchStartIndex, matchLength) && rightIsWordBounday(wordSeparators2, text, textLength, matchStartIndex, matchLength);
}
var $kI = class {
  constructor(wordSeparators2, searchRegex) {
    this._wordSeparators = wordSeparators2;
    this.a = searchRegex;
    this.b = -1;
    this.c = 0;
  }
  reset(lastIndex) {
    this.a.lastIndex = lastIndex;
    this.b = -1;
    this.c = 0;
  }
  next(text) {
    const textLength = text.length;
    let m;
    do {
      if (this.b + this.c === textLength) {
        return null;
      }
      m = this.a.exec(text);
      if (!m) {
        return null;
      }
      const matchStartIndex = m.index;
      const matchLength = m[0].length;
      if (matchStartIndex === this.b && matchLength === this.c) {
        if (matchLength === 0) {
          if ($8f(text, textLength, this.a.lastIndex) > 65535) {
            this.a.lastIndex += 2;
          } else {
            this.a.lastIndex += 1;
          }
          continue;
        }
        return null;
      }
      this.b = matchStartIndex;
      this.c = matchLength;
      if (!this._wordSeparators || $jI(this._wordSeparators, text, textLength, matchStartIndex, matchLength)) {
        return m;
      }
    } while (m);
    return null;
  }
};

// out-build/vs/platform/workspace/common/virtualWorkspace.js
function $8S(resource) {
  return resource.scheme !== Schemas.file && resource.scheme !== Schemas.vscodeRemote;
}
function $9S(workspace) {
  if (workspace.folders.length) {
    return workspace.folders.every((f) => $8S(f.uri)) ? workspace.folders[0].uri : void 0;
  } else if (workspace.configuration && $8S(workspace.configuration)) {
    return workspace.configuration;
  }
  return void 0;
}
function $0S(workspace) {
  return $9S(workspace)?.scheme;
}

// out-build/vs/workbench/services/environment/common/environmentService.js
var $US = $Rk($Xk);

// out-build/vs/workbench/services/remote/common/remoteAgentService.js
var $RL = $Qk("remoteAgentService");
var $SL = new class {
  constructor() {
    this.maxSampleCount = 5;
    this.sampleDelay = 2e3;
    this.initial = [];
    this.maxInitialCount = 3;
    this.average = [];
    this.maxAverageCount = 100;
    this.highLatencyMultiple = 2;
    this.highLatencyMinThreshold = 500;
    this.highLatencyMaxThreshold = 1500;
    this.lastMeasurement = void 0;
  }
  get latency() {
    return this.lastMeasurement;
  }
  async measure(remoteAgentService) {
    let currentLatency = Infinity;
    for (let i = 0; i < this.maxSampleCount; i++) {
      const rtt = await remoteAgentService.getRoundTripTime();
      if (rtt === void 0) {
        return void 0;
      }
      currentLatency = Math.min(
        currentLatency,
        rtt / 2
        /* we want just one way, not round trip time */
      );
      await $Wh(this.sampleDelay);
    }
    this.average.push(currentLatency);
    if (this.average.length > this.maxAverageCount) {
      this.average.shift();
    }
    let initialLatency = void 0;
    if (this.initial.length < this.maxInitialCount) {
      this.initial.push(currentLatency);
    } else {
      initialLatency = this.initial.reduce((sum, value) => sum + value, 0) / this.initial.length;
    }
    this.lastMeasurement = {
      initial: initialLatency,
      current: currentLatency,
      average: this.average.reduce((sum, value) => sum + value, 0) / this.average.length,
      high: (() => {
        if (typeof initialLatency === "undefined") {
          return false;
        }
        if (currentLatency > this.highLatencyMaxThreshold) {
          return true;
        }
        if (currentLatency > this.highLatencyMinThreshold && currentLatency > initialLatency * this.highLatencyMultiple) {
          return true;
        }
        return false;
      })()
    };
    return this.lastMeasurement;
  }
}();

// out-build/vs/workbench/services/path/common/pathService.js
var $bT_1;
var $aT = $Qk("pathService");
var $bT = $bT_1 = class $bT2 {
  constructor(d, e, f, g) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.a = (async () => {
      const env2 = await this.e.getEnvironment();
      return env2?.os || OS;
    })();
    this.b = (async () => {
      const env2 = await this.e.getEnvironment();
      const userHome = this.c = env2?.userHome ?? d;
      return userHome;
    })();
  }
  hasValidBasename(resource, arg2, basename) {
    if (typeof arg2 === "string" || typeof arg2 === "undefined") {
      return this.a.then((os3) => this.h(resource, os3, arg2));
    }
    return this.h(resource, arg2, basename);
  }
  h(resource, os3, name) {
    if (resource.scheme === Schemas.file || resource.scheme === Schemas.vscodeRemote) {
      return $Xg(
        name ?? $sh(resource),
        os3 === 1
        /* OperatingSystem.Windows */
      );
    }
    return true;
  }
  get defaultUriScheme() {
    return $bT_1.findDefaultUriScheme(this.f, this.g);
  }
  static findDefaultUriScheme(environmentService, contextService) {
    if (environmentService.remoteAuthority) {
      return Schemas.vscodeRemote;
    }
    const virtualWorkspace = $0S(contextService.getWorkspace());
    if (virtualWorkspace) {
      return virtualWorkspace;
    }
    const firstFolder = contextService.getWorkspace().folders[0];
    if (firstFolder) {
      return firstFolder.uri.scheme;
    }
    const configuration = contextService.getWorkspace().configuration;
    if (configuration) {
      return configuration.scheme;
    }
    return Schemas.file;
  }
  userHome(options2) {
    return options2?.preferLocal ? this.d : this.b;
  }
  get resolvedUserHome() {
    return this.c;
  }
  get path() {
    return this.a.then((os3) => {
      return os3 === 1 ? $jc : $kc;
    });
  }
  async fileURI(_path) {
    let authority = "";
    const os3 = await this.a;
    if (os3 === 1) {
      _path = _path.replace(/\\/g, "/");
    }
    if (_path[0] === "/" && _path[1] === "/") {
      const idx = _path.indexOf("/", 2);
      if (idx === -1) {
        authority = _path.substring(2);
        _path = "/";
      } else {
        authority = _path.substring(2, idx);
        _path = _path.substring(idx) || "/";
      }
    }
    return URI.from({
      scheme: Schemas.file,
      authority,
      path: _path,
      query: "",
      fragment: ""
    });
  }
};
$bT = $bT_1 = __decorate([
  __param(1, $RL),
  __param(2, $US),
  __param(3, $Zk)
], $bT);

// out-build/vs/workbench/services/search/common/queryBuilder.js
function $cT(object) {
  return typeof object === "object" && "uri" in object && "pattern" in object;
}
var $eT = class $eT2 {
  constructor(a, b, c, d, f, g) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
  }
  aiText(contentPattern, folderResources, options2 = {}) {
    const commonQuery = this.j(folderResources?.map($_k), options2);
    return {
      ...commonQuery,
      type: 3,
      contentPattern
    };
  }
  text(contentPattern, folderResources, options2 = {}) {
    contentPattern = this.h(contentPattern, options2);
    const searchConfig = this.a.getValue();
    const fallbackToPCRE = folderResources && folderResources.some((folder) => {
      const folderConfig = this.a.getValue({ resource: folder });
      return !folderConfig.search.useRipgrep;
    });
    const commonQuery = this.j(folderResources?.map($_k), options2);
    return {
      ...commonQuery,
      type: 2,
      contentPattern,
      previewOptions: options2.previewOptions,
      maxFileSize: options2.maxFileSize,
      usePCRE2: searchConfig.search.usePCRE2 || fallbackToPCRE || false,
      surroundingContext: options2.surroundingContext,
      userDisabledExcludesAndIgnoreFiles: options2.disregardExcludeSettings && options2.disregardIgnoreFiles
    };
  }
  /**
   * Adjusts input pattern for config
   */
  h(inputPattern, options2) {
    const searchConfig = this.a.getValue();
    if (inputPattern.isRegExp) {
      inputPattern.pattern = inputPattern.pattern.replace(/\r?\n/g, "\\n");
    }
    const newPattern = {
      ...inputPattern,
      wordSeparators: searchConfig.editor.wordSeparators
    };
    if (this.l(inputPattern, options2)) {
      newPattern.isCaseSensitive = true;
    }
    if (this.m(inputPattern)) {
      newPattern.isMultiline = true;
    }
    if (options2.notebookSearchConfig?.includeMarkupInput) {
      if (!newPattern.notebookInfo) {
        newPattern.notebookInfo = {};
      }
      newPattern.notebookInfo.isInNotebookMarkdownInput = options2.notebookSearchConfig.includeMarkupInput;
    }
    if (options2.notebookSearchConfig?.includeMarkupPreview) {
      if (!newPattern.notebookInfo) {
        newPattern.notebookInfo = {};
      }
      newPattern.notebookInfo.isInNotebookMarkdownPreview = options2.notebookSearchConfig.includeMarkupPreview;
    }
    if (options2.notebookSearchConfig?.includeCodeInput) {
      if (!newPattern.notebookInfo) {
        newPattern.notebookInfo = {};
      }
      newPattern.notebookInfo.isInNotebookCellInput = options2.notebookSearchConfig.includeCodeInput;
    }
    if (options2.notebookSearchConfig?.includeOutput) {
      if (!newPattern.notebookInfo) {
        newPattern.notebookInfo = {};
      }
      newPattern.notebookInfo.isInNotebookCellOutput = options2.notebookSearchConfig.includeOutput;
    }
    return newPattern;
  }
  file(folders, options2 = {}) {
    const commonQuery = this.j(folders, options2);
    return {
      ...commonQuery,
      type: 1,
      filePattern: options2.filePattern ? options2.filePattern.trim() : options2.filePattern,
      exists: options2.exists,
      sortByScore: options2.sortByScore,
      cacheKey: options2.cacheKey,
      shouldGlobMatchFilePattern: options2.shouldGlobSearch
    };
  }
  i(pattern, expandPatterns) {
    if (!pattern) {
      return {};
    }
    if (Array.isArray(pattern)) {
      pattern = pattern.filter((p) => p.length > 0).map(normalizeSlashes);
      if (!pattern.length) {
        return {};
      }
    } else {
      pattern = normalizeSlashes(pattern);
    }
    return expandPatterns ? this.parseSearchPaths(pattern) : { pattern: patternListToIExpression(...Array.isArray(pattern) ? pattern : [pattern]) };
  }
  j(folderResources = [], options2 = {}) {
    let excludePatterns = Array.isArray(options2.excludePattern) ? options2.excludePattern.map((p) => p.pattern).flat() : options2.excludePattern;
    excludePatterns = excludePatterns?.length === 1 ? excludePatterns[0] : excludePatterns;
    const includeSearchPathsInfo = this.i(options2.includePattern, options2.expandPatterns);
    const excludeSearchPathsInfo = this.i(excludePatterns, options2.expandPatterns);
    const includeFolderName = folderResources.length > 1;
    const folderQueries = (includeSearchPathsInfo.searchPaths && includeSearchPathsInfo.searchPaths.length ? includeSearchPathsInfo.searchPaths.map((searchPath) => this.t(searchPath, options2, excludeSearchPathsInfo)) : folderResources.map((folder) => this.u(folder, options2, excludeSearchPathsInfo, includeFolderName))).filter((query) => !!query);
    const queryProps = {
      _reason: options2._reason,
      folderQueries,
      usingSearchPaths: !!(includeSearchPathsInfo.searchPaths && includeSearchPathsInfo.searchPaths.length),
      extraFileResources: options2.extraFileResources,
      excludePattern: excludeSearchPathsInfo.pattern,
      includePattern: includeSearchPathsInfo.pattern,
      onlyOpenEditors: options2.onlyOpenEditors,
      maxResults: options2.maxResults,
      onlyFileScheme: options2.onlyFileScheme
    };
    if (options2.onlyOpenEditors) {
      const openEditors = $Mb(this.c.groups.flatMap((group) => group.editors.map((editor) => editor.resource)));
      this.d.trace("QueryBuilder#commonQuery - openEditor URIs", JSON.stringify(openEditors));
      const openEditorsInQuery = openEditors.filter((editor) => $3N(queryProps, editor.fsPath));
      const openEditorsQueryProps = this.k(openEditorsInQuery);
      this.d.trace("QueryBuilder#commonQuery - openEditor Query", JSON.stringify(openEditorsQueryProps));
      return { ...queryProps, ...openEditorsQueryProps };
    }
    const extraFileResources = options2.extraFileResources && options2.extraFileResources.filter((extraFile) => $3N(queryProps, extraFile.fsPath));
    queryProps.extraFileResources = extraFileResources && extraFileResources.length ? extraFileResources : void 0;
    return queryProps;
  }
  k(files) {
    const folderQueries = [];
    const foldersToSearch = new $Ec();
    const includePattern = {};
    let hasIncludedFile = false;
    files.forEach((file) => {
      if (file.scheme === Schemas.walkThrough) {
        return;
      }
      const providerExists = $zh(file);
      if (providerExists) {
        const searchRoot = this.b.getWorkspaceFolder(file)?.uri ?? this.g.extUri.dirname(file);
        let folderQuery = foldersToSearch.get(searchRoot);
        if (!folderQuery) {
          hasIncludedFile = true;
          folderQuery = { folder: searchRoot, includePattern: {} };
          folderQueries.push(folderQuery);
          foldersToSearch.set(searchRoot, folderQuery);
        }
        const relPath = $pc(searchRoot.fsPath, file.fsPath);
        $Kg(folderQuery.includePattern)[relPath.replace(/\\/g, "/")] = true;
      } else {
        if (file.fsPath) {
          hasIncludedFile = true;
          includePattern[file.fsPath] = true;
        }
      }
    });
    return {
      folderQueries,
      includePattern,
      usingSearchPaths: true,
      excludePattern: hasIncludedFile ? void 0 : { "**/*": true }
    };
  }
  /**
   * Resolve isCaseSensitive flag based on the query and the isSmartCase flag, for search providers that don't support smart case natively.
   */
  l(contentPattern, options2) {
    if (options2.isSmartCase) {
      if (contentPattern.isRegExp) {
        if ($qg(contentPattern.pattern, true)) {
          return true;
        }
      } else if ($qg(contentPattern.pattern)) {
        return true;
      }
    }
    return !!contentPattern.isCaseSensitive;
  }
  m(contentPattern) {
    if (contentPattern.isMultiline) {
      return true;
    }
    if (contentPattern.isRegExp && $gI(contentPattern.pattern)) {
      return true;
    }
    if (contentPattern.pattern.indexOf("\n") >= 0) {
      return true;
    }
    return !!contentPattern.isMultiline;
  }
  /**
   * Take the includePattern as seen in the search viewlet, and split into components that look like searchPaths, and
   * glob patterns. Glob patterns are expanded from 'foo/bar' to '{foo/bar/**, **\/foo/bar}.
   *
   * Public for test.
   */
  parseSearchPaths(pattern) {
    const isSearchPath = (segment) => {
      return $mc(segment) || /^\.\.?([\/\\]|$)/.test(segment);
    };
    const patterns = Array.isArray(pattern) ? pattern : splitGlobPattern(pattern);
    const segments = patterns.map((segment) => {
      const userHome = this.f.resolvedUserHome;
      if (userHome) {
        return $3t(segment, userHome.scheme === Schemas.file ? userHome.fsPath : userHome.path);
      }
      return segment;
    });
    const groups = $a(segments, (segment) => isSearchPath(segment) ? "searchPaths" : "exprSegments");
    const expandedExprSegments = (groups.exprSegments || []).map((s) => $Gf(s, "/")).map((s) => $Gf(s, "\\")).map((p) => {
      if (p[0] === ".") {
        p = "*" + p;
      }
      return expandGlobalGlob(p);
    });
    const result = {};
    const searchPaths = this.o(groups.searchPaths || []);
    if (searchPaths && searchPaths.length) {
      result.searchPaths = searchPaths;
    }
    const exprSegments = expandedExprSegments.flat();
    const includePattern = patternListToIExpression(...exprSegments);
    if (includePattern) {
      result.pattern = includePattern;
    }
    return result;
  }
  n(folderConfig, options2) {
    return options2.disregardExcludeSettings ? void 0 : $2N(folderConfig, !options2.disregardSearchExcludeSettings);
  }
  /**
   * Split search paths (./ or ../ or absolute paths in the includePatterns) into absolute paths and globs applied to those paths
   */
  o(searchPaths) {
    if (!searchPaths || !searchPaths.length) {
      return [];
    }
    const expandedSearchPaths = searchPaths.flatMap((searchPath) => {
      let { pathPortion, globPortion } = splitGlobFromPath(searchPath);
      if (globPortion) {
        globPortion = normalizeGlobPattern(globPortion);
      }
      const oneExpanded = this.q(pathPortion);
      return oneExpanded.flatMap((oneExpandedResult) => this.r(oneExpandedResult, globPortion));
    });
    const searchPathPatternMap = /* @__PURE__ */ new Map();
    expandedSearchPaths.forEach((oneSearchPathPattern) => {
      const key = oneSearchPathPattern.searchPath.toString();
      const existing = searchPathPatternMap.get(key);
      if (existing) {
        if (oneSearchPathPattern.pattern) {
          existing.pattern = existing.pattern || {};
          existing.pattern[oneSearchPathPattern.pattern] = true;
        }
      } else {
        searchPathPatternMap.set(key, {
          searchPath: oneSearchPathPattern.searchPath,
          pattern: oneSearchPathPattern.pattern ? patternListToIExpression(oneSearchPathPattern.pattern) : void 0
        });
      }
    });
    return Array.from(searchPathPatternMap.values());
  }
  /**
   * Takes a searchPath like `./a/foo` or `../a/foo` and expands it to absolute paths for all the workspaces it matches.
   */
  q(searchPath) {
    if ($mc(searchPath)) {
      const workspaceFolders = this.b.getWorkspace().folders;
      if (workspaceFolders[0] && workspaceFolders[0].uri.scheme !== Schemas.file) {
        return [{
          searchPath: workspaceFolders[0].uri.with({ path: searchPath })
        }];
      }
      return [{
        searchPath: URI.file($lc(searchPath))
      }];
    }
    if (this.b.getWorkbenchState() === 2) {
      const workspaceUri = this.b.getWorkspace().folders[0].uri;
      searchPath = normalizeSlashes(searchPath);
      if (searchPath.startsWith("../") || searchPath === "..") {
        const resolvedPath = $kc.resolve(workspaceUri.path, searchPath);
        return [{
          searchPath: workspaceUri.with({ path: resolvedPath })
        }];
      }
      const cleanedPattern = normalizeGlobPattern(searchPath);
      return [{
        searchPath: workspaceUri,
        pattern: cleanedPattern
      }];
    } else if (searchPath === "./" || searchPath === ".\\") {
      return [];
    } else {
      const searchPathWithoutDotSlash = searchPath.replace(/^\.[\/\\]/, "");
      const folders = this.b.getWorkspace().folders;
      const folderMatches = folders.map((folder) => {
        const match = searchPathWithoutDotSlash.match(new RegExp(`^${$Af(folder.name)}(?:/(.*)|$)`));
        return match ? {
          match,
          folder
        } : null;
      }).filter($Hg);
      if (folderMatches.length) {
        return folderMatches.map((match) => {
          const patternMatch = match.match[1];
          return {
            searchPath: match.folder.uri,
            pattern: patternMatch && normalizeGlobPattern(patternMatch)
          };
        });
      } else {
        const probableWorkspaceFolderNameMatch = searchPath.match(/\.[\/\\](.+)[\/\\]?/);
        const probableWorkspaceFolderName = probableWorkspaceFolderNameMatch ? probableWorkspaceFolderNameMatch[1] : searchPath;
        const searchPathNotFoundError = localize(13104, null, probableWorkspaceFolderName);
        throw new Error(searchPathNotFoundError);
      }
    }
  }
  r(oneExpandedResult, globPortion) {
    const pattern = oneExpandedResult.pattern && globPortion ? `${oneExpandedResult.pattern}/${globPortion}` : oneExpandedResult.pattern || globPortion;
    const results = [
      {
        searchPath: oneExpandedResult.searchPath,
        pattern
      }
    ];
    if (pattern && !pattern.endsWith("**")) {
      results.push({
        searchPath: oneExpandedResult.searchPath,
        pattern: pattern + "/**"
      });
    }
    return results;
  }
  t(searchPath, options2, searchPathExcludes) {
    const rootConfig = this.u($_k(searchPath.searchPath), options2, searchPathExcludes, false);
    if (!rootConfig) {
      return null;
    }
    return {
      ...rootConfig,
      ...{
        includePattern: searchPath.pattern
      }
    };
  }
  u(folder, options2, searchPathExcludes, includeFolderName) {
    let thisFolderExcludeSearchPathPattern;
    const folderUri = URI.isUri(folder) ? folder : folder.uri;
    let excludeFolderRoots = options2.excludePattern?.map((excludePattern2) => {
      const excludeRoot = options2.excludePattern && $cT(excludePattern2) ? excludePattern2.uri : void 0;
      const shouldUseExcludeRoot = !excludeRoot || !(URI.isUri(folder) && this.g.extUri.isEqual(folder, excludeRoot));
      return shouldUseExcludeRoot ? excludeRoot : void 0;
    });
    if (!excludeFolderRoots?.length) {
      excludeFolderRoots = [void 0];
    }
    if (searchPathExcludes.searchPaths) {
      const thisFolderExcludeSearchPath = searchPathExcludes.searchPaths.filter((sp) => $oh(sp.searchPath, folderUri))[0];
      if (thisFolderExcludeSearchPath && !thisFolderExcludeSearchPath.pattern) {
        return null;
      } else if (thisFolderExcludeSearchPath) {
        thisFolderExcludeSearchPathPattern = thisFolderExcludeSearchPath.pattern;
      }
    }
    const folderConfig = this.a.getValue({ resource: folderUri });
    const settingExcludes = this.n(folderConfig, options2);
    const excludePattern = {
      ...settingExcludes || {},
      ...thisFolderExcludeSearchPathPattern || {}
    };
    const folderName = URI.isUri(folder) ? $sh(folder) : folder.name;
    const excludePatternRet = excludeFolderRoots.map((excludeFolderRoot) => {
      return Object.keys(excludePattern).length > 0 ? {
        folder: excludeFolderRoot,
        pattern: excludePattern
      } : void 0;
    }).filter((e) => e);
    return {
      folder: folderUri,
      folderName: includeFolderName ? folderName : void 0,
      excludePattern: excludePatternRet,
      fileEncoding: folderConfig.files && folderConfig.files.encoding,
      disregardIgnoreFiles: typeof options2.disregardIgnoreFiles === "boolean" ? options2.disregardIgnoreFiles : !folderConfig.search.useIgnoreFiles,
      disregardGlobalIgnoreFiles: typeof options2.disregardGlobalIgnoreFiles === "boolean" ? options2.disregardGlobalIgnoreFiles : !folderConfig.search.useGlobalIgnoreFiles,
      disregardParentIgnoreFiles: typeof options2.disregardParentIgnoreFiles === "boolean" ? options2.disregardParentIgnoreFiles : !folderConfig.search.useParentIgnoreFiles,
      ignoreSymlinks: typeof options2.ignoreSymlinks === "boolean" ? options2.ignoreSymlinks : !folderConfig.search.followSymlinks
    };
  }
};
$eT = __decorate([
  __param(0, $kl),
  __param(1, $Zk),
  __param(2, $iJ),
  __param(3, $wn),
  __param(4, $aT),
  __param(5, $vl)
], $eT);
function splitGlobFromPath(searchPath) {
  const globCharMatch = searchPath.match(/[\*\{\}\(\)\[\]\?]/);
  if (globCharMatch) {
    const globCharIdx = globCharMatch.index;
    const lastSlashMatch = searchPath.substr(0, globCharIdx).match(/[/|\\][^/\\]*$/);
    if (lastSlashMatch) {
      let pathPortion = searchPath.substr(0, lastSlashMatch.index);
      if (!pathPortion.match(/[/\\]/)) {
        pathPortion += "/";
      }
      return {
        pathPortion,
        globPortion: searchPath.substr((lastSlashMatch.index || 0) + 1)
      };
    }
  }
  return {
    pathPortion: searchPath
  };
}
function patternListToIExpression(...patterns) {
  return patterns.length ? patterns.reduce((glob, cur) => {
    glob[cur] = true;
    return glob;
  }, /* @__PURE__ */ Object.create(null)) : void 0;
}
function splitGlobPattern(pattern) {
  return $Bl(pattern, ",").map((s) => s.trim()).filter((s) => !!s.length);
}
function expandGlobalGlob(pattern) {
  const patterns = [
    `**/${pattern}/**`,
    `**/${pattern}`
  ];
  return patterns.map((p) => p.replace(/\*\*\/\*\*/g, "**"));
}
function normalizeSlashes(pattern) {
  return pattern.replace(/\\/g, "/");
}
function normalizeGlobPattern(pattern) {
  return normalizeSlashes(pattern).replace(/^\.\//, "").replace(/\/+$/g, "");
}

// out-build/vs/workbench/services/extensions/common/workspaceContains.js
var WORKSPACE_CONTAINS_TIMEOUT = 7e3;
function $7Rb(host, desc) {
  const activationEvents = desc.activationEvents;
  if (!activationEvents) {
    return Promise.resolve(void 0);
  }
  const fileNames = [];
  const globPatterns = [];
  for (const activationEvent of activationEvents) {
    if (/^workspaceContains:/.test(activationEvent)) {
      const fileNameOrGlob = activationEvent.substr("workspaceContains:".length);
      if (fileNameOrGlob.indexOf("*") >= 0 || fileNameOrGlob.indexOf("?") >= 0 || host.forceUsingSearch) {
        globPatterns.push(fileNameOrGlob);
      } else {
        fileNames.push(fileNameOrGlob);
      }
    }
  }
  if (fileNames.length === 0 && globPatterns.length === 0) {
    return Promise.resolve(void 0);
  }
  const { promise, resolve } = $Oh();
  const activate = (activationEvent) => resolve({ activationEvent });
  const fileNamePromise = Promise.all(fileNames.map((fileName) => _activateIfFileName(host, fileName, activate))).then(() => {
  });
  const globPatternPromise = _activateIfGlobPatterns(host, desc.identifier, globPatterns, activate);
  Promise.all([fileNamePromise, globPatternPromise]).then(() => {
    resolve(void 0);
  });
  return promise;
}
async function _activateIfFileName(host, fileName, activate) {
  for (const uri of host.folders) {
    if (await host.exists($vh(URI.revive(uri), fileName))) {
      activate(`workspaceContains:${fileName}`);
      return;
    }
  }
}
async function _activateIfGlobPatterns(host, extensionId, globPatterns, activate) {
  if (globPatterns.length === 0) {
    return Promise.resolve(void 0);
  }
  const tokenSource = new $ad();
  const searchP = host.checkExists(host.folders, globPatterns, tokenSource.token);
  const timer2 = setTimeout(async () => {
    tokenSource.cancel();
    host.logService.info(`Not activating extension '${extensionId.value}': Timed out while searching for 'workspaceContains' pattern ${globPatterns.join(",")}`);
  }, WORKSPACE_CONTAINS_TIMEOUT);
  let exists = false;
  try {
    exists = await searchP;
  } catch (err) {
    if (!$kb(err)) {
      $gb(err);
    }
  }
  tokenSource.dispose();
  clearTimeout(timer2);
  if (exists) {
    activate(`workspaceContains:${globPatterns.join(",")}`);
  }
}

// out-build/vs/workbench/api/common/extHostSecretState.js
var $Cxc = class {
  constructor(mainContext) {
    this.b = new $ze();
    this.onDidChangePassword = this.b.event;
    this.a = mainContext.getProxy($xT.MainThreadSecretState);
  }
  async $onDidChangePassword(e) {
    this.b.fire(e);
  }
  get(extensionId, key) {
    return this.a.$getPassword(extensionId, key);
  }
  store(extensionId, key, value) {
    return this.a.$setPassword(extensionId, key, value);
  }
  delete(extensionId, key) {
    return this.a.$deletePassword(extensionId, key);
  }
};
var $Dxc = $Qk("IExtHostSecretState");

// out-build/vs/workbench/api/common/extHostSecrets.js
var $Exc = class {
  #secretState;
  constructor(extensionDescription, secretState) {
    this.disposables = new $2c();
    this.a = $5z.toKey(extensionDescription.identifier);
    this.#secretState = secretState;
    this.onDidChange = Event.map(Event.filter(this.#secretState.onDidChangePassword, (e) => e.extensionId === this.a), (e) => ({ key: e.key }), this.disposables);
  }
  dispose() {
    this.disposables.dispose();
  }
  get(key) {
    return this.#secretState.get(this.a, key);
  }
  store(key, value) {
    return this.#secretState.store(this.a, key, value);
  }
  delete(key) {
    return this.#secretState.delete(this.a, key);
  }
};

// out-build/vs/workbench/api/common/extHostLocalizationService.js
var $Fxc = class $Fxc2 {
  constructor(initData, rpc, f) {
    this.f = f;
    this.d = /* @__PURE__ */ new Map();
    this.a = rpc.getProxy($xT.MainThreadLocalization);
    this.b = initData.environment.appLanguage;
    this.c = this.b === $j;
  }
  getMessage(extensionId, details) {
    const { message, args: args2, comment } = details;
    if (this.c) {
      return $xf(message, args2 ?? {});
    }
    let key = message;
    if (comment && comment.length > 0) {
      key += `/${Array.isArray(comment) ? comment.join("") : comment}`;
    }
    const str = this.d.get(extensionId)?.contents[key];
    if (!str) {
      this.f.warn(`Using default string since no string found in i18n bundle that has the key: ${key}`);
    }
    return $xf(str ?? message, args2 ?? {});
  }
  getBundle(extensionId) {
    return this.d.get(extensionId)?.contents;
  }
  getBundleUri(extensionId) {
    return this.d.get(extensionId)?.uri;
  }
  async initializeLocalizedMessages(extension) {
    if (this.c || !extension.l10n && !extension.isBuiltin) {
      return;
    }
    if (this.d.has(extension.identifier.value)) {
      return;
    }
    let contents;
    const bundleUri = await this.g(extension);
    if (!bundleUri) {
      this.f.error(`No bundle location found for extension ${extension.identifier.value}`);
      return;
    }
    try {
      const response = await this.a.$fetchBundleContents(bundleUri);
      const result = JSON.parse(response);
      contents = extension.isBuiltin ? result.contents?.bundle : result;
    } catch (e) {
      this.f.error(`Failed to load translations for ${extension.identifier.value} from ${bundleUri}: ${e.message}`);
      return;
    }
    if (contents) {
      this.d.set(extension.identifier.value, {
        contents,
        uri: bundleUri
      });
    }
  }
  async g(extension) {
    if (extension.isBuiltin) {
      const uri = await this.a.$fetchBuiltInBundleUri(extension.identifier.value, this.b);
      return URI.revive(uri);
    }
    return extension.l10n ? URI.joinPath(extension.extensionLocation, extension.l10n, `bundle.l10n.${this.b}.json`) : void 0;
  }
};
$Fxc = __decorate([
  __param(0, $wW),
  __param(1, $gW),
  __param(2, $wn)
], $Fxc);
var $Gxc = $Qk("IExtHostLocalizationService");

// out-build/vs/workbench/api/common/extHostManagedSockets.js
var $Hxc = $Qk("IExtHostManagedSockets");
var $Ixc = class $Ixc2 {
  constructor(extHostRpc) {
    this.b = 0;
    this.c = null;
    this.d = /* @__PURE__ */ new Map();
    this.a = extHostRpc.getProxy($xT.MainThreadManagedSockets);
  }
  setFactory(socketFactoryId, makeConnection) {
    for (const socket of this.d.values()) {
      socket.dispose();
    }
    if (this.c) {
      this.a.$unregisterSocketFactory(this.c.socketFactoryId);
    }
    this.c = new ManagedSocketFactory(socketFactoryId, makeConnection);
    this.a.$registerSocketFactory(this.c.socketFactoryId);
  }
  async $openRemoteSocket(socketFactoryId) {
    if (!this.c || this.c.socketFactoryId !== socketFactoryId) {
      throw new Error(`No socket factory with id ${socketFactoryId}`);
    }
    const id2 = ++this.b;
    const socket = await this.c.makeConnection();
    const disposable = new $2c();
    this.d.set(id2, new ManagedSocket(id2, socket, disposable));
    disposable.add($1c(() => this.d.delete(id2)));
    disposable.add(socket.onDidEnd(() => {
      this.a.$onDidManagedSocketEnd(id2);
      disposable.dispose();
    }));
    disposable.add(socket.onDidClose((e) => {
      this.a.$onDidManagedSocketClose(id2, e?.stack ?? e?.message);
      disposable.dispose();
    }));
    disposable.add(socket.onDidReceiveMessage((e) => this.a.$onDidManagedSocketHaveData(id2, $Ci.wrap(e))));
    return id2;
  }
  $remoteSocketWrite(socketId, buffer) {
    this.d.get(socketId)?.actual.send(buffer.buffer);
  }
  $remoteSocketEnd(socketId) {
    const socket = this.d.get(socketId);
    if (socket) {
      socket.actual.end();
      socket.dispose();
    }
  }
  async $remoteSocketDrain(socketId) {
    await this.d.get(socketId)?.actual.drain?.();
  }
};
$Ixc = __decorate([
  __param(0, $gW)
], $Ixc);
var ManagedSocketFactory = class {
  constructor(socketFactoryId, makeConnection) {
    this.socketFactoryId = socketFactoryId;
    this.makeConnection = makeConnection;
  }
};
var ManagedSocket = class extends $3c {
  constructor(socketId, actual, disposer) {
    super();
    this.socketId = socketId;
    this.actual = actual;
    this.B(disposer);
  }
};

// out-build/vs/workbench/api/common/extHostExtensionService.js
var $Kxc_1;
var $Jxc = $Qk("IHostUtils");
var $Kxc = $Kxc_1 = class $Kxc2 extends $3c {
  constructor(instaService, hostUtils, extHostContext, extHostWorkspace, extHostConfiguration, logService, initData, storagePath, extHostTunnelService, extHostTerminalService, extHostLocalizationService, Y, Z) {
    super();
    this.Y = Y;
    this.Z = Z;
    this.a = this.B(new $ze());
    this.onDidChangeRemoteConnectionData = this.a.event;
    this.R = /* @__PURE__ */ new Map();
    this.W = false;
    this.c = hostUtils;
    this.g = extHostContext;
    this.f = initData;
    this.j = extHostWorkspace;
    this.m = extHostConfiguration;
    this.s = logService;
    this.t = extHostTunnelService;
    this.u = extHostTerminalService;
    this.w = extHostLocalizationService;
    this.y = this.g.getProxy($xT.MainThreadWorkspace);
    this.z = this.g.getProxy($xT.MainThreadTelemetry);
    this.C = this.g.getProxy($xT.MainThreadExtensionService);
    this.D = new $Uh();
    this.F = new $Uh();
    this.G = new $Uh();
    this.H = new $Uh();
    this.I = new SyncedActivationEventsReader(this.f.extensions.activationEvents);
    this.L = new $inc(this.I, this.f.extensions.allExtensions);
    const myExtensionsSet = new $6z(this.f.extensions.myExtensions);
    this.J = new $inc(this.I, filterExtensions(this.L, myExtensionsSet));
    if ($w) {
      this.s.info(`Creating extension host with the following global extensions: ${printExtIds(this.L)}`);
      this.s.info(`Creating extension host with the following local extensions: ${printExtIds(this.J)}`);
    }
    this.M = new $uxc(this.g, this.s);
    this.N = new $Cxc(this.g);
    this.O = storagePath;
    this.h = this.q.add(instaService.createChild(new $Ok([$vxc, this.M], [$Dxc, this.N])));
    this.P = this.B(new $txc(this.J, this.L, {
      onExtensionActivationError: (extensionId, error, missingExtensionDependency) => {
        this.C.$onExtensionActivationError(extensionId, $ib(error), missingExtensionDependency);
      },
      actualActivateExtension: async (extensionId, reason) => {
        if ($inc.isHostExtension(extensionId, this.J, this.L)) {
          await this.C.$activateExtension(extensionId, reason);
          return new $sxc();
        }
        const extensionDescription = this.J.getExtensionDescription(extensionId);
        return this.fb(extensionDescription, reason);
      }
    }, this.s));
    this.Q = null;
    this.S = /* @__PURE__ */ Object.create(null);
    this.U = false;
    this.X = this.f.remote.connectionData;
  }
  getRemoteConnectionData() {
    return this.X;
  }
  async initialize() {
    try {
      await this.vb();
      this.D.open();
      await this.j.waitForInitializeCall();
      $S("code/extHost/ready");
      this.F.open();
      if (this.f.autoStart) {
        this.tb();
      }
    } catch (err) {
      $gb(err);
    }
  }
  async $() {
    this.O.onWillDeactivateAll();
    let allPromises = [];
    try {
      const allExtensions = this.J.getAllExtensionDescriptions();
      const allExtensionsIds = allExtensions.map((ext) => ext.identifier);
      const activatedExtensions = allExtensionsIds.filter((id2) => this.isActivated(id2));
      allPromises = activatedExtensions.map((extensionId) => {
        return this.eb(extensionId);
      });
    } catch (err) {
    }
    await Promise.all(allPromises);
  }
  terminate(reason, code = 0) {
    if (this.W) {
      return;
    }
    this.W = true;
    this.s.info(`Extension host terminating: ${reason}`);
    this.s.flush();
    this.u.dispose();
    this.P.dispose();
    setUnexpectedErrorHandler((err) => {
      this.s.error(err);
    });
    this.g.dispose();
    const extensionsDeactivated = this.$();
    Promise.race([$Wh(5e3), extensionsDeactivated]).finally(() => {
      if (this.c.pid) {
        this.s.info(`Extension host with pid ${this.c.pid} exiting with code ${code}`);
      } else {
        this.s.info(`Extension host exiting with code ${code}`);
      }
      this.s.flush();
      this.s.dispose();
      this.c.exit(code);
    });
  }
  isActivated(extensionId) {
    if (this.G.isOpen()) {
      return this.P.isActivated(extensionId);
    }
    return false;
  }
  async getExtension(extensionId) {
    const ext = await this.C.$getExtension(extensionId);
    return ext && {
      ...ext,
      identifier: new $5z(ext.identifier.value),
      extensionLocation: URI.revive(ext.extensionLocation)
    };
  }
  ab(activationEvent, startup) {
    return this.P.activateByEvent(activationEvent, startup);
  }
  bb(extensionId, reason) {
    return this.P.activateById(extensionId, reason);
  }
  activateByIdWithErrors(extensionId, reason) {
    return this.bb(extensionId, reason).then(() => {
      const extension = this.P.getActivatedExtension(extensionId);
      if (extension.activationFailed) {
        return Promise.reject(extension.activationFailedError);
      }
      return void 0;
    });
  }
  getExtensionRegistry() {
    return this.G.wait().then((_) => this.J);
  }
  getExtensionExports(extensionId) {
    if (this.G.isOpen()) {
      return this.P.getActivatedExtension(extensionId).exports;
    } else {
      try {
        return this.P.getActivatedExtension(extensionId).exports;
      } catch (err) {
        return null;
      }
    }
  }
  /**
   * Applies realpath to file-uris and returns all others uris unmodified.
   * The real path is cached for the lifetime of the extension host.
   */
  async cb(uri) {
    if (uri.scheme === Schemas.file && this.c.fsRealpath) {
      const fsPath = uri.fsPath;
      if (!this.R.has(fsPath)) {
        this.R.set(fsPath, this.c.fsRealpath(fsPath));
      }
      const realpathValue = await this.R.get(fsPath);
      return URI.file(realpathValue);
    }
    return uri;
  }
  // create trie to enable fast 'filename -> extension id' look up
  async getExtensionPathIndex() {
    if (!this.Q) {
      this.Q = this.db(this.J.getAllExtensionDescriptions()).then((searchTree) => {
        return new $Nxc(searchTree);
      });
    }
    return this.Q;
  }
  /**
   * create trie to enable fast 'filename -> extension id' look up
   */
  async db(extensions) {
    const tst = $Wk.forUris((key) => {
      return $mh.ignorePathCasing(key);
    });
    await Promise.all(extensions.map(async (ext) => {
      if (this.wb(ext)) {
        const uri = await this.cb(ext.extensionLocation);
        tst.set(uri, ext);
      }
    }));
    return tst;
  }
  eb(extensionId) {
    let result = Promise.resolve(void 0);
    if (!this.G.isOpen()) {
      return result;
    }
    if (!this.P.isActivated(extensionId)) {
      return result;
    }
    const extension = this.P.getActivatedExtension(extensionId);
    if (!extension) {
      return result;
    }
    try {
      if (typeof extension.module.deactivate === "function") {
        result = Promise.resolve(extension.module.deactivate()).then(void 0, (err) => {
          this.s.error(err);
          return Promise.resolve(void 0);
        });
      }
    } catch (err) {
      this.s.error(`An error occurred when deactivating the extension '${extensionId.value}':`);
      this.s.error(err);
    }
    try {
      extension.disposable.dispose();
    } catch (err) {
      this.s.error(`An error occurred when disposing the subscriptions for extension '${extensionId.value}':`);
      this.s.error(err);
    }
    return result;
  }
  // --- impl
  async fb(extensionDescription, reason) {
    if (!this.f.remote.isRemote) {
      await this.C.$onWillActivateExtension(extensionDescription.identifier);
    } else {
      this.C.$onWillActivateExtension(extensionDescription.identifier);
    }
    return this.hb(extensionDescription, reason).then((activatedExtension) => {
      const activationTimes = activatedExtension.activationTimes;
      this.C.$onDidActivateExtension(extensionDescription.identifier, activationTimes.codeLoadingTime, activationTimes.activateCallTime, activationTimes.activateResolvedTime, reason);
      this.gb(extensionDescription, reason, "success", activationTimes);
      return activatedExtension;
    }, (err) => {
      this.gb(extensionDescription, reason, "failure");
      throw err;
    });
  }
  gb(extensionDescription, reason, outcome, activationTimes) {
    const event = getTelemetryActivationEvent(extensionDescription, reason);
    this.z.$publicLog2("extensionActivationTimes", {
      ...event,
      ...activationTimes || {},
      outcome
    });
  }
  hb(extensionDescription, reason) {
    const event = getTelemetryActivationEvent(extensionDescription, reason);
    this.z.$publicLog2("activatePlugin", event);
    const entryPoint = this.wb(extensionDescription);
    if (!entryPoint) {
      return Promise.resolve(new $rxc($oxc.NONE));
    }
    this.s.info(`ExtensionService#_doActivateExtension ${extensionDescription.identifier.value}, startup: ${reason.startup}, activationEvent: '${reason.activationEvent}'${extensionDescription.identifier.value !== reason.extensionId.value ? `, root cause: ${reason.extensionId.value}` : ``}`);
    this.s.flush();
    const extensionInternalStore = new $2c();
    const activationTimesBuilder = new $pxc(reason.startup);
    return Promise.all([
      this.xb(extensionDescription, $vh(extensionDescription.extensionLocation, entryPoint), activationTimesBuilder),
      this.ib(extensionDescription, extensionInternalStore)
    ]).then((values) => {
      $S(`code/extHost/willActivateExtension/${extensionDescription.identifier.value}`);
      return $Kxc_1.jb(this.s, extensionDescription.identifier, values[0], values[1], extensionInternalStore, activationTimesBuilder);
    }).then((activatedExtension) => {
      $S(`code/extHost/didActivateExtension/${extensionDescription.identifier.value}`);
      return activatedExtension;
    });
  }
  ib(extensionDescription, extensionInternalStore) {
    const languageModelAccessInformation = this.Z.createLanguageModelAccessInformation(extensionDescription);
    const globalState = extensionInternalStore.add(new $xxc(extensionDescription, this.M));
    const workspaceState = extensionInternalStore.add(new $wxc(extensionDescription.identifier.value, false, this.M));
    const secrets = extensionInternalStore.add(new $Exc(extensionDescription, this.N));
    const extensionMode = extensionDescription.isUnderDevelopment ? this.f.environment.extensionTestsLocationURI ? ExtensionMode.Test : ExtensionMode.Development : ExtensionMode.Production;
    const extensionKind = this.f.remote.isRemote ? ExtensionKind.Workspace : ExtensionKind.UI;
    this.s.trace(`ExtensionService#loadExtensionContext ${extensionDescription.identifier.value}`);
    return Promise.all([
      globalState.whenReady,
      workspaceState.whenReady,
      this.O.whenReady
    ]).then(() => {
      const that = this;
      let extension;
      let messagePassingProtocol;
      const messagePort = $zN(extensionDescription, "ipc") ? this.f.messagePorts?.get($5z.toKey(extensionDescription.identifier)) : void 0;
      return Object.freeze({
        globalState,
        workspaceState,
        secrets,
        subscriptions: [],
        get languageModelAccessInformation() {
          return languageModelAccessInformation;
        },
        get extensionUri() {
          return extensionDescription.extensionLocation;
        },
        get extensionPath() {
          return extensionDescription.extensionLocation.fsPath;
        },
        asAbsolutePath(relativePath) {
          return $nc(extensionDescription.extensionLocation.fsPath, relativePath);
        },
        get storagePath() {
          return that.O.workspaceValue(extensionDescription)?.fsPath;
        },
        get globalStoragePath() {
          return that.O.globalValue(extensionDescription).fsPath;
        },
        get logPath() {
          return $nc(that.f.logsLocation.fsPath, extensionDescription.identifier.value);
        },
        get logUri() {
          return URI.joinPath(that.f.logsLocation, extensionDescription.identifier.value);
        },
        get storageUri() {
          return that.O.workspaceValue(extensionDescription);
        },
        get globalStorageUri() {
          return that.O.globalValue(extensionDescription);
        },
        get extensionMode() {
          return extensionMode;
        },
        get extension() {
          if (extension === void 0) {
            extension = new $Mxc(that, extensionDescription.identifier, extensionDescription, extensionKind, false);
          }
          return extension;
        },
        get extensionRuntime() {
          $AN(extensionDescription, "extensionRuntime");
          return that.extensionRuntime;
        },
        get environmentVariableCollection() {
          return that.u.getEnvironmentVariableCollection(extensionDescription);
        },
        get messagePassingProtocol() {
          if (!messagePassingProtocol) {
            if (!messagePort) {
              return void 0;
            }
            const onDidReceiveMessage = Event.buffer(Event.fromDOMEventEmitter(messagePort, "message", (e) => e.data));
            messagePort.start();
            messagePassingProtocol = {
              onDidReceiveMessage,
              postMessage: messagePort.postMessage.bind(messagePort)
            };
          }
          return messagePassingProtocol;
        }
      });
    });
  }
  static jb(logService, extensionId, extensionModule, context, extensionInternalStore, activationTimesBuilder) {
    extensionModule = extensionModule || {
      activate: void 0,
      deactivate: void 0
    };
    return this.kb(logService, extensionId, extensionModule, context, activationTimesBuilder).then((extensionExports) => {
      return new $qxc(false, null, activationTimesBuilder.build(), extensionModule, extensionExports, $1c(() => {
        extensionInternalStore.dispose();
        $Xc(context.subscriptions);
      }));
    });
  }
  static kb(logService, extensionId, extensionModule, context, activationTimesBuilder) {
    if (typeof extensionModule.activate === "function") {
      try {
        activationTimesBuilder.activateCallStart();
        logService.trace(`ExtensionService#_callActivateOptional ${extensionId.value}`);
        const scope = typeof global === "object" ? global : self;
        const activateResult = extensionModule.activate.apply(scope, [context]);
        activationTimesBuilder.activateCallStop();
        activationTimesBuilder.activateResolveStart();
        return Promise.resolve(activateResult).then((value) => {
          activationTimesBuilder.activateResolveStop();
          return value;
        });
      } catch (err) {
        return Promise.reject(err);
      }
    } else {
      return Promise.resolve(extensionModule);
    }
  }
  // -- eager activation
  lb(desc, activationEvent) {
    this.bb(desc.identifier, {
      startup: false,
      extensionId: desc.identifier,
      activationEvent
    }).then(void 0, (err) => {
      this.s.error(err);
    });
  }
  mb(extensions, start = 0) {
    const timeBudget = 50;
    const startTime = Date.now();
    $E(() => {
      for (let i = start; i < extensions.length; i += 1) {
        const desc = extensions[i];
        for (const activationEvent of desc.activationEvents ?? []) {
          if (activationEvent === "onStartupFinished") {
            if (Date.now() - startTime > timeBudget) {
              this.mb(extensions, i);
              break;
            } else {
              this.lb(desc, activationEvent);
            }
          }
        }
      }
    });
  }
  nb() {
    this.C.$setPerformanceMarks($T());
    this.m.getConfigProvider().then((configProvider) => {
      const shouldDeferActivation = configProvider.getConfiguration("extensions.experimental").get("deferredStartupFinishedActivation");
      const allExtensionDescriptions = this.J.getAllExtensionDescriptions();
      if (shouldDeferActivation) {
        this.mb(allExtensionDescriptions);
      } else {
        for (const desc of allExtensionDescriptions) {
          if (desc.activationEvents) {
            for (const activationEvent of desc.activationEvents) {
              if (activationEvent === "onStartupFinished") {
                this.lb(desc, activationEvent);
              }
            }
          }
        }
      }
    });
  }
  // Handle "eager" activation extensions
  ob() {
    const starActivation = this.ab("*", true).then(void 0, (err) => {
      this.s.error(err);
    });
    this.B(this.j.onDidChangeWorkspace((e) => this.pb(e.added)));
    const folders = this.j.workspace ? this.j.workspace.folders : [];
    const workspaceContainsActivation = this.pb(folders);
    const remoteResolverActivation = this.rb();
    const eagerExtensionsActivation = Promise.all([remoteResolverActivation, starActivation, workspaceContainsActivation]).then(() => {
    });
    Promise.race([eagerExtensionsActivation, $Wh(1e4)]).then(() => {
      this.nb();
    });
    return eagerExtensionsActivation;
  }
  pb(folders) {
    if (folders.length === 0) {
      return Promise.resolve(void 0);
    }
    return Promise.all(this.J.getAllExtensionDescriptions().map((desc) => {
      return this.qb(folders, desc);
    })).then(() => {
    });
  }
  async qb(folders, desc) {
    if (this.isActivated(desc.identifier)) {
      return;
    }
    const localWithRemote = !this.f.remote.isRemote && !!this.f.remote.authority;
    const host = {
      logService: this.s,
      folders: folders.map((folder) => folder.uri),
      forceUsingSearch: localWithRemote || !this.c.fsExists,
      exists: (uri) => this.c.fsExists(uri.fsPath),
      checkExists: (folders2, includes, token) => this.y.$checkExists(folders2, includes, token)
    };
    const result = await $7Rb(host, desc);
    if (!result) {
      return;
    }
    return this.bb(desc.identifier, { startup: true, extensionId: desc.identifier, activationEvent: result.activationEvent }).then(void 0, (err) => this.s.error(err));
  }
  async rb() {
    if (this.f.remote.authority) {
      return this.ab(`onResolveRemoteAuthority:${this.f.remote.authority}`, false);
    }
  }
  async $extensionTestsExecute() {
    await this.H.wait();
    try {
      return await this.sb();
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
  async sb() {
    const { extensionDevelopmentLocationURI, extensionTestsLocationURI } = this.f.environment;
    if (!extensionDevelopmentLocationURI || !extensionTestsLocationURI) {
      throw new Error(localize(2755, null));
    }
    const testRunner = await this.xb(null, extensionTestsLocationURI, new $pxc(false));
    if (!testRunner || typeof testRunner.run !== "function") {
      throw new Error(localize(2756, null, extensionTestsLocationURI.toString()));
    }
    return new Promise((resolve, reject) => {
      const oldTestRunnerCallback = (error, failures) => {
        if (error) {
          if ($w) {
            this.s.error(`Test runner called back with error`, error);
          }
          reject(error);
        } else {
          if ($w) {
            if (failures) {
              this.s.info(`Test runner called back with ${failures} failures.`);
            } else {
              this.s.info(`Test runner called back with successful outcome.`);
            }
          }
          resolve(
            typeof failures === "number" && failures > 0 ? 1 : 0
            /* OK */
          );
        }
      };
      const extensionTestsPath = $jh(extensionTestsLocationURI);
      const runResult = testRunner.run(extensionTestsPath, oldTestRunnerCallback);
      if (runResult && runResult.then) {
        runResult.then(() => {
          if ($w) {
            this.s.info(`Test runner finished successfully.`);
          }
          resolve(0);
        }).catch((err) => {
          if ($w) {
            this.s.error(`Test runner finished with error`, err);
          }
          reject(err instanceof Error && err.stack ? err.stack : String(err));
        });
      }
    });
  }
  tb() {
    if (this.U) {
      throw new Error(`Extension host is already started!`);
    }
    this.U = true;
    return this.F.wait().then(() => this.G.open()).then(() => {
      return Promise.race([this.P.waitForActivatingExtensions(), $Wh(1e3)]);
    }).then(() => this.ob()).then(() => {
      this.H.open();
      this.s.info(`Eager extensions activated`);
    });
  }
  // -- called by extensions
  registerRemoteAuthorityResolver(authorityPrefix, resolver) {
    this.S[authorityPrefix] = resolver;
    return $1c(() => {
      delete this.S[authorityPrefix];
    });
  }
  async getRemoteExecServer(remoteAuthority) {
    const { resolver } = await this.ub(remoteAuthority);
    return resolver?.resolveExecServer?.(remoteAuthority, { resolveAttempt: 0 });
  }
  // -- called by main thread
  async ub(remoteAuthority) {
    const authorityPlusIndex = remoteAuthority.indexOf("+");
    if (authorityPlusIndex === -1) {
      throw new $HT(`Not an authority that can be resolved!`, RemoteAuthorityResolverErrorCode.InvalidAuthority);
    }
    const authorityPrefix = remoteAuthority.substr(0, authorityPlusIndex);
    await this.D.wait();
    await this.ab(`onResolveRemoteAuthority:${authorityPrefix}`, false);
    return { authorityPrefix, resolver: this.S[authorityPrefix] };
  }
  async $resolveAuthority(remoteAuthorityChain, resolveAttempt) {
    const sw = $te.create(false);
    const prefix = () => `[resolveAuthority(${$fC(remoteAuthorityChain)},${resolveAttempt})][${sw.elapsed()}ms] `;
    const logInfo = (msg) => this.s.info(`${prefix()}${msg}`);
    const logWarning = (msg) => this.s.warn(`${prefix()}${msg}`);
    const logError = (msg, err = void 0) => this.s.error(`${prefix()}${msg}`, err);
    const normalizeError = (err) => {
      if (err instanceof $HT) {
        return {
          type: "error",
          error: {
            code: err._code,
            message: err._message,
            detail: err._detail
          }
        };
      }
      throw err;
    };
    const getResolver = async (remoteAuthority) => {
      logInfo(`activating resolver for ${remoteAuthority}...`);
      const { resolver, authorityPrefix } = await this.ub(remoteAuthority);
      if (!resolver) {
        logError(`no resolver for ${authorityPrefix}`);
        throw new $HT(`No remote extension installed to resolve ${authorityPrefix}.`, RemoteAuthorityResolverErrorCode.NoResolverFound);
      }
      return { resolver, authorityPrefix, remoteAuthority };
    };
    const chain = remoteAuthorityChain.split(/@|%40/g).reverse();
    logInfo(`activating remote resolvers ${chain.join(" -> ")}`);
    let resolvers;
    try {
      resolvers = await Promise.all(chain.map(getResolver)).catch(async (e) => {
        if (!(e instanceof $HT) || e._code !== RemoteAuthorityResolverErrorCode.InvalidAuthority) {
          throw e;
        }
        logWarning(`resolving nested authorities failed: ${e.message}`);
        return [await getResolver(remoteAuthorityChain)];
      });
    } catch (e) {
      return normalizeError(e);
    }
    const intervalLogger = new $7h();
    intervalLogger.cancelAndSet(() => logInfo("waiting..."), 1e3);
    let result;
    let execServer;
    for (const [i, { authorityPrefix, resolver, remoteAuthority }] of resolvers.entries()) {
      try {
        if (i === resolvers.length - 1) {
          logInfo(`invoking final resolve()...`);
          $S(`code/extHost/willResolveAuthority/${authorityPrefix}`);
          result = await resolver.resolve(remoteAuthority, { resolveAttempt, execServer });
          $S(`code/extHost/didResolveAuthorityOK/${authorityPrefix}`);
          logInfo(`setting tunnel factory...`);
          this.B(await this.t.setTunnelFactory(resolver, $GT.isManagedResolvedAuthority(result) ? result : void 0));
        } else {
          logInfo(`invoking resolveExecServer() for ${remoteAuthority}`);
          $S(`code/extHost/willResolveExecServer/${authorityPrefix}`);
          execServer = await resolver.resolveExecServer?.(remoteAuthority, { resolveAttempt, execServer });
          if (!execServer) {
            throw new $HT(`Exec server was not available for ${remoteAuthority}`, RemoteAuthorityResolverErrorCode.NoResolverFound);
          }
          $S(`code/extHost/didResolveExecServerOK/${authorityPrefix}`);
        }
      } catch (e) {
        $S(`code/extHost/didResolveAuthorityError/${authorityPrefix}`);
        logError(`returned an error`, e);
        intervalLogger.dispose();
        return normalizeError(e);
      }
    }
    intervalLogger.dispose();
    const tunnelInformation = {
      environmentTunnels: result.environmentTunnels,
      features: result.tunnelFeatures ? {
        elevation: result.tunnelFeatures.elevation,
        privacyOptions: result.tunnelFeatures.privacyOptions,
        protocol: result.tunnelFeatures.protocol === void 0 ? true : result.tunnelFeatures.protocol
      } : void 0
    };
    const options2 = {
      extensionHostEnv: result.extensionHostEnv,
      isTrusted: result.isTrusted,
      authenticationSession: result.authenticationSessionForInitializingExtensions ? { id: result.authenticationSessionForInitializingExtensions.id, providerId: result.authenticationSessionForInitializingExtensions.providerId } : void 0
    };
    logInfo(`returned ${$GT.isManagedResolvedAuthority(result) ? "managed authority" : `${result.host}:${result.port}`}`);
    let authority;
    if ($GT.isManagedResolvedAuthority(result)) {
      const socketFactoryId = resolveAttempt;
      this.Y.setFactory(socketFactoryId, result.makeConnection);
      authority = {
        authority: remoteAuthorityChain,
        connectTo: new $cC(socketFactoryId),
        connectionToken: result.connectionToken
      };
    } else {
      authority = {
        authority: remoteAuthorityChain,
        connectTo: new $dC(result.host, result.port),
        connectionToken: result.connectionToken
      };
    }
    return {
      type: "ok",
      value: {
        authority,
        options: options2,
        tunnelInformation
      }
    };
  }
  async $getCanonicalURI(remoteAuthority, uriComponents) {
    this.s.info(`$getCanonicalURI invoked for authority (${$fC(remoteAuthority)})`);
    const { resolver } = await this.ub(remoteAuthority);
    if (!resolver) {
      return null;
    }
    const uri = URI.revive(uriComponents);
    if (typeof resolver.getCanonicalURI === "undefined") {
      return uri;
    }
    const result = await $Nh(() => resolver.getCanonicalURI(uri));
    if (!result) {
      return uri;
    }
    return result;
  }
  async $startExtensionHost(extensionsDelta) {
    extensionsDelta.toAdd.forEach((extension) => extension.extensionLocation = URI.revive(extension.extensionLocation));
    const { globalRegistry, myExtensions } = applyExtensionsDelta(this.I, this.L, this.J, extensionsDelta);
    const newSearchTree = await this.db(myExtensions);
    const extensionsPaths = await this.getExtensionPathIndex();
    extensionsPaths.setSearchTree(newSearchTree);
    this.L.set(globalRegistry.getAllExtensionDescriptions());
    this.J.set(myExtensions);
    if ($w) {
      this.s.info(`$startExtensionHost: global extensions: ${printExtIds(this.L)}`);
      this.s.info(`$startExtensionHost: local extensions: ${printExtIds(this.J)}`);
    }
    return this.tb();
  }
  $activateByEvent(activationEvent, activationKind) {
    if (activationKind === 1) {
      return this.D.wait().then((_) => this.ab(activationEvent, false));
    }
    return this.G.wait().then((_) => this.ab(activationEvent, false));
  }
  async $activate(extensionId, reason) {
    await this.G.wait();
    if (!this.J.getExtensionDescription(extensionId)) {
      return false;
    }
    await this.bb(extensionId, reason);
    return true;
  }
  async $deltaExtensions(extensionsDelta) {
    extensionsDelta.toAdd.forEach((extension) => extension.extensionLocation = URI.revive(extension.extensionLocation));
    const { globalRegistry, myExtensions } = applyExtensionsDelta(this.I, this.L, this.J, extensionsDelta);
    const newSearchTree = await this.db(myExtensions);
    const extensionsPaths = await this.getExtensionPathIndex();
    extensionsPaths.setSearchTree(newSearchTree);
    this.L.set(globalRegistry.getAllExtensionDescriptions());
    this.J.set(myExtensions);
    if ($w) {
      this.s.info(`$deltaExtensions: global extensions: ${printExtIds(this.L)}`);
      this.s.info(`$deltaExtensions: local extensions: ${printExtIds(this.J)}`);
    }
    return Promise.resolve(void 0);
  }
  async $test_latency(n) {
    return n;
  }
  async $test_up(b) {
    return b.byteLength;
  }
  async $test_down(size) {
    const buff = $Ci.alloc(size);
    const value = Math.random() % 256;
    for (let i = 0; i < size; i++) {
      buff.writeUInt8(value, i);
    }
    return buff;
  }
  async $updateRemoteConnectionData(connectionData) {
    this.X = connectionData;
    this.a.fire();
  }
};
$Kxc = $Kxc_1 = __decorate([
  __param(0, $Pk),
  __param(1, $Jxc),
  __param(2, $gW),
  __param(3, $0wc),
  __param(4, $axc),
  __param(5, $wn),
  __param(6, $wW),
  __param(7, $dxc),
  __param(8, $6Sb),
  __param(9, $yxc),
  __param(10, $Gxc),
  __param(11, $Hxc),
  __param(12, $Ywc)
], $Kxc);
function applyExtensionsDelta(activationEventsReader, oldGlobalRegistry, oldMyRegistry, extensionsDelta) {
  activationEventsReader.addActivationEvents(extensionsDelta.addActivationEvents);
  const globalRegistry = new $inc(activationEventsReader, oldGlobalRegistry.getAllExtensionDescriptions());
  globalRegistry.deltaExtensions(extensionsDelta.toAdd, extensionsDelta.toRemove);
  const myExtensionsSet = new $6z(oldMyRegistry.getAllExtensionDescriptions().map((extension) => extension.identifier));
  for (const extensionId of extensionsDelta.myToRemove) {
    myExtensionsSet.delete(extensionId);
  }
  for (const extensionId of extensionsDelta.myToAdd) {
    myExtensionsSet.add(extensionId);
  }
  const myExtensions = filterExtensions(globalRegistry, myExtensionsSet);
  return { globalRegistry, myExtensions };
}
function getTelemetryActivationEvent(extensionDescription, reason) {
  const event = {
    id: extensionDescription.identifier.value,
    name: extensionDescription.name,
    extensionVersion: extensionDescription.version,
    publisherDisplayName: extensionDescription.publisher,
    activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(",") : null,
    isBuiltin: extensionDescription.isBuiltin,
    reason: reason.activationEvent,
    reasonId: reason.extensionId.value
  };
  return event;
}
function printExtIds(registry) {
  return registry.getAllExtensionDescriptions().map((ext) => ext.identifier.value).join(",");
}
var $Lxc = $Qk("IExtHostExtensionService");
var $Mxc = class {
  #extensionService;
  #originExtensionId;
  #identifier;
  constructor(extensionService, originExtensionId, description, kind, isFromDifferentExtensionHost) {
    this.#extensionService = extensionService;
    this.#originExtensionId = originExtensionId;
    this.#identifier = description.identifier;
    this.id = description.identifier.value;
    this.extensionUri = description.extensionLocation;
    this.extensionPath = $lc($jh(description.extensionLocation));
    this.packageJSON = description;
    this.extensionKind = kind;
    this.isFromDifferentExtensionHost = isFromDifferentExtensionHost;
  }
  get isActive() {
    return this.#extensionService.isActivated(this.#identifier);
  }
  get exports() {
    if (this.packageJSON.api === "none" || this.isFromDifferentExtensionHost) {
      return void 0;
    }
    return this.#extensionService.getExtensionExports(this.#identifier);
  }
  async activate() {
    if (this.isFromDifferentExtensionHost) {
      throw new Error("Cannot activate foreign extension");
    }
    await this.#extensionService.activateByIdWithErrors(this.#identifier, { startup: false, extensionId: this.#originExtensionId, activationEvent: "api" });
    return this.exports;
  }
};
function filterExtensions(globalRegistry, desiredExtensions) {
  return globalRegistry.getAllExtensionDescriptions().filter((extension) => desiredExtensions.has(extension.identifier));
}
var $Nxc = class {
  constructor(a) {
    this.a = a;
  }
  setSearchTree(searchTree) {
    this.a = searchTree;
  }
  findSubstr(key) {
    return this.a.findSubstr(key);
  }
  forEach(callback) {
    return this.a.forEach(callback);
  }
};
var SyncedActivationEventsReader = class {
  constructor(activationEvents) {
    this.a = new $7z();
    this.addActivationEvents(activationEvents);
  }
  readActivationEvents(extensionDescription) {
    return this.a.get(extensionDescription.identifier) ?? [];
  }
  addActivationEvents(activationEvents) {
    for (const extensionId of Object.keys(activationEvents)) {
      this.a.set(extensionId, activationEvents[extensionId]);
    }
  }
};

// out-build/vs/workbench/api/common/extensionHostMain.js
var $6yc = class {
  static async installEarlyHandler(accessor) {
    Error.stackTraceLimit = 100;
    const logService = accessor.get($wn);
    const rpcService = accessor.get($gW);
    const mainThreadErrors = rpcService.getProxy($xT.MainThreadErrors);
    setUnexpectedErrorHandler((err) => {
      logService.error(err);
      const data = $ib(err);
      mainThreadErrors.$onUnexpectedError(data);
    });
  }
  static async installFullHandler(accessor) {
    const logService = accessor.get($wn);
    const rpcService = accessor.get($gW);
    const extensionService = accessor.get($Lxc);
    const extensionTelemetry = accessor.get($AW);
    const mainThreadExtensions = rpcService.getProxy($xT.MainThreadExtensionService);
    const mainThreadErrors = rpcService.getProxy($xT.MainThreadErrors);
    const map = await extensionService.getExtensionPathIndex();
    const extensionErrors = /* @__PURE__ */ new WeakMap();
    function prepareStackTraceAndFindExtension(error, stackTrace) {
      if (extensionErrors.has(error)) {
        return extensionErrors.get(error).stack;
      }
      let stackTraceMessage = "";
      let extension;
      let fileName;
      for (const call of stackTrace) {
        stackTraceMessage += `
	at ${call.toString()}`;
        fileName = call.getFileName();
        if (!extension && fileName) {
          extension = map.findSubstr(URI.file(fileName));
        }
      }
      const result = `${error.name || "Error"}: ${error.message || ""}${stackTraceMessage}`;
      extensionErrors.set(error, { extensionIdentifier: extension?.identifier, stack: result });
      return result;
    }
    const _wasWrapped = Symbol("prepareStackTrace wrapped");
    let _prepareStackTrace = prepareStackTraceAndFindExtension;
    Object.defineProperty(Error, "prepareStackTrace", {
      configurable: false,
      get() {
        return _prepareStackTrace;
      },
      set(v) {
        if (v === prepareStackTraceAndFindExtension || !v || v[_wasWrapped]) {
          _prepareStackTrace = v || prepareStackTraceAndFindExtension;
          return;
        }
        _prepareStackTrace = function(error, stackTrace) {
          prepareStackTraceAndFindExtension(error, stackTrace);
          return v.call(Error, error, stackTrace);
        };
        Object.assign(_prepareStackTrace, { [_wasWrapped]: true });
      }
    });
    setUnexpectedErrorHandler((err) => {
      logService.error(err);
      const errorData = $ib(err);
      const stackData = extensionErrors.get(err);
      if (!stackData?.extensionIdentifier) {
        mainThreadErrors.$onUnexpectedError(errorData);
        return;
      }
      mainThreadExtensions.$onExtensionRuntimeError(stackData.extensionIdentifier, errorData);
      const reported = extensionTelemetry.onExtensionError(stackData.extensionIdentifier, err);
      logService.trace("forwarded error to extension?", reported, stackData);
    });
  }
};
var $7yc = class _$7yc {
  constructor(protocol, initData, hostUtils, uriTransformer, messagePorts) {
    this.a = hostUtils;
    this.b = new $qnc(protocol, null, uriTransformer);
    initData = _$7yc.e(initData, this.b);
    const services = new $Ok(...$TC());
    services.set($wW, { _serviceBrand: void 0, ...initData, messagePorts });
    services.set($gW, new $hW(this.b));
    services.set($7wc, new $8wc(uriTransformer));
    services.set($Jxc, hostUtils);
    const instaService = new $0B(services, true);
    instaService.invokeFunction($6yc.installEarlyHandler);
    this.d = instaService.invokeFunction((accessor) => accessor.get($wn));
    $S(`code/extHost/didCreateServices`);
    if (this.a.pid) {
      this.d.info(`Extension host with pid ${this.a.pid} started`);
    } else {
      this.d.info(`Extension host started`);
    }
    this.d.trace("initData", initData);
    this.c = instaService.invokeFunction((accessor) => accessor.get($Lxc));
    this.c.initialize();
    instaService.invokeFunction($6yc.installFullHandler);
  }
  async asBrowserUri(uri) {
    const mainThreadExtensionsProxy = this.b.getProxy($xT.MainThreadExtensionService);
    return URI.revive(await mainThreadExtensionsProxy.$asBrowserUri(uri));
  }
  terminate(reason) {
    this.c.terminate(reason);
  }
  static e(initData, rpcProtocol) {
    initData.extensions.allExtensions.forEach((ext) => {
      ext.extensionLocation = URI.revive(rpcProtocol.transformIncomingURIs(ext.extensionLocation));
    });
    initData.environment.appRoot = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.appRoot));
    const extDevLocs = initData.environment.extensionDevelopmentLocationURI;
    if (extDevLocs) {
      initData.environment.extensionDevelopmentLocationURI = extDevLocs.map((url) => URI.revive(rpcProtocol.transformIncomingURIs(url)));
    }
    initData.environment.extensionTestsLocationURI = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTestsLocationURI));
    initData.environment.globalStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.globalStorageHome));
    initData.environment.workspaceStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.workspaceStorageHome));
    initData.environment.extensionTelemetryLogResource = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTelemetryLogResource));
    initData.nlsBaseUrl = URI.revive(rpcProtocol.transformIncomingURIs(initData.nlsBaseUrl));
    initData.logsLocation = URI.revive(rpcProtocol.transformIncomingURIs(initData.logsLocation));
    initData.workspace = rpcProtocol.transformIncomingURIs(initData.workspace);
    return initData;
  }
};

// out-build/vs/workbench/api/node/uriTransformer.js
function createRawURITransformer(remoteAuthority) {
  return {
    transformIncoming: (uri) => {
      if (uri.scheme === "vscode-remote") {
        return { scheme: "file", path: uri.path, query: uri.query, fragment: uri.fragment };
      }
      if (uri.scheme === "file") {
        return { scheme: "vscode-local", path: uri.path, query: uri.query, fragment: uri.fragment };
      }
      return uri;
    },
    transformOutgoing: (uri) => {
      if (uri.scheme === "file") {
        return { scheme: "vscode-remote", authority: remoteAuthority, path: uri.path, query: uri.query, fragment: uri.fragment };
      }
      if (uri.scheme === "vscode-local") {
        return { scheme: "file", path: uri.path, query: uri.query, fragment: uri.fragment };
      }
      return uri;
    },
    transformOutgoingScheme: (scheme) => {
      if (scheme === "file") {
        return "vscode-remote";
      } else if (scheme === "vscode-local") {
        return "file";
      }
      return scheme;
    }
  };
}
function $FX(remoteAuthority) {
  return new $ry(createRawURITransformer(remoteAuthority));
}

// out-build/vs/workbench/services/extensions/common/extensionHostEnv.js
var ExtHostConnectionType;
(function(ExtHostConnectionType2) {
  ExtHostConnectionType2[ExtHostConnectionType2["IPC"] = 1] = "IPC";
  ExtHostConnectionType2[ExtHostConnectionType2["Socket"] = 2] = "Socket";
  ExtHostConnectionType2[ExtHostConnectionType2["MessagePort"] = 3] = "MessagePort";
})(ExtHostConnectionType || (ExtHostConnectionType = {}));
var $RW = class _$RW {
  static {
    this.ENV_KEY = "VSCODE_EXTHOST_IPC_HOOK";
  }
  constructor(pipeName) {
    this.pipeName = pipeName;
    this.type = 1;
  }
  serialize(env2) {
    env2[_$RW.ENV_KEY] = this.pipeName;
  }
};
var $SW = class _$SW {
  constructor() {
    this.type = 2;
  }
  static {
    this.ENV_KEY = "VSCODE_EXTHOST_WILL_SEND_SOCKET";
  }
  serialize(env2) {
    env2[_$SW.ENV_KEY] = "1";
  }
};
var $TW = class _$TW {
  constructor() {
    this.type = 3;
  }
  static {
    this.ENV_KEY = "VSCODE_WILL_SEND_MESSAGE_PORT";
  }
  serialize(env2) {
    env2[_$TW.ENV_KEY] = "1";
  }
};
function clean(env2) {
  delete env2[$RW.ENV_KEY];
  delete env2[$SW.ENV_KEY];
  delete env2[$TW.ENV_KEY];
}
function $VW(env2) {
  if (env2[$RW.ENV_KEY]) {
    return cleanAndReturn(env2, new $RW(env2[$RW.ENV_KEY]));
  }
  if (env2[$SW.ENV_KEY]) {
    return cleanAndReturn(env2, new $SW());
  }
  if (env2[$TW.ENV_KEY]) {
    return cleanAndReturn(env2, new $TW());
  }
  throw new Error(`No connection information defined in environment!`);
}
function cleanAndReturn(env2, result) {
  clean(env2);
  return result;
}

// out-build/vs/workbench/services/output/common/output.js
var $LS = new $nn("inOutput", false);
var $MS = new $nn("activeLogOutput", false);
var $NS = new $nn("activeLogOutput.levelSettable", false);
var $OS = new $nn("activeLogOutput.level", "");
var $PS = new $nn("activeLogOutput.levelIsDefault", false);
var $QS = new $nn(`outputView.scrollLock`, false);
var $RS = $Qk("outputService");
var OutputChannelUpdateMode;
(function(OutputChannelUpdateMode2) {
  OutputChannelUpdateMode2[OutputChannelUpdateMode2["Append"] = 1] = "Append";
  OutputChannelUpdateMode2[OutputChannelUpdateMode2["Replace"] = 2] = "Replace";
  OutputChannelUpdateMode2[OutputChannelUpdateMode2["Clear"] = 3] = "Clear";
})(OutputChannelUpdateMode || (OutputChannelUpdateMode = {}));
var $SS = {
  OutputChannels: "workbench.contributions.outputChannels"
};
var OutputChannelRegistry = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = new $ze();
    this.onDidRegisterChannel = this.b.event;
    this.c = new $ze();
    this.onDidRemoveChannel = this.c.event;
  }
  registerChannel(descriptor) {
    if (!this.a.has(descriptor.id)) {
      this.a.set(descriptor.id, descriptor);
      this.b.fire(descriptor.id);
    }
  }
  getChannels() {
    const result = [];
    this.a.forEach((value) => result.push(value));
    return result;
  }
  getChannel(id2) {
    return this.a.get(id2);
  }
  removeChannel(id2) {
    this.a.delete(id2);
    this.c.fire(id2);
  }
};
$Wn.add($SS.OutputChannels, new OutputChannelRegistry());
var $TS = new $nn("activeOutputChannel", "");

// out-build/vs/workbench/api/common/extHostOutput.js
var ExtHostOutputChannel = class extends $Cn {
  constructor(id2, name, r, s, extension) {
    super();
    this.id = id2;
    this.name = name;
    this.r = r;
    this.s = s;
    this.extension = extension;
    this.n = 0;
    this.visible = false;
    this.setLevel(r.getLevel());
    this.B(r.onDidChangeLogLevel((level) => this.setLevel(level)));
    this.B($1c(() => this.s.$dispose(this.id)));
  }
  get logLevel() {
    return this.getLevel();
  }
  appendLine(value) {
    this.append(value + "\n");
  }
  append(value) {
    this.info(value);
  }
  clear() {
    const till = this.n;
    this.r.flush();
    this.s.$update(this.id, OutputChannelUpdateMode.Clear, till);
  }
  replace(value) {
    const till = this.n;
    this.info(value);
    this.s.$update(this.id, OutputChannelUpdateMode.Replace, till);
    if (this.visible) {
      this.r.flush();
    }
  }
  show(columnOrPreserveFocus, preserveFocus) {
    this.r.flush();
    this.s.$reveal(this.id, !!(typeof columnOrPreserveFocus === "boolean" ? columnOrPreserveFocus : preserveFocus));
  }
  hide() {
    this.s.$close(this.id);
  }
  m(level, message) {
    this.n += $Ci.fromString(message).byteLength;
    log(this.r, level, message);
    if (this.visible) {
      this.r.flush();
      this.s.$update(this.id, OutputChannelUpdateMode.Append);
    }
  }
};
var ExtHostLogOutputChannel = class extends ExtHostOutputChannel {
  appendLine(value) {
    this.append(value);
  }
};
var $zyc = class $zyc2 {
  constructor(extHostRpc, i, j, k, l, m) {
    this.i = i;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.d = /* @__PURE__ */ new Map();
    this.f = 1;
    this.g = /* @__PURE__ */ new Map();
    this.h = null;
    this.a = extHostRpc.getProxy($xT.MainThreadOutputService);
    this.b = this.k.extUri.joinPath(i.logsLocation, `output_logging_${$Tu(/* @__PURE__ */ new Date()).replace(/-|:|\.\d+Z$/g, "")}`);
  }
  $setVisibleChannel(visibleChannelId) {
    this.h = visibleChannelId;
    for (const [id2, channel] of this.g) {
      channel.visible = id2 === this.h;
    }
  }
  createOutputChannel(name, options2, extension) {
    name = name.trim();
    if (!name) {
      throw new Error("illegal argument `name`. must not be falsy");
    }
    const log4 = typeof options2 === "object" && options2.log;
    const languageId = $zg(options2) ? options2 : void 0;
    if ($zg(languageId) && !languageId.trim()) {
      throw new Error("illegal argument `languageId`. must not be empty");
    }
    let logLevel;
    const logLevelValue = this.i.environment.extensionLogLevel?.find(([identifier]) => $5z.equals(extension.identifier, identifier))?.[1];
    if (logLevelValue) {
      logLevel = $Nn(logLevelValue);
    }
    const channelDisposables = new $2c();
    const extHostOutputChannel = log4 ? this.o(name, logLevel, extension, channelDisposables) : this.n(name, languageId, extension, channelDisposables);
    extHostOutputChannel.then((channel) => {
      this.g.set(channel.id, channel);
      channel.visible = channel.id === this.h;
      channelDisposables.add($1c(() => this.g.delete(channel.id)));
    });
    return log4 ? this.r(name, logLevel ?? this.m.getLevel(), extHostOutputChannel, channelDisposables) : this.q(name, extHostOutputChannel, channelDisposables);
  }
  async n(name, languageId, extension, channelDisposables) {
    if (!this.c) {
      this.c = this.j.value.createDirectory(this.b).then(() => this.b);
    }
    const outputDir = await this.c;
    const file = this.k.extUri.joinPath(outputDir, `${this.f++}-${name.replace(/[\\/:\*\?"<>\|]/g, "")}.log`);
    const logger = channelDisposables.add(this.l.createLogger(file, { logLevel: "always", donotRotate: true, donotUseFormatters: true, hidden: true }));
    const id2 = await this.a.$register(name, file, languageId, extension.identifier.value);
    channelDisposables.add($1c(() => this.l.deregisterLogger(file)));
    return new ExtHostOutputChannel(id2, name, logger, this.a, extension);
  }
  async o(name, logLevel, extension, channelDisposables) {
    const extensionLogDir = await this.p(extension);
    const fileName = name.replace(/[\\/:\*\?"<>\|]/g, "");
    const file = this.k.extUri.joinPath(extensionLogDir, `${fileName}.log`);
    const id2 = `${extension.identifier.value}.${fileName}`;
    const logger = channelDisposables.add(this.l.createLogger(file, { id: id2, name, logLevel, extensionId: extension.identifier.value }));
    channelDisposables.add($1c(() => this.l.deregisterLogger(file)));
    return new ExtHostLogOutputChannel(id2, name, logger, this.a, extension);
  }
  p(extension) {
    let extensionLogDirectoryPromise = this.d.get(extension.identifier.value);
    if (!extensionLogDirectoryPromise) {
      const extensionLogDirectory = this.k.extUri.joinPath(this.i.logsLocation, extension.identifier.value);
      this.d.set(extension.identifier.value, extensionLogDirectoryPromise = (async () => {
        try {
          await this.j.value.createDirectory(extensionLogDirectory);
        } catch (err) {
          if ($Am(err) !== FileSystemProviderErrorCode.FileExists) {
            throw err;
          }
        }
        return extensionLogDirectory;
      })());
    }
    return extensionLogDirectoryPromise;
  }
  q(name, channelPromise, channelDisposables) {
    const validate = () => {
      if (channelDisposables.isDisposed) {
        throw new Error("Channel has been closed");
      }
    };
    channelPromise.then((channel) => channelDisposables.add(channel));
    return {
      get name() {
        return name;
      },
      append(value) {
        validate();
        channelPromise.then((channel) => channel.append(value));
      },
      appendLine(value) {
        validate();
        channelPromise.then((channel) => channel.appendLine(value));
      },
      clear() {
        validate();
        channelPromise.then((channel) => channel.clear());
      },
      replace(value) {
        validate();
        channelPromise.then((channel) => channel.replace(value));
      },
      show(columnOrPreserveFocus, preserveFocus) {
        validate();
        channelPromise.then((channel) => channel.show(columnOrPreserveFocus, preserveFocus));
      },
      hide() {
        validate();
        channelPromise.then((channel) => channel.hide());
      },
      dispose() {
        channelDisposables.dispose();
      }
    };
  }
  r(name, logLevel, channelPromise, channelDisposables) {
    const validate = () => {
      if (channelDisposables.isDisposed) {
        throw new Error("Channel has been closed");
      }
    };
    const onDidChangeLogLevel = channelDisposables.add(new $ze());
    function setLogLevel2(newLogLevel) {
      logLevel = newLogLevel;
      onDidChangeLogLevel.fire(newLogLevel);
    }
    channelPromise.then((channel) => {
      if (channel.logLevel !== logLevel) {
        setLogLevel2(channel.logLevel);
      }
      channelDisposables.add(channel.onDidChangeLogLevel((e) => setLogLevel2(e)));
    });
    return {
      ...this.q(name, channelPromise, channelDisposables),
      get logLevel() {
        return logLevel;
      },
      onDidChangeLogLevel: onDidChangeLogLevel.event,
      trace(value, ...args2) {
        validate();
        channelPromise.then((channel) => channel.trace(value, ...args2));
      },
      debug(value, ...args2) {
        validate();
        channelPromise.then((channel) => channel.debug(value, ...args2));
      },
      info(value, ...args2) {
        validate();
        channelPromise.then((channel) => channel.info(value, ...args2));
      },
      warn(value, ...args2) {
        validate();
        channelPromise.then((channel) => channel.warn(value, ...args2));
      },
      error(value, ...args2) {
        validate();
        channelPromise.then((channel) => channel.error(value, ...args2));
      }
    };
  }
};
$zyc = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $cxc),
  __param(3, $Pwc),
  __param(4, $xn),
  __param(5, $wn)
], $zyc);
var $Ayc = $Qk("IExtHostOutputService");

// out-build/vs/workbench/api/common/extHostDecorations.js
var $1xc_1;
var $1xc = class $1xc2 {
  static {
    $1xc_1 = this;
  }
  static {
    this.c = 0;
  }
  static {
    this.d = 250;
  }
  constructor(extHostRpc, h) {
    this.h = h;
    this.f = /* @__PURE__ */ new Map();
    this.g = extHostRpc.getProxy($xT.MainThreadDecorations);
  }
  registerFileDecorationProvider(provider, extensionDescription) {
    const handle = $1xc_1.c++;
    this.f.set(handle, { provider, extensionDescription });
    this.g.$registerDecorationProvider(handle, extensionDescription.identifier.value);
    const listener = provider.onDidChangeFileDecorations && provider.onDidChangeFileDecorations((e) => {
      if (!e) {
        this.g.$onDidChange(handle, null);
        return;
      }
      const array = $5b(e);
      if (array.length <= $1xc_1.d) {
        this.g.$onDidChange(handle, array);
        return;
      }
      this.h.warn("[Decorations] CAPPING events from decorations provider", extensionDescription.identifier.value, array.length);
      const mapped = array.map((uri) => ({ uri, rank: $Bf(uri.path, "/") }));
      const groups = $Eb(mapped, (a, b) => a.rank - b.rank || $Tf(a.uri.path, b.uri.path));
      const picked = [];
      outer: for (const uris of groups) {
        let lastDirname;
        for (const obj of uris) {
          const myDirname = $qc(obj.uri.path);
          if (lastDirname !== myDirname) {
            lastDirname = myDirname;
            if (picked.push(obj.uri) >= $1xc_1.d) {
              break outer;
            }
          }
        }
      }
      this.g.$onDidChange(handle, picked);
    });
    return new $zT(() => {
      listener?.dispose();
      this.g.$unregisterDecorationProvider(handle);
      this.f.delete(handle);
    });
  }
  async $provideDecorations(handle, requests, token) {
    if (!this.f.has(handle)) {
      return /* @__PURE__ */ Object.create(null);
    }
    const result = /* @__PURE__ */ Object.create(null);
    const { provider, extensionDescription: extensionId } = this.f.get(handle);
    await Promise.all(requests.map(async (request) => {
      try {
        const { uri, id: id2 } = request;
        const data = await Promise.resolve(provider.provideFileDecoration(URI.revive(uri), token));
        if (!data) {
          return;
        }
        try {
          $4U.validate(data);
          if (data.badge && typeof data.badge !== "string") {
            $AN(extensionId, "codiconDecoration");
          }
          result[id2] = [data.propagate, data.tooltip, data.badge, data.color];
        } catch (e) {
          this.h.warn(`INVALID decoration from extension '${extensionId.identifier.value}': ${e}`);
        }
      } catch (err) {
        this.h.error(err);
      }
    }));
    return result;
  }
};
$1xc = $1xc_1 = __decorate([
  __param(0, $gW),
  __param(1, $wn)
], $1xc);
var $2xc = $Qk("IExtHostDecorations");

// out-build/vs/editor/common/model/prefixSumComputer.js
var $wM = class {
  constructor(values) {
    this.a = values;
    this.b = new Uint32Array(values.length);
    this.c = new Int32Array(1);
    this.c[0] = -1;
  }
  getCount() {
    return this.a.length;
  }
  insertValues(insertIndex, insertValues) {
    insertIndex = $uf(insertIndex);
    const oldValues = this.a;
    const oldPrefixSum = this.b;
    const insertValuesLen = insertValues.length;
    if (insertValuesLen === 0) {
      return false;
    }
    this.a = new Uint32Array(oldValues.length + insertValuesLen);
    this.a.set(oldValues.subarray(0, insertIndex), 0);
    this.a.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen);
    this.a.set(insertValues, insertIndex);
    if (insertIndex - 1 < this.c[0]) {
      this.c[0] = insertIndex - 1;
    }
    this.b = new Uint32Array(this.a.length);
    if (this.c[0] >= 0) {
      this.b.set(oldPrefixSum.subarray(0, this.c[0] + 1));
    }
    return true;
  }
  setValue(index, value) {
    index = $uf(index);
    value = $uf(value);
    if (this.a[index] === value) {
      return false;
    }
    this.a[index] = value;
    if (index - 1 < this.c[0]) {
      this.c[0] = index - 1;
    }
    return true;
  }
  removeValues(startIndex, count) {
    startIndex = $uf(startIndex);
    count = $uf(count);
    const oldValues = this.a;
    const oldPrefixSum = this.b;
    if (startIndex >= oldValues.length) {
      return false;
    }
    const maxCount = oldValues.length - startIndex;
    if (count >= maxCount) {
      count = maxCount;
    }
    if (count === 0) {
      return false;
    }
    this.a = new Uint32Array(oldValues.length - count);
    this.a.set(oldValues.subarray(0, startIndex), 0);
    this.a.set(oldValues.subarray(startIndex + count), startIndex);
    this.b = new Uint32Array(this.a.length);
    if (startIndex - 1 < this.c[0]) {
      this.c[0] = startIndex - 1;
    }
    if (this.c[0] >= 0) {
      this.b.set(oldPrefixSum.subarray(0, this.c[0] + 1));
    }
    return true;
  }
  getTotalSum() {
    if (this.a.length === 0) {
      return 0;
    }
    return this.d(this.a.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 = $uf(index);
    return this.d(index);
  }
  d(index) {
    if (index <= this.c[0]) {
      return this.b[index];
    }
    let startIndex = this.c[0] + 1;
    if (startIndex === 0) {
      this.b[0] = this.a[0];
      startIndex++;
    }
    if (index >= this.a.length) {
      index = this.a.length - 1;
    }
    for (let i = startIndex; i <= index; i++) {
      this.b[i] = this.b[i - 1] + this.a[i];
    }
    this.c[0] = Math.max(this.c[0], index);
    return this.b[index];
  }
  getIndexOf(sum) {
    sum = Math.floor(sum);
    this.getTotalSum();
    let low = 0;
    let high = this.a.length - 1;
    let mid = 0;
    let midStop = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      midStop = this.b[mid];
      midStart = midStop - this.a[mid];
      if (sum < midStart) {
        high = mid - 1;
      } else if (sum >= midStop) {
        low = mid + 1;
      } else {
        break;
      }
    }
    return new $yM(mid, sum - midStart);
  }
};
var $yM = class {
  constructor(index, remainder) {
    this.index = index;
    this.remainder = remainder;
    this._prefixSumIndexOfResultBrand = void 0;
    this.index = index;
    this.remainder = remainder;
  }
};

// out-build/vs/editor/common/model/mirrorTextModel.js
var $zM = class {
  constructor(uri, lines, eol, versionId) {
    this.a = uri;
    this.b = lines;
    this.c = eol;
    this.d = versionId;
    this.f = null;
    this.g = null;
  }
  dispose() {
    this.b.length = 0;
  }
  get version() {
    return this.d;
  }
  getText() {
    if (this.g === null) {
      this.g = this.b.join(this.c);
    }
    return this.g;
  }
  onEvents(e) {
    if (e.eol && e.eol !== this.c) {
      this.c = e.eol;
      this.f = null;
    }
    const changes = e.changes;
    for (const change of changes) {
      this.k(change.range);
      this.l(new $8C(change.range.startLineNumber, change.range.startColumn), change.text);
    }
    this.d = e.versionId;
    this.g = null;
  }
  h() {
    if (!this.f) {
      const eolLength = this.c.length;
      const linesLength = this.b.length;
      const lineStartValues = new Uint32Array(linesLength);
      for (let i = 0; i < linesLength; i++) {
        lineStartValues[i] = this.b[i].length + eolLength;
      }
      this.f = new $wM(lineStartValues);
    }
  }
  /**
   * All changes to a line's text go through this method
   */
  j(lineIndex, newValue) {
    this.b[lineIndex] = newValue;
    if (this.f) {
      this.f.setValue(lineIndex, this.b[lineIndex].length + this.c.length);
    }
  }
  k(range) {
    if (range.startLineNumber === range.endLineNumber) {
      if (range.startColumn === range.endColumn) {
        return;
      }
      this.j(range.startLineNumber - 1, this.b[range.startLineNumber - 1].substring(0, range.startColumn - 1) + this.b[range.startLineNumber - 1].substring(range.endColumn - 1));
      return;
    }
    this.j(range.startLineNumber - 1, this.b[range.startLineNumber - 1].substring(0, range.startColumn - 1) + this.b[range.endLineNumber - 1].substring(range.endColumn - 1));
    this.b.splice(range.startLineNumber, range.endLineNumber - range.startLineNumber);
    if (this.f) {
      this.f.removeValues(range.startLineNumber, range.endLineNumber - range.startLineNumber);
    }
  }
  l(position, insertText) {
    if (insertText.length === 0) {
      return;
    }
    const insertLines = $Mf(insertText);
    if (insertLines.length === 1) {
      this.j(position.lineNumber - 1, this.b[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0] + this.b[position.lineNumber - 1].substring(position.column - 1));
      return;
    }
    insertLines[insertLines.length - 1] += this.b[position.lineNumber - 1].substring(position.column - 1);
    this.j(position.lineNumber - 1, this.b[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.b.splice(position.lineNumber + i - 1, 0, insertLines[i]);
      newLengths[i - 1] = insertLines[i].length + this.c.length;
    }
    if (this.f) {
      this.f.insertValues(position.lineNumber, newLengths);
    }
  }
};

// out-build/vs/workbench/api/common/extHostDocumentData.js
var _languageId2WordDefinition = /* @__PURE__ */ new Map();
function $iW(languageId, wordDefinition) {
  if (!wordDefinition) {
    _languageId2WordDefinition.delete(languageId);
  } else {
    _languageId2WordDefinition.set(languageId, wordDefinition);
  }
}
function getWordDefinitionFor(languageId) {
  return _languageId2WordDefinition.get(languageId);
}
var $jW = class extends $zM {
  constructor(o, uri, lines, eol, versionId, p, q) {
    super(uri, lines, eol, versionId);
    this.o = o;
    this.p = p;
    this.q = q;
    this.n = false;
  }
  // eslint-disable-next-line local/code-must-use-super-dispose
  dispose() {
    ok(!this.n);
    this.n = true;
    this.q = false;
  }
  equalLines(lines) {
    return $zb(this.b, lines);
  }
  get document() {
    if (!this.m) {
      const that = this;
      this.m = {
        get uri() {
          return that.a;
        },
        get fileName() {
          return that.a.fsPath;
        },
        get isUntitled() {
          return that.a.scheme === Schemas.untitled;
        },
        get languageId() {
          return that.p;
        },
        get version() {
          return that.d;
        },
        get isClosed() {
          return that.n;
        },
        get isDirty() {
          return that.q;
        },
        save() {
          return that.r();
        },
        getText(range) {
          return range ? that.s(range) : that.getText();
        },
        get eol() {
          return that.c === "\n" ? EndOfLine.LF : EndOfLine.CRLF;
        },
        get lineCount() {
          return that.b.length;
        },
        lineAt(lineOrPos) {
          return that.t(lineOrPos);
        },
        offsetAt(pos) {
          return that.u(pos);
        },
        positionAt(offset) {
          return that.v(offset);
        },
        validateRange(ran) {
          return that.w(ran);
        },
        validatePosition(pos) {
          return that.x(pos);
        },
        getWordRangeAtPosition(pos, regexp) {
          return that.y(pos, regexp);
        },
        [Symbol.for("debug.description")]() {
          return `TextDocument(${that.a.toString()})`;
        }
      };
    }
    return Object.freeze(this.m);
  }
  _acceptLanguageId(newLanguageId) {
    ok(!this.n);
    this.p = newLanguageId;
  }
  _acceptIsDirty(isDirty) {
    ok(!this.n);
    this.q = isDirty;
  }
  r() {
    if (this.n) {
      return Promise.reject(new Error("Document has been closed"));
    }
    return this.o.$trySaveDocument(this.a);
  }
  s(_range) {
    const range = this.w(_range);
    if (range.isEmpty) {
      return "";
    }
    if (range.isSingleLine) {
      return this.b[range.start.line].substring(range.start.character, range.end.character);
    }
    const lineEnding = this.c, startLineIndex = range.start.line, endLineIndex = range.end.line, resultLines = [];
    resultLines.push(this.b[startLineIndex].substring(range.start.character));
    for (let i = startLineIndex + 1; i < endLineIndex; i++) {
      resultLines.push(this.b[i]);
    }
    resultLines.push(this.b[endLineIndex].substring(0, range.end.character));
    return resultLines.join(lineEnding);
  }
  t(lineOrPosition) {
    let line;
    if (lineOrPosition instanceof $AT) {
      line = lineOrPosition.line;
    } else if (typeof lineOrPosition === "number") {
      line = lineOrPosition;
    }
    if (typeof line !== "number" || line < 0 || line >= this.b.length || Math.floor(line) !== line) {
      throw new Error("Illegal value for `line`");
    }
    return new $kW(line, this.b[line], line === this.b.length - 1);
  }
  u(position) {
    position = this.x(position);
    this.h();
    return this.f.getPrefixSum(position.line - 1) + position.character;
  }
  v(offset) {
    offset = Math.floor(offset);
    offset = Math.max(0, offset);
    this.h();
    const out = this.f.getIndexOf(offset);
    const lineLength = this.b[out.index].length;
    return new $AT(out.index, Math.min(out.remainder, lineLength));
  }
  // ---- range math
  w(range) {
    if (!(range instanceof $BT)) {
      throw new Error("Invalid argument");
    }
    const start = this.x(range.start);
    const end = this.x(range.end);
    if (start === range.start && end === range.end) {
      return range;
    }
    return new $BT(start.line, start.character, end.line, end.character);
  }
  x(position) {
    if (!(position instanceof $AT)) {
      throw new Error("Invalid argument");
    }
    if (this.b.length === 0) {
      return position.with(0, 0);
    }
    let { line, character } = position;
    let hasChanged = false;
    if (line < 0) {
      line = 0;
      character = 0;
      hasChanged = true;
    } else if (line >= this.b.length) {
      line = this.b.length - 1;
      character = this.b[line].length;
      hasChanged = true;
    } else {
      const maxCharacter = this.b[line].length;
      if (character < 0) {
        character = 0;
        hasChanged = true;
      } else if (character > maxCharacter) {
        character = maxCharacter;
        hasChanged = true;
      }
    }
    if (!hasChanged) {
      return position;
    }
    return new $AT(line, character);
  }
  y(_position, regexp) {
    const position = this.x(_position);
    if (!regexp) {
      regexp = getWordDefinitionFor(this.p);
    } else if ($Kf(regexp)) {
      throw new Error(`[getWordRangeAtPosition]: ignoring custom regexp '${regexp.source}' because it matches the empty string.`);
    }
    const wordAtText = $MD(position.character + 1, $KD(regexp), this.b[position.line], 0);
    if (wordAtText) {
      return new $BT(position.line, wordAtText.startColumn - 1, position.line, wordAtText.endColumn - 1);
    }
    return void 0;
  }
};
var $kW = class {
  constructor(line, text, isLastLine) {
    this.a = line;
    this.b = text;
    this.c = isLastLine;
  }
  get lineNumber() {
    return this.a;
  }
  get text() {
    return this.b;
  }
  get range() {
    return new $BT(this.a, 0, this.a, this.b.length);
  }
  get rangeIncludingLineBreak() {
    if (this.c) {
      return this.range;
    }
    return new $BT(this.a, 0, this.a + 1, 0);
  }
  get firstNonWhitespaceCharacterIndex() {
    return /^(\s*)/.exec(this.b)[1].length;
  }
  get isEmptyOrWhitespace() {
    return this.firstNonWhitespaceCharacterIndex === this.b.length;
  }
};

// out-build/vs/base/common/idGenerator.js
var $lW = class {
  constructor(prefix) {
    this.a = prefix;
    this.b = 0;
  }
  nextId() {
    return this.a + ++this.b;
  }
};
var $mW = new $lW("id#");

// out-build/vs/workbench/api/common/extHostTextEditor.js
var $nW = class _$nW {
  static {
    this.c = new $lW("TextEditorDecorationType");
  }
  constructor(proxy, extension, options2) {
    const key = _$nW.c.nextId();
    proxy.$registerTextEditorDecorationType(extension.identifier, key, DecorationRenderOptions.from(options2));
    this.value = Object.freeze({
      key,
      dispose() {
        proxy.$removeTextEditorDecorationType(key);
      }
    });
  }
};
var TextEditorEdit = class {
  constructor(document2, options2) {
    this.g = [];
    this.h = void 0;
    this.j = false;
    this.c = document2;
    this.d = document2.version;
    this.e = options2.undoStopBefore;
    this.f = options2.undoStopAfter;
  }
  finalize() {
    this.j = true;
    return {
      documentVersionId: this.d,
      edits: this.g,
      setEndOfLine: this.h,
      undoStopBefore: this.e,
      undoStopAfter: this.f
    };
  }
  k() {
    if (this.j) {
      throw new Error("Edit is only valid while callback runs");
    }
  }
  replace(location2, value) {
    this.k();
    let range = null;
    if (location2 instanceof $AT) {
      range = new $BT(location2, location2);
    } else if (location2 instanceof $BT) {
      range = location2;
    } else {
      throw new Error("Unrecognized location");
    }
    this.l(range, value, false);
  }
  insert(location2, value) {
    this.k();
    this.l(new $BT(location2, location2), value, true);
  }
  delete(location2) {
    this.k();
    let range = null;
    if (location2 instanceof $BT) {
      range = location2;
    } else {
      throw new Error("Unrecognized location");
    }
    this.l(range, null, true);
  }
  l(range, text, forceMoveMarkers) {
    const validRange2 = this.c.validateRange(range);
    this.g.push({
      range: validRange2,
      text,
      forceMoveMarkers
    });
  }
  setEndOfLine(endOfLine) {
    this.k();
    if (endOfLine !== EndOfLine.LF && endOfLine !== EndOfLine.CRLF) {
      throw $nb("endOfLine");
    }
    this.h = endOfLine;
  }
};
var $oW = class {
  constructor(proxy, id2, source, logService) {
    this.c = proxy;
    this.d = id2;
    this._accept(source);
    this.e = logService;
    const that = this;
    this.value = {
      get tabSize() {
        return that.f;
      },
      set tabSize(value) {
        that.n(value);
      },
      get indentSize() {
        return that.g;
      },
      set indentSize(value) {
        that.p(value);
      },
      get insertSpaces() {
        return that.j;
      },
      set insertSpaces(value) {
        that.s(value);
      },
      get cursorStyle() {
        return that.k;
      },
      set cursorStyle(value) {
        that.t(value);
      },
      get lineNumbers() {
        return that.l;
      },
      set lineNumbers(value) {
        that.u(value);
      }
    };
  }
  _accept(source) {
    this.f = source.tabSize;
    this.g = source.indentSize;
    this.h = source.originalIndentSize;
    this.j = source.insertSpaces;
    this.k = source.cursorStyle;
    this.l = TextEditorLineNumbersStyle2.to(source.lineNumbers);
  }
  // --- internal: tabSize
  m(value) {
    if (value === "auto") {
      return "auto";
    }
    if (typeof value === "number") {
      const r = Math.floor(value);
      return r > 0 ? r : null;
    }
    if (typeof value === "string") {
      const r = parseInt(value, 10);
      if (isNaN(r)) {
        return null;
      }
      return r > 0 ? r : null;
    }
    return null;
  }
  n(value) {
    const tabSize = this.m(value);
    if (tabSize === null) {
      return;
    }
    if (typeof tabSize === "number") {
      if (this.f === tabSize) {
        return;
      }
      this.f = tabSize;
    }
    this.v("setTabSize", this.c.$trySetOptions(this.d, {
      tabSize
    }));
  }
  // --- internal: indentSize
  o(value) {
    if (value === "tabSize") {
      return "tabSize";
    }
    if (typeof value === "number") {
      const r = Math.floor(value);
      return r > 0 ? r : null;
    }
    if (typeof value === "string") {
      const r = parseInt(value, 10);
      if (isNaN(r)) {
        return null;
      }
      return r > 0 ? r : null;
    }
    return null;
  }
  p(value) {
    const indentSize = this.o(value);
    if (indentSize === null) {
      return;
    }
    if (typeof indentSize === "number") {
      if (this.h === indentSize) {
        return;
      }
      this.g = indentSize;
      this.h = indentSize;
    }
    this.v("setIndentSize", this.c.$trySetOptions(this.d, {
      indentSize
    }));
  }
  // --- internal: insert spaces
  q(value) {
    if (value === "auto") {
      return "auto";
    }
    return value === "false" ? false : Boolean(value);
  }
  s(value) {
    const insertSpaces = this.q(value);
    if (typeof insertSpaces === "boolean") {
      if (this.j === insertSpaces) {
        return;
      }
      this.j = insertSpaces;
    }
    this.v("setInsertSpaces", this.c.$trySetOptions(this.d, {
      insertSpaces
    }));
  }
  // --- internal: cursor style
  t(value) {
    if (this.k === value) {
      return;
    }
    this.k = value;
    this.v("setCursorStyle", this.c.$trySetOptions(this.d, {
      cursorStyle: value
    }));
  }
  // --- internal: line number
  u(value) {
    if (this.l === value) {
      return;
    }
    this.l = value;
    this.v("setLineNumbers", this.c.$trySetOptions(this.d, {
      lineNumbers: TextEditorLineNumbersStyle2.from(value)
    }));
  }
  assign(newOptions) {
    const bulkConfigurationUpdate = {};
    let hasUpdate = false;
    if (typeof newOptions.tabSize !== "undefined") {
      const tabSize = this.m(newOptions.tabSize);
      if (tabSize === "auto") {
        hasUpdate = true;
        bulkConfigurationUpdate.tabSize = tabSize;
      } else if (typeof tabSize === "number" && this.f !== tabSize) {
        this.f = tabSize;
        hasUpdate = true;
        bulkConfigurationUpdate.tabSize = tabSize;
      }
    }
    if (typeof newOptions.indentSize !== "undefined") {
      const indentSize = this.o(newOptions.indentSize);
      if (indentSize === "tabSize") {
        hasUpdate = true;
        bulkConfigurationUpdate.indentSize = indentSize;
      } else if (typeof indentSize === "number" && this.h !== indentSize) {
        this.g = indentSize;
        this.h = indentSize;
        hasUpdate = true;
        bulkConfigurationUpdate.indentSize = indentSize;
      }
    }
    if (typeof newOptions.insertSpaces !== "undefined") {
      const insertSpaces = this.q(newOptions.insertSpaces);
      if (insertSpaces === "auto") {
        hasUpdate = true;
        bulkConfigurationUpdate.insertSpaces = insertSpaces;
      } else if (this.j !== insertSpaces) {
        this.j = insertSpaces;
        hasUpdate = true;
        bulkConfigurationUpdate.insertSpaces = insertSpaces;
      }
    }
    if (typeof newOptions.cursorStyle !== "undefined") {
      if (this.k !== newOptions.cursorStyle) {
        this.k = newOptions.cursorStyle;
        hasUpdate = true;
        bulkConfigurationUpdate.cursorStyle = newOptions.cursorStyle;
      }
    }
    if (typeof newOptions.lineNumbers !== "undefined") {
      if (this.l !== newOptions.lineNumbers) {
        this.l = newOptions.lineNumbers;
        hasUpdate = true;
        bulkConfigurationUpdate.lineNumbers = TextEditorLineNumbersStyle2.from(newOptions.lineNumbers);
      }
    }
    if (hasUpdate) {
      this.v("setOptions", this.c.$trySetOptions(this.d, bulkConfigurationUpdate));
    }
  }
  v(action, promise) {
    promise.catch((err) => {
      this.e.warn(`ExtHostTextEditorOptions '${action}' failed:'`);
      this.e.warn(err);
    });
  }
};
var $pW = class {
  constructor(id2, k, l, document2, selections, options2, visibleRanges, viewColumn) {
    this.id = id2;
    this.k = k;
    this.l = l;
    this.g = false;
    this.h = /* @__PURE__ */ new Set();
    this.c = selections;
    this.d = new $oW(this.k, this.id, options2, l);
    this.e = visibleRanges;
    this.f = viewColumn;
    const that = this;
    this.value = Object.freeze({
      get document() {
        return document2.value;
      },
      set document(_value) {
        throw new $pb("document");
      },
      // --- selection
      get selection() {
        return that.c && that.c[0];
      },
      set selection(value) {
        if (!(value instanceof $CT)) {
          throw $nb("selection");
        }
        that.c = [value];
        that.m();
      },
      get selections() {
        return that.c;
      },
      set selections(value) {
        if (!Array.isArray(value) || value.some((a) => !(a instanceof $CT))) {
          throw $nb("selections");
        }
        that.c = value;
        that.m();
      },
      // --- visible ranges
      get visibleRanges() {
        return that.e;
      },
      set visibleRanges(_value) {
        throw new $pb("visibleRanges");
      },
      get diffInformation() {
        return that.j;
      },
      // --- options
      get options() {
        return that.d.value;
      },
      set options(value) {
        if (!that.g) {
          that.d.assign(value);
        }
      },
      // --- view column
      get viewColumn() {
        return that.f;
      },
      set viewColumn(_value) {
        throw new $pb("viewColumn");
      },
      // --- edit
      edit(callback, options3 = { undoStopBefore: true, undoStopAfter: true }) {
        if (that.g) {
          return Promise.reject(new Error("TextEditor#edit not possible on closed editors"));
        }
        const edit2 = new TextEditorEdit(document2.value, options3);
        callback(edit2);
        return that.n(edit2);
      },
      // --- snippet edit
      insertSnippet(snippet, where, options3 = { undoStopBefore: true, undoStopAfter: true }) {
        if (that.g) {
          return Promise.reject(new Error("TextEditor#insertSnippet not possible on closed editors"));
        }
        let ranges;
        if (!where || Array.isArray(where) && where.length === 0) {
          ranges = that.c.map((range) => Range.from(range));
        } else if (where instanceof $AT) {
          const { lineNumber, column } = Position.from(where);
          ranges = [{ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column }];
        } else if (where instanceof $BT) {
          ranges = [Range.from(where)];
        } else {
          ranges = [];
          for (const posOrRange of where) {
            if (posOrRange instanceof $BT) {
              ranges.push(Range.from(posOrRange));
            } else {
              const { lineNumber, column } = Position.from(posOrRange);
              ranges.push({ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column });
            }
          }
        }
        return k.$tryInsertSnippet(id2, document2.value.version, snippet.value, ranges, options3);
      },
      setDecorations(decorationType, ranges) {
        const willBeEmpty = ranges.length === 0;
        if (willBeEmpty && !that.h.has(decorationType.key)) {
          return;
        }
        if (willBeEmpty) {
          that.h.delete(decorationType.key);
        } else {
          that.h.add(decorationType.key);
        }
        that.o(() => {
          if ($dW(ranges)) {
            return k.$trySetDecorations(id2, decorationType.key, $eW(ranges));
          } else {
            const _ranges = new Array(4 * ranges.length);
            for (let i = 0, len = ranges.length; i < len; i++) {
              const range = ranges[i];
              _ranges[4 * i] = range.start.line + 1;
              _ranges[4 * i + 1] = range.start.character + 1;
              _ranges[4 * i + 2] = range.end.line + 1;
              _ranges[4 * i + 3] = range.end.character + 1;
            }
            return k.$trySetDecorationsFast(id2, decorationType.key, _ranges);
          }
        });
      },
      revealRange(range, revealType) {
        that.o(() => k.$tryRevealRange(id2, Range.from(range), revealType || TextEditorRevealType2.Default));
      },
      show(column) {
        k.$tryShowEditor(id2, ViewColumn2.from(column));
      },
      hide() {
        k.$tryHideEditor(id2);
      },
      [Symbol.for("debug.description")]() {
        return `TextEditor(${this.document.uri.toString()})`;
      }
    });
  }
  dispose() {
    ok(!this.g);
    this.g = true;
  }
  // --- incoming: extension host MUST accept what the renderer says
  _acceptOptions(options2) {
    ok(!this.g);
    this.d._accept(options2);
  }
  _acceptVisibleRanges(value) {
    ok(!this.g);
    this.e = value;
  }
  _acceptViewColumn(value) {
    ok(!this.g);
    this.f = value;
  }
  _acceptSelections(selections) {
    ok(!this.g);
    this.c = selections;
  }
  _acceptDiffInformation(diffInformation) {
    ok(!this.g);
    this.j = diffInformation;
  }
  async m() {
    const selection = this.c.map(Selection.from);
    await this.o(() => this.k.$trySetSelections(this.id, selection));
    return this.value;
  }
  n(editBuilder) {
    const editData = editBuilder.finalize();
    if (editData.edits.length === 0 && !editData.setEndOfLine) {
      return Promise.resolve(true);
    }
    const editRanges = editData.edits.map((edit2) => edit2.range);
    editRanges.sort((a, b) => {
      if (a.end.line === b.end.line) {
        if (a.end.character === b.end.character) {
          if (a.start.line === b.start.line) {
            return a.start.character - b.start.character;
          }
          return a.start.line - b.start.line;
        }
        return a.end.character - b.end.character;
      }
      return a.end.line - b.end.line;
    });
    for (let i = 0, count = editRanges.length - 1; i < count; i++) {
      const rangeEnd = editRanges[i].end;
      const nextRangeStart = editRanges[i + 1].start;
      if (nextRangeStart.isBefore(rangeEnd)) {
        return Promise.reject(new Error("Overlapping ranges are not allowed!"));
      }
    }
    const edits = editData.edits.map((edit2) => {
      return {
        range: Range.from(edit2.range),
        text: edit2.text,
        forceMoveMarkers: edit2.forceMoveMarkers
      };
    });
    return this.k.$tryApplyEdits(this.id, editData.documentVersionId, edits, {
      setEndOfLine: typeof editData.setEndOfLine === "number" ? EndOfLine2.from(editData.setEndOfLine) : void 0,
      undoStopBefore: editData.undoStopBefore,
      undoStopAfter: editData.undoStopAfter
    });
  }
  o(callback) {
    if (this.g) {
      this.l.warn("TextEditor is closed/disposed");
      return Promise.resolve(void 0);
    }
    return callback().then(() => this, (err) => {
      if (!(err instanceof Error && err.name === "DISPOSED")) {
        this.l.warn(err);
      }
      return null;
    });
  }
};

// out-build/vs/workbench/api/common/extHostDocumentsAndEditors.js
var Reference = class {
  constructor(value) {
    this.value = value;
    this.a = 0;
  }
  ref() {
    this.a++;
  }
  unref() {
    return --this.a === 0;
  }
};
var $qW = class $qW2 {
  constructor(h, i) {
    this.h = h;
    this.i = i;
    this.a = null;
    this.b = /* @__PURE__ */ new Map();
    this.c = new $Ec();
    this.d = new $ze();
    this.e = new $ze();
    this.f = new $ze();
    this.g = new $ze();
    this.onDidAddDocuments = this.d.event;
    this.onDidRemoveDocuments = this.e.event;
    this.onDidChangeVisibleTextEditors = this.f.event;
    this.onDidChangeActiveTextEditor = this.g.event;
  }
  $acceptDocumentsAndEditorsDelta(delta2) {
    this.acceptDocumentsAndEditorsDelta(delta2);
  }
  acceptDocumentsAndEditorsDelta(delta2) {
    const removedDocuments = [];
    const addedDocuments = [];
    const removedEditors = [];
    if (delta2.removedDocuments) {
      for (const uriComponent of delta2.removedDocuments) {
        const uri = URI.revive(uriComponent);
        const data = this.c.get(uri);
        if (data?.unref()) {
          this.c.delete(uri);
          removedDocuments.push(data.value);
        }
      }
    }
    if (delta2.addedDocuments) {
      for (const data of delta2.addedDocuments) {
        const resource = URI.revive(data.uri);
        let ref = this.c.get(resource);
        if (ref) {
          if (resource.scheme !== Schemas.vscodeNotebookCell && resource.scheme !== Schemas.vscodeInteractiveInput) {
            throw new Error(`document '${resource} already exists!'`);
          }
        }
        if (!ref) {
          ref = new Reference(new $jW(this.h.getProxy($xT.MainThreadDocuments), resource, data.lines, data.EOL, data.versionId, data.languageId, data.isDirty));
          this.c.set(resource, ref);
          addedDocuments.push(ref.value);
        }
        ref.ref();
      }
    }
    if (delta2.removedEditors) {
      for (const id2 of delta2.removedEditors) {
        const editor = this.b.get(id2);
        this.b.delete(id2);
        if (editor) {
          removedEditors.push(editor);
        }
      }
    }
    if (delta2.addedEditors) {
      for (const data of delta2.addedEditors) {
        const resource = URI.revive(data.documentUri);
        ok(this.c.has(resource), `document '${resource}' does not exist`);
        ok(!this.b.has(data.id), `editor '${data.id}' already exists!`);
        const documentData = this.c.get(resource).value;
        const editor = new $pW(data.id, this.h.getProxy($xT.MainThreadTextEditors), this.i, new $sf(() => documentData.document), data.selections.map(Selection.to), data.options, data.visibleRanges.map((range) => Range.to(range)), typeof data.editorPosition === "number" ? ViewColumn2.to(data.editorPosition) : void 0);
        this.b.set(data.id, editor);
      }
    }
    if (delta2.newActiveEditor !== void 0) {
      ok(delta2.newActiveEditor === null || this.b.has(delta2.newActiveEditor), `active editor '${delta2.newActiveEditor}' does not exist`);
      this.a = delta2.newActiveEditor;
    }
    $Xc(removedDocuments);
    $Xc(removedEditors);
    if (delta2.removedDocuments) {
      this.e.fire(removedDocuments);
    }
    if (delta2.addedDocuments) {
      this.d.fire(addedDocuments);
    }
    if (delta2.removedEditors || delta2.addedEditors) {
      this.f.fire(this.allEditors().map((editor) => editor.value));
    }
    if (delta2.newActiveEditor !== void 0) {
      this.g.fire(this.activeEditor());
    }
  }
  getDocument(uri) {
    return this.c.get(uri)?.value;
  }
  allDocuments() {
    return Iterable.map(this.c.values(), (ref) => ref.value);
  }
  getEditor(id2) {
    return this.b.get(id2);
  }
  activeEditor(internal) {
    if (!this.a) {
      return void 0;
    }
    const editor = this.b.get(this.a);
    if (internal) {
      return editor;
    } else {
      return editor?.value;
    }
  }
  allEditors() {
    return [...this.b.values()];
  }
};
$qW = __decorate([
  __param(0, $gW),
  __param(1, $wn)
], $qW);
var $rW = $Qk("IExtHostDocumentsAndEditors");

// out-build/vs/workbench/api/common/extHostApiDeprecationService.js
var $Lwc = $Qk("IExtHostApiDeprecationService");
var $Mwc = class $Mwc2 {
  constructor(rpc, c) {
    this.c = c;
    this.a = /* @__PURE__ */ new Set();
    this.b = rpc.getProxy($xT.MainThreadTelemetry);
  }
  report(apiId, extension, migrationSuggestion) {
    const key = this.d(apiId, extension);
    if (this.a.has(key)) {
      return;
    }
    this.a.add(key);
    if (extension.isUnderDevelopment) {
      this.c.warn(`[Deprecation Warning] '${apiId}' is deprecated. ${migrationSuggestion}`);
    }
    this.b.$publicLog2("extHostDeprecatedApiUsage", {
      extensionId: extension.identifier.value,
      apiId
    });
  }
  d(apiId, extension) {
    return `${apiId}-${extension.identifier.value}`;
  }
};
$Mwc = __decorate([
  __param(0, $gW),
  __param(1, $wn)
], $Mwc);
var $Nwc = Object.freeze(new class {
  report(_apiId, _extension, _warningMessage) {
  }
}());

// out-build/vs/platform/extensions/common/extensionsApiProposals.js
var _allApiProposals = {
  activeComment: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.activeComment.d.ts"
  },
  aiRelatedInformation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.aiRelatedInformation.d.ts"
  },
  aiTextSearchProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.aiTextSearchProvider.d.ts",
    version: 2
  },
  authLearnMore: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authLearnMore.d.ts"
  },
  authSession: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authSession.d.ts"
  },
  canonicalUriProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.canonicalUriProvider.d.ts"
  },
  chatEditing: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatEditing.d.ts"
  },
  chatParticipantAdditions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatParticipantAdditions.d.ts"
  },
  chatParticipantPrivate: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatParticipantPrivate.d.ts",
    version: 2
  },
  chatProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatProvider.d.ts"
  },
  chatReferenceBinaryData: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatReferenceBinaryData.d.ts"
  },
  chatTab: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatTab.d.ts"
  },
  chatVariableResolver: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatVariableResolver.d.ts"
  },
  codeActionAI: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.codeActionAI.d.ts"
  },
  codeActionRanges: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.codeActionRanges.d.ts"
  },
  codiconDecoration: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.codiconDecoration.d.ts"
  },
  commentReactor: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentReactor.d.ts"
  },
  commentReveal: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentReveal.d.ts"
  },
  commentThreadApplicability: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentThreadApplicability.d.ts"
  },
  commentingRangeHint: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentingRangeHint.d.ts"
  },
  commentsDraftState: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentsDraftState.d.ts"
  },
  contribAccessibilityHelpContent: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribAccessibilityHelpContent.d.ts"
  },
  contribCommentEditorActionsMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentEditorActionsMenu.d.ts"
  },
  contribCommentPeekContext: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentPeekContext.d.ts"
  },
  contribCommentThreadAdditionalMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentThreadAdditionalMenu.d.ts"
  },
  contribCommentsViewThreadMenus: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentsViewThreadMenus.d.ts"
  },
  contribDebugCreateConfiguration: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribDebugCreateConfiguration.d.ts"
  },
  contribDiffEditorGutterToolBarMenus: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribDiffEditorGutterToolBarMenus.d.ts"
  },
  contribEditSessions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribEditSessions.d.ts"
  },
  contribEditorContentMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribEditorContentMenu.d.ts"
  },
  contribLabelFormatterWorkspaceTooltip: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribLabelFormatterWorkspaceTooltip.d.ts"
  },
  contribMenuBarHome: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribMenuBarHome.d.ts"
  },
  contribMergeEditorMenus: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribMergeEditorMenus.d.ts"
  },
  contribMultiDiffEditorMenus: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribMultiDiffEditorMenus.d.ts"
  },
  contribNotebookStaticPreloads: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribNotebookStaticPreloads.d.ts"
  },
  contribRemoteHelp: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribRemoteHelp.d.ts"
  },
  contribShareMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribShareMenu.d.ts"
  },
  contribSourceControlHistoryItemMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlHistoryItemMenu.d.ts"
  },
  contribSourceControlHistoryTitleMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlHistoryTitleMenu.d.ts"
  },
  contribSourceControlInputBoxMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlInputBoxMenu.d.ts"
  },
  contribSourceControlTitleMenu: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlTitleMenu.d.ts"
  },
  contribStatusBarItems: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribStatusBarItems.d.ts"
  },
  contribViewContainerTitle: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribViewContainerTitle.d.ts"
  },
  contribViewsRemote: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribViewsRemote.d.ts"
  },
  contribViewsWelcome: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribViewsWelcome.d.ts"
  },
  createFileSystemWatcher: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.createFileSystemWatcher.d.ts"
  },
  customEditorMove: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.customEditorMove.d.ts"
  },
  debugVisualization: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.debugVisualization.d.ts"
  },
  defaultChatParticipant: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.defaultChatParticipant.d.ts",
    version: 2
  },
  diffCommand: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.diffCommand.d.ts"
  },
  diffContentOptions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.diffContentOptions.d.ts"
  },
  documentFiltersExclusive: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.documentFiltersExclusive.d.ts"
  },
  documentPaste: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.documentPaste.d.ts"
  },
  editSessionIdentityProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.editSessionIdentityProvider.d.ts"
  },
  editorHoverVerbosityLevel: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.editorHoverVerbosityLevel.d.ts"
  },
  editorInsets: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.editorInsets.d.ts"
  },
  embeddings: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.embeddings.d.ts"
  },
  extensionRuntime: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.extensionRuntime.d.ts"
  },
  extensionsAny: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.extensionsAny.d.ts"
  },
  externalUriOpener: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.externalUriOpener.d.ts"
  },
  fileComments: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fileComments.d.ts"
  },
  fileSearchProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fileSearchProvider.d.ts"
  },
  fileSearchProvider2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fileSearchProvider2.d.ts"
  },
  findFiles2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findFiles2.d.ts",
    version: 2
  },
  findTextInFiles: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findTextInFiles.d.ts"
  },
  findTextInFiles2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findTextInFiles2.d.ts"
  },
  fsChunks: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fsChunks.d.ts"
  },
  idToken: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.idToken.d.ts"
  },
  inlineCompletionsAdditions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.inlineCompletionsAdditions.d.ts"
  },
  inlineEdit: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.inlineEdit.d.ts"
  },
  interactive: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.interactive.d.ts"
  },
  interactiveWindow: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.interactiveWindow.d.ts"
  },
  ipc: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.ipc.d.ts"
  },
  languageModelSystem: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageModelSystem.d.ts"
  },
  languageStatusText: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageStatusText.d.ts"
  },
  mappedEditsProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.mappedEditsProvider.d.ts"
  },
  multiDocumentHighlightProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.multiDocumentHighlightProvider.d.ts"
  },
  nativeWindowHandle: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.nativeWindowHandle.d.ts"
  },
  newSymbolNamesProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.newSymbolNamesProvider.d.ts"
  },
  notebookCellExecution: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookCellExecution.d.ts"
  },
  notebookCellExecutionState: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookCellExecutionState.d.ts"
  },
  notebookControllerAffinityHidden: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookControllerAffinityHidden.d.ts"
  },
  notebookDeprecated: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookDeprecated.d.ts"
  },
  notebookExecution: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookExecution.d.ts"
  },
  notebookKernelSource: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookKernelSource.d.ts"
  },
  notebookLiveShare: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookLiveShare.d.ts"
  },
  notebookMessaging: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookMessaging.d.ts"
  },
  notebookMime: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookMime.d.ts"
  },
  notebookReplDocument: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookReplDocument.d.ts"
  },
  notebookVariableProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookVariableProvider.d.ts"
  },
  portsAttributes: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.portsAttributes.d.ts"
  },
  profileContentHandlers: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.profileContentHandlers.d.ts"
  },
  quickDiffProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickDiffProvider.d.ts"
  },
  quickInputButtonLocation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickInputButtonLocation.d.ts"
  },
  quickPickItemTooltip: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickPickItemTooltip.d.ts"
  },
  quickPickSortByLabel: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickPickSortByLabel.d.ts"
  },
  resolvers: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.resolvers.d.ts"
  },
  scmActionButton: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmActionButton.d.ts"
  },
  scmHistoryProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmHistoryProvider.d.ts"
  },
  scmMultiDiffEditor: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmMultiDiffEditor.d.ts"
  },
  scmSelectedProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmSelectedProvider.d.ts"
  },
  scmTextDocument: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmTextDocument.d.ts"
  },
  scmValidation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmValidation.d.ts"
  },
  shareProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.shareProvider.d.ts"
  },
  showLocal: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.showLocal.d.ts"
  },
  speech: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.speech.d.ts"
  },
  tabInputMultiDiff: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tabInputMultiDiff.d.ts"
  },
  tabInputTextMerge: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tabInputTextMerge.d.ts"
  },
  taskPresentationGroup: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.taskPresentationGroup.d.ts"
  },
  telemetry: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.telemetry.d.ts"
  },
  terminalCompletionProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalCompletionProvider.d.ts"
  },
  terminalDataWriteEvent: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalDataWriteEvent.d.ts"
  },
  terminalDimensions: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalDimensions.d.ts"
  },
  terminalExecuteCommandEvent: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalExecuteCommandEvent.d.ts"
  },
  terminalQuickFixProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalQuickFixProvider.d.ts"
  },
  terminalSelection: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalSelection.d.ts"
  },
  testObserver: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.testObserver.d.ts"
  },
  testRelatedCode: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.testRelatedCode.d.ts"
  },
  textEditorDiffInformation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textEditorDiffInformation.d.ts"
  },
  textSearchComplete2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchComplete2.d.ts"
  },
  textSearchProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchProvider.d.ts"
  },
  textSearchProvider2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchProvider2.d.ts"
  },
  timeline: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.timeline.d.ts"
  },
  tokenInformation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tokenInformation.d.ts"
  },
  treeViewActiveItem: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeViewActiveItem.d.ts"
  },
  treeViewMarkdownMessage: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeViewMarkdownMessage.d.ts"
  },
  treeViewReveal: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeViewReveal.d.ts"
  },
  tunnelFactory: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tunnelFactory.d.ts"
  },
  tunnels: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tunnels.d.ts"
  },
  valueSelectionInQuickPick: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.valueSelectionInQuickPick.d.ts"
  },
  workspaceTrust: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.workspaceTrust.d.ts"
  }
};
var allApiProposals = Object.freeze(_allApiProposals);

// out-build/vs/workbench/services/extensions/common/extensionsRegistry.js
var schemaRegistry = $Wn.as($Xn.JSONContribution);
var $pN = class _$pN {
  static a(arr) {
    const result = new $6z();
    for (let i = 0, len = arr.length; i < len; i++) {
      result.add(arr[i].description.identifier);
    }
    return result;
  }
  static compute(previous, current) {
    if (!previous || !previous.length) {
      return new _$pN(current, []);
    }
    if (!current || !current.length) {
      return new _$pN([], previous);
    }
    const previousSet = this.a(previous);
    const currentSet = this.a(current);
    const added = current.filter((user) => !previousSet.has(user.description.identifier));
    const removed = previous.filter((user) => !currentSet.has(user.description.identifier));
    return new _$pN(added, removed);
  }
  constructor(added, removed) {
    this.added = added;
    this.removed = removed;
  }
};
var $qN = class {
  constructor(name, defaultExtensionKind, canHandleResolver) {
    this.name = name;
    this.defaultExtensionKind = defaultExtensionKind;
    this.canHandleResolver = canHandleResolver;
    this.a = null;
    this.b = null;
    this.c = null;
  }
  setHandler(handler) {
    if (this.a !== null) {
      throw new Error("Handler already set!");
    }
    this.a = handler;
    this.d();
    return {
      dispose: () => {
        this.a = null;
      }
    };
  }
  acceptUsers(users) {
    this.c = $pN.compute(this.b, users);
    this.b = users;
    this.d();
  }
  d() {
    if (this.a === null || this.b === null || this.c === null) {
      return;
    }
    try {
      this.a(this.b, this.c);
    } catch (err) {
      $gb(err);
    }
  }
};
var extensionKindSchema = {
  type: "string",
  enum: [
    "ui",
    "workspace"
  ],
  enumDescriptions: [
    localize(12808, null),
    localize(12809, null)
  ]
};
var schemaId = "vscode://schemas/vscode-extensions";
var $rN = {
  properties: {
    engines: {
      type: "object",
      description: localize(12810, null),
      properties: {
        "vscode": {
          type: "string",
          description: localize(12811, null),
          default: "^1.22.0"
        }
      }
    },
    publisher: {
      description: localize(12812, null),
      type: "string"
    },
    displayName: {
      description: localize(12813, null),
      type: "string"
    },
    categories: {
      description: localize(12814, null),
      type: "array",
      uniqueItems: true,
      items: {
        oneOf: [
          {
            type: "string",
            enum: $4z
          },
          {
            type: "string",
            const: "Languages",
            deprecationMessage: localize(12815, null)
          }
        ]
      }
    },
    galleryBanner: {
      type: "object",
      description: localize(12816, null),
      properties: {
        color: {
          description: localize(12817, null),
          type: "string"
        },
        theme: {
          description: localize(12818, null),
          type: "string",
          enum: ["dark", "light"]
        }
      }
    },
    contributes: {
      description: localize(12819, null),
      type: "object",
      properties: {
        // extensions will fill in
      },
      default: {}
    },
    preview: {
      type: "boolean",
      description: localize(12820, null)
    },
    enableProposedApi: {
      type: "boolean",
      deprecationMessage: localize(12821, null)
    },
    enabledApiProposals: {
      markdownDescription: localize(12822, null),
      type: "array",
      uniqueItems: true,
      items: {
        type: "string",
        enum: Object.keys(allApiProposals).map((proposalName) => proposalName),
        markdownEnumDescriptions: Object.values(allApiProposals).map((value) => value.proposal)
      }
    },
    api: {
      markdownDescription: localize(12823, null),
      type: "string",
      enum: ["none"],
      enumDescriptions: [
        localize(12824, null)
      ]
    },
    activationEvents: {
      description: localize(12825, null),
      type: "array",
      items: {
        type: "string",
        defaultSnippets: [
          {
            label: "onWebviewPanel",
            description: localize(12826, null),
            body: "onWebviewPanel:viewType"
          },
          {
            label: "onLanguage",
            description: localize(12827, null),
            body: "onLanguage:${1:languageId}"
          },
          {
            label: "onCommand",
            description: localize(12828, null),
            body: "onCommand:${2:commandId}"
          },
          {
            label: "onDebug",
            description: localize(12829, null),
            body: "onDebug"
          },
          {
            label: "onDebugInitialConfigurations",
            description: localize(12830, null),
            body: "onDebugInitialConfigurations"
          },
          {
            label: "onDebugDynamicConfigurations",
            description: localize(12831, null),
            body: "onDebugDynamicConfigurations"
          },
          {
            label: "onDebugResolve",
            description: localize(12832, null),
            body: "onDebugResolve:${6:type}"
          },
          {
            label: "onDebugAdapterProtocolTracker",
            description: localize(12833, null),
            body: "onDebugAdapterProtocolTracker:${6:type}"
          },
          {
            label: "workspaceContains",
            description: localize(12834, null),
            body: "workspaceContains:${4:filePattern}"
          },
          {
            label: "onStartupFinished",
            description: localize(12835, null),
            body: "onStartupFinished"
          },
          {
            label: "onTaskType",
            description: localize(12836, null),
            body: "onTaskType:${1:taskType}"
          },
          {
            label: "onFileSystem",
            description: localize(12837, null),
            body: "onFileSystem:${1:scheme}"
          },
          {
            label: "onEditSession",
            description: localize(12838, null),
            body: "onEditSession:${1:scheme}"
          },
          {
            label: "onSearch",
            description: localize(12839, null),
            body: "onSearch:${7:scheme}"
          },
          {
            label: "onView",
            body: "onView:${5:viewId}",
            description: localize(12840, null)
          },
          {
            label: "onUri",
            body: "onUri",
            description: localize(12841, null)
          },
          {
            label: "onOpenExternalUri",
            body: "onOpenExternalUri",
            description: localize(12842, null)
          },
          {
            label: "onCustomEditor",
            body: "onCustomEditor:${9:viewType}",
            description: localize(12843, null)
          },
          {
            label: "onNotebook",
            body: "onNotebook:${1:type}",
            description: localize(12844, null)
          },
          {
            label: "onAuthenticationRequest",
            body: "onAuthenticationRequest:${11:authenticationProviderId}",
            description: localize(12845, null)
          },
          {
            label: "onRenderer",
            description: localize(12846, null),
            body: "onRenderer:${11:rendererId}"
          },
          {
            label: "onTerminalProfile",
            body: "onTerminalProfile:${1:terminalId}",
            description: localize(12847, null)
          },
          {
            label: "onTerminalQuickFixRequest",
            body: "onTerminalQuickFixRequest:${1:quickFixId}",
            description: localize(12848, null)
          },
          {
            label: "onWalkthrough",
            body: "onWalkthrough:${1:walkthroughID}",
            description: localize(12849, null)
          },
          {
            label: "onIssueReporterOpened",
            body: "onIssueReporterOpened",
            description: localize(12850, null)
          },
          {
            label: "onChatParticipant",
            body: "onChatParticipant:${1:participantId}",
            description: localize(12851, null)
          },
          {
            label: "onLanguageModelTool",
            body: "onLanguageModelTool:${1:toolId}",
            description: localize(12852, null)
          },
          {
            label: "onTerminalCompletionsRequested",
            body: "onTerminalCompletionsRequested",
            description: localize(12853, null)
          },
          {
            label: "*",
            description: localize(12854, null),
            body: "*"
          }
        ]
      }
    },
    badges: {
      type: "array",
      description: localize(12855, null),
      items: {
        type: "object",
        required: ["url", "href", "description"],
        properties: {
          url: {
            type: "string",
            description: localize(12856, null)
          },
          href: {
            type: "string",
            description: localize(12857, null)
          },
          description: {
            type: "string",
            description: localize(12858, null)
          }
        }
      }
    },
    markdown: {
      type: "string",
      description: localize(12859, null),
      enum: ["github", "standard"],
      default: "github"
    },
    qna: {
      default: "marketplace",
      description: localize(12860, null),
      anyOf: [
        {
          type: ["string", "boolean"],
          enum: ["marketplace", false]
        },
        {
          type: "string"
        }
      ]
    },
    extensionDependencies: {
      description: localize(12861, null),
      type: "array",
      uniqueItems: true,
      items: {
        type: "string",
        pattern: $cA
      }
    },
    extensionPack: {
      description: localize(12862, null),
      type: "array",
      uniqueItems: true,
      items: {
        type: "string",
        pattern: $cA
      }
    },
    extensionKind: {
      description: localize(12863, null),
      type: "array",
      items: extensionKindSchema,
      default: ["workspace"],
      defaultSnippets: [
        {
          body: ["ui"],
          description: localize(12864, null)
        },
        {
          body: ["workspace"],
          description: localize(12865, null)
        },
        {
          body: ["ui", "workspace"],
          description: localize(12866, null)
        },
        {
          body: ["workspace", "ui"],
          description: localize(12867, null)
        },
        {
          body: [],
          description: localize(12868, null)
        }
      ]
    },
    capabilities: {
      description: localize(12869, null),
      type: "object",
      properties: {
        virtualWorkspaces: {
          description: localize(12870, null),
          type: ["boolean", "object"],
          defaultSnippets: [
            { label: "limited", body: { supported: "${1:limited}", description: "${2}" } },
            { label: "false", body: { supported: false, description: "${2}" } }
          ],
          default: true.valueOf,
          properties: {
            supported: {
              markdownDescription: localize(12871, null),
              type: ["string", "boolean"],
              enum: ["limited", true, false],
              enumDescriptions: [
                localize(12872, null),
                localize(12873, null),
                localize(12874, null)
              ]
            },
            description: {
              type: "string",
              markdownDescription: localize(12875, null)
            }
          }
        },
        untrustedWorkspaces: {
          description: localize(12876, null),
          type: "object",
          required: ["supported"],
          defaultSnippets: [
            { body: { supported: "${1:limited}", description: "${2}" } }
          ],
          properties: {
            supported: {
              markdownDescription: localize(12877, null),
              type: ["string", "boolean"],
              enum: ["limited", true, false],
              enumDescriptions: [
                localize(12878, null),
                localize(12879, null),
                localize(12880, null)
              ]
            },
            restrictedConfigurations: {
              description: localize(12881, null),
              type: "array",
              items: {
                type: "string"
              }
            },
            description: {
              type: "string",
              markdownDescription: localize(12882, null)
            }
          }
        }
      }
    },
    sponsor: {
      description: localize(12883, null),
      type: "object",
      defaultSnippets: [
        { body: { url: "${1:https:}" } }
      ],
      properties: {
        "url": {
          description: localize(12884, null),
          type: "string"
        }
      }
    },
    scripts: {
      type: "object",
      properties: {
        "vscode:prepublish": {
          description: localize(12885, null),
          type: "string"
        },
        "vscode:uninstall": {
          description: localize(12886, null),
          type: "string"
        }
      }
    },
    icon: {
      type: "string",
      description: localize(12887, null)
    },
    l10n: {
      type: "string",
      description: localize(12888, null)
    },
    pricing: {
      type: "string",
      markdownDescription: localize(12889, null),
      enum: ["Free", "Trial"],
      default: "Free"
    }
  }
};
var $sN = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  registerExtensionPoint(desc) {
    if (this.a.has(desc.extensionPoint)) {
      throw new Error("Duplicate extension point: " + desc.extensionPoint);
    }
    const result = new $qN(desc.extensionPoint, desc.defaultExtensionKind, desc.canHandleResolver);
    this.a.set(desc.extensionPoint, result);
    if (desc.activationEventsGenerator) {
      $fN.register(desc.extensionPoint, desc.activationEventsGenerator);
    }
    $rN.properties["contributes"].properties[desc.extensionPoint] = desc.jsonSchema;
    schemaRegistry.registerSchema(schemaId, $rN);
    return result;
  }
  getExtensionPoints() {
    return Array.from(this.a.values());
  }
};
var PRExtensions = {
  ExtensionsRegistry: "ExtensionsRegistry"
};
$Wn.add(PRExtensions.ExtensionsRegistry, new $sN());
var $tN = $Wn.as(PRExtensions.ExtensionsRegistry);
schemaRegistry.registerSchema(schemaId, $rN);
schemaRegistry.registerSchema($Wu, {
  properties: {
    extensionEnabledApiProposals: {
      description: localize(12890, null),
      type: "object",
      properties: {},
      additionalProperties: {
        anyOf: [{
          type: "array",
          uniqueItems: true,
          items: {
            type: "string",
            enum: Object.keys(allApiProposals),
            markdownEnumDescriptions: Object.values(allApiProposals).map((value) => value.proposal)
          }
        }]
      }
    }
  }
});

// out-build/vs/workbench/contrib/tasks/common/taskDefinitionRegistry.js
var taskDefinitionSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    type: {
      type: "string",
      description: localize(10347, null)
    },
    required: {
      type: "array",
      items: {
        type: "string"
      }
    },
    properties: {
      type: "object",
      description: localize(10348, null),
      additionalProperties: {
        $ref: "http://json-schema.org/draft-07/schema#"
      }
    },
    when: {
      type: "string",
      markdownDescription: localize(10349, null),
      default: ""
    }
  }
};
var Configuration;
(function(Configuration2) {
  function from(value, extensionId, messageCollector) {
    if (!value) {
      return void 0;
    }
    const taskType = $zg(value.type) ? value.type : void 0;
    if (!taskType || taskType.length === 0) {
      messageCollector.error(localize(10350, null));
      return void 0;
    }
    const required = [];
    if (Array.isArray(value.required)) {
      for (const element of value.required) {
        if ($zg(element)) {
          required.push(element);
        }
      }
    }
    return {
      extensionId: extensionId.value,
      taskType,
      required,
      properties: value.properties ? $Lv(value.properties) : {},
      when: value.when ? $7m.deserialize(value.when) : void 0
    };
  }
  Configuration2.from = from;
})(Configuration || (Configuration = {}));
var taskDefinitionsExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "taskDefinitions",
  activationEventsGenerator: (contributions, result) => {
    for (const task of contributions) {
      if (task.type) {
        result.push(`onTaskType:${task.type}`);
      }
    }
  },
  jsonSchema: {
    description: localize(10351, null),
    type: "array",
    items: taskDefinitionSchema
  }
});
var TaskDefinitionRegistryImpl = class {
  constructor() {
    this.d = new $ze();
    this.onDefinitionsChanged = this.d.event;
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = new Promise((resolve, reject) => {
      taskDefinitionsExtPoint.setHandler((extensions, delta2) => {
        this.c = void 0;
        try {
          for (const extension of delta2.removed) {
            const taskTypes = extension.value;
            for (const taskType of taskTypes) {
              if (this.a && taskType.type && this.a[taskType.type]) {
                delete this.a[taskType.type];
              }
            }
          }
          for (const extension of delta2.added) {
            const taskTypes = extension.value;
            for (const taskType of taskTypes) {
              const type = Configuration.from(taskType, extension.description.identifier, extension.collector);
              if (type) {
                this.a[type.taskType] = type;
              }
            }
          }
          if (delta2.removed.length > 0 || delta2.added.length > 0) {
            this.d.fire();
          }
        } catch (error) {
        }
        resolve(void 0);
      });
    });
  }
  onReady() {
    return this.b;
  }
  get(key) {
    return this.a[key];
  }
  all() {
    return Object.keys(this.a).map((key) => this.a[key]);
  }
  getJsonSchema() {
    if (this.c === void 0) {
      const schemas = [];
      for (const definition of this.all()) {
        const schema = {
          type: "object",
          additionalProperties: false
        };
        if (definition.required.length > 0) {
          schema.required = definition.required.slice(0);
        }
        if (definition.properties !== void 0) {
          schema.properties = $Lv(definition.properties);
        } else {
          schema.properties = /* @__PURE__ */ Object.create(null);
        }
        schema.properties.type = {
          type: "string",
          enum: [definition.taskType]
        };
        schemas.push(schema);
      }
      this.c = { oneOf: schemas };
    }
    return this.c;
  }
};
var $aQ = new TaskDefinitionRegistryImpl();

// out-build/vs/workbench/contrib/tasks/common/tasks.js
var $bQ = "settings";
var $cQ = new $nn("taskRunning", false, localize(10352, null));
var $dQ = localize2(10354, "Tasks");
var ShellQuoting2;
(function(ShellQuoting3) {
  ShellQuoting3[ShellQuoting3["Escape"] = 1] = "Escape";
  ShellQuoting3[ShellQuoting3["Strong"] = 2] = "Strong";
  ShellQuoting3[ShellQuoting3["Weak"] = 3] = "Weak";
})(ShellQuoting2 || (ShellQuoting2 = {}));
(function(ShellQuoting3) {
  function from(value) {
    if (!value) {
      return ShellQuoting3.Strong;
    }
    switch (value.toLowerCase()) {
      case "escape":
        return ShellQuoting3.Escape;
      case "strong":
        return ShellQuoting3.Strong;
      case "weak":
        return ShellQuoting3.Weak;
      default:
        return ShellQuoting3.Strong;
    }
  }
  ShellQuoting3.from = from;
})(ShellQuoting2 || (ShellQuoting2 = {}));
var CommandOptions;
(function(CommandOptions2) {
  CommandOptions2.defaults = { cwd: "${workspaceFolder}" };
})(CommandOptions || (CommandOptions = {}));
var RevealKind;
(function(RevealKind2) {
  RevealKind2[RevealKind2["Always"] = 1] = "Always";
  RevealKind2[RevealKind2["Silent"] = 2] = "Silent";
  RevealKind2[RevealKind2["Never"] = 3] = "Never";
})(RevealKind || (RevealKind = {}));
(function(RevealKind2) {
  function fromString(value) {
    switch (value.toLowerCase()) {
      case "always":
        return RevealKind2.Always;
      case "silent":
        return RevealKind2.Silent;
      case "never":
        return RevealKind2.Never;
      default:
        return RevealKind2.Always;
    }
  }
  RevealKind2.fromString = fromString;
})(RevealKind || (RevealKind = {}));
var RevealProblemKind;
(function(RevealProblemKind2) {
  RevealProblemKind2[RevealProblemKind2["Never"] = 1] = "Never";
  RevealProblemKind2[RevealProblemKind2["OnProblem"] = 2] = "OnProblem";
  RevealProblemKind2[RevealProblemKind2["Always"] = 3] = "Always";
})(RevealProblemKind || (RevealProblemKind = {}));
(function(RevealProblemKind2) {
  function fromString(value) {
    switch (value.toLowerCase()) {
      case "always":
        return RevealProblemKind2.Always;
      case "never":
        return RevealProblemKind2.Never;
      case "onproblem":
        return RevealProblemKind2.OnProblem;
      default:
        return RevealProblemKind2.OnProblem;
    }
  }
  RevealProblemKind2.fromString = fromString;
})(RevealProblemKind || (RevealProblemKind = {}));
var PanelKind;
(function(PanelKind2) {
  PanelKind2[PanelKind2["Shared"] = 1] = "Shared";
  PanelKind2[PanelKind2["Dedicated"] = 2] = "Dedicated";
  PanelKind2[PanelKind2["New"] = 3] = "New";
})(PanelKind || (PanelKind = {}));
(function(PanelKind2) {
  function fromString(value) {
    switch (value.toLowerCase()) {
      case "shared":
        return PanelKind2.Shared;
      case "dedicated":
        return PanelKind2.Dedicated;
      case "new":
        return PanelKind2.New;
      default:
        return PanelKind2.Shared;
    }
  }
  PanelKind2.fromString = fromString;
})(PanelKind || (PanelKind = {}));
var PresentationOptions;
(function(PresentationOptions2) {
  PresentationOptions2.defaults = {
    echo: true,
    reveal: RevealKind.Always,
    revealProblems: RevealProblemKind.Never,
    focus: false,
    panel: PanelKind.Shared,
    showReuseMessage: true,
    clear: false
  };
})(PresentationOptions || (PresentationOptions = {}));
var RuntimeType;
(function(RuntimeType2) {
  RuntimeType2[RuntimeType2["Shell"] = 1] = "Shell";
  RuntimeType2[RuntimeType2["Process"] = 2] = "Process";
  RuntimeType2[RuntimeType2["CustomExecution"] = 3] = "CustomExecution";
})(RuntimeType || (RuntimeType = {}));
(function(RuntimeType2) {
  function fromString(value) {
    switch (value.toLowerCase()) {
      case "shell":
        return RuntimeType2.Shell;
      case "process":
        return RuntimeType2.Process;
      case "customExecution":
        return RuntimeType2.CustomExecution;
      default:
        return RuntimeType2.Process;
    }
  }
  RuntimeType2.fromString = fromString;
  function toString(value) {
    switch (value) {
      case RuntimeType2.Shell:
        return "shell";
      case RuntimeType2.Process:
        return "process";
      case RuntimeType2.CustomExecution:
        return "customExecution";
      default:
        return "process";
    }
  }
  RuntimeType2.toString = toString;
})(RuntimeType || (RuntimeType = {}));
var CommandString;
(function(CommandString2) {
  function value(value2) {
    if ($zg(value2)) {
      return value2;
    } else {
      return value2.value;
    }
  }
  CommandString2.value = value;
})(CommandString || (CommandString = {}));
var TaskGroup;
(function(TaskGroup2) {
  TaskGroup2.Clean = { _id: "clean", isDefault: false };
  TaskGroup2.Build = { _id: "build", isDefault: false };
  TaskGroup2.Rebuild = { _id: "rebuild", isDefault: false };
  TaskGroup2.Test = { _id: "test", isDefault: false };
  function is(value) {
    return value === TaskGroup2.Clean._id || value === TaskGroup2.Build._id || value === TaskGroup2.Rebuild._id || value === TaskGroup2.Test._id;
  }
  TaskGroup2.is = is;
  function from(value) {
    if (value === void 0) {
      return void 0;
    } else if ($zg(value)) {
      if (is(value)) {
        return { _id: value, isDefault: false };
      }
      return void 0;
    } else {
      return value;
    }
  }
  TaskGroup2.from = from;
})(TaskGroup || (TaskGroup = {}));
var TaskScope2;
(function(TaskScope3) {
  TaskScope3[TaskScope3["Global"] = 1] = "Global";
  TaskScope3[TaskScope3["Workspace"] = 2] = "Workspace";
  TaskScope3[TaskScope3["Folder"] = 3] = "Folder";
})(TaskScope2 || (TaskScope2 = {}));
var TaskSourceKind;
(function(TaskSourceKind2) {
  TaskSourceKind2.Workspace = "workspace";
  TaskSourceKind2.Extension = "extension";
  TaskSourceKind2.InMemory = "inMemory";
  TaskSourceKind2.WorkspaceFile = "workspaceFile";
  TaskSourceKind2.User = "user";
  function toConfigurationTarget(kind) {
    switch (kind) {
      case TaskSourceKind2.User:
        return 2;
      case TaskSourceKind2.WorkspaceFile:
        return 5;
      default:
        return 6;
    }
  }
  TaskSourceKind2.toConfigurationTarget = toConfigurationTarget;
})(TaskSourceKind || (TaskSourceKind = {}));
var DependsOrder;
(function(DependsOrder2) {
  DependsOrder2["parallel"] = "parallel";
  DependsOrder2["sequence"] = "sequence";
})(DependsOrder || (DependsOrder = {}));
var RunOnOptions;
(function(RunOnOptions2) {
  RunOnOptions2[RunOnOptions2["default"] = 1] = "default";
  RunOnOptions2[RunOnOptions2["folderOpen"] = 2] = "folderOpen";
})(RunOnOptions || (RunOnOptions = {}));
var RunOptions;
(function(RunOptions2) {
  RunOptions2.defaults = { reevaluateOnRerun: true, runOn: RunOnOptions.default, instanceLimit: 1 };
})(RunOptions || (RunOptions = {}));
var ExecutionEngine;
(function(ExecutionEngine2) {
  ExecutionEngine2[ExecutionEngine2["Process"] = 1] = "Process";
  ExecutionEngine2[ExecutionEngine2["Terminal"] = 2] = "Terminal";
})(ExecutionEngine || (ExecutionEngine = {}));
(function(ExecutionEngine2) {
  ExecutionEngine2._default = ExecutionEngine2.Terminal;
})(ExecutionEngine || (ExecutionEngine = {}));
var JsonSchemaVersion;
(function(JsonSchemaVersion2) {
  JsonSchemaVersion2[JsonSchemaVersion2["V0_1_0"] = 1] = "V0_1_0";
  JsonSchemaVersion2[JsonSchemaVersion2["V2_0_0"] = 2] = "V2_0_0";
})(JsonSchemaVersion || (JsonSchemaVersion = {}));
var TaskEventKind;
(function(TaskEventKind2) {
  TaskEventKind2["DependsOnStarted"] = "dependsOnStarted";
  TaskEventKind2["AcquiredInput"] = "acquiredInput";
  TaskEventKind2["Start"] = "start";
  TaskEventKind2["ProcessStarted"] = "processStarted";
  TaskEventKind2["Active"] = "active";
  TaskEventKind2["Inactive"] = "inactive";
  TaskEventKind2["Changed"] = "changed";
  TaskEventKind2["Terminated"] = "terminated";
  TaskEventKind2["ProcessEnded"] = "processEnded";
  TaskEventKind2["End"] = "end";
})(TaskEventKind || (TaskEventKind = {}));
var TaskRunType;
(function(TaskRunType2) {
  TaskRunType2["SingleRun"] = "singleRun";
  TaskRunType2["Background"] = "background";
})(TaskRunType || (TaskRunType = {}));
var TaskRunSource;
(function(TaskRunSource2) {
  TaskRunSource2[TaskRunSource2["System"] = 0] = "System";
  TaskRunSource2[TaskRunSource2["User"] = 1] = "User";
  TaskRunSource2[TaskRunSource2["FolderOpen"] = 2] = "FolderOpen";
  TaskRunSource2[TaskRunSource2["ConfigurationChange"] = 3] = "ConfigurationChange";
  TaskRunSource2[TaskRunSource2["Reconnect"] = 4] = "Reconnect";
})(TaskRunSource || (TaskRunSource = {}));
var TaskEvent;
(function(TaskEvent2) {
  function common(task) {
    return {
      taskId: task._id,
      taskName: task.configurationProperties.name,
      runType: task.configurationProperties.isBackground ? "background" : "singleRun",
      group: task.configurationProperties.group,
      __task: task
    };
  }
  function start(task, terminalId, resolvedVariables) {
    return {
      ...common(task),
      kind: "start",
      terminalId,
      resolvedVariables
    };
  }
  TaskEvent2.start = start;
  function processStarted(task, terminalId, processId) {
    return {
      ...common(task),
      kind: "processStarted",
      terminalId,
      processId
    };
  }
  TaskEvent2.processStarted = processStarted;
  function processEnded(task, terminalId, exitCode) {
    return {
      ...common(task),
      kind: "processEnded",
      terminalId,
      exitCode
    };
  }
  TaskEvent2.processEnded = processEnded;
  function terminated(task, terminalId, exitReason) {
    return {
      ...common(task),
      kind: "terminated",
      exitReason,
      terminalId
    };
  }
  TaskEvent2.terminated = terminated;
  function general(kind, task, terminalId) {
    return {
      ...common(task),
      kind,
      terminalId
    };
  }
  TaskEvent2.general = general;
  function changed() {
    return {
      kind: "changed"
      /* TaskEventKind.Changed */
    };
  }
  TaskEvent2.changed = changed;
})(TaskEvent || (TaskEvent = {}));
var KeyedTaskIdentifier;
(function(KeyedTaskIdentifier2) {
  function sortedStringify(literal) {
    const keys = Object.keys(literal).sort();
    let result = "";
    for (const key of keys) {
      let stringified = literal[key];
      if (stringified instanceof Object) {
        stringified = sortedStringify(stringified);
      } else if (typeof stringified === "string") {
        stringified = stringified.replace(/,/g, ",,");
      }
      result += key + "," + stringified + ",";
    }
    return result;
  }
  function create(value) {
    const resultKey = sortedStringify(value);
    const result = { _key: resultKey, type: value.taskType };
    Object.assign(result, value);
    return result;
  }
  KeyedTaskIdentifier2.create = create;
})(KeyedTaskIdentifier || (KeyedTaskIdentifier = {}));
var TaskSettingId;
(function(TaskSettingId2) {
  TaskSettingId2["AutoDetect"] = "task.autoDetect";
  TaskSettingId2["SaveBeforeRun"] = "task.saveBeforeRun";
  TaskSettingId2["ShowDecorations"] = "task.showDecorations";
  TaskSettingId2["ProblemMatchersNeverPrompt"] = "task.problemMatchers.neverPrompt";
  TaskSettingId2["SlowProviderWarning"] = "task.slowProviderWarning";
  TaskSettingId2["QuickOpenHistory"] = "task.quickOpen.history";
  TaskSettingId2["QuickOpenDetail"] = "task.quickOpen.detail";
  TaskSettingId2["QuickOpenSkip"] = "task.quickOpen.skip";
  TaskSettingId2["QuickOpenShowAll"] = "task.quickOpen.showAll";
  TaskSettingId2["AllowAutomaticTasks"] = "task.allowAutomaticTasks";
  TaskSettingId2["Reconnection"] = "task.reconnection";
  TaskSettingId2["VerboseLogging"] = "task.verboseLogging";
})(TaskSettingId || (TaskSettingId = {}));
var TasksSchemaProperties;
(function(TasksSchemaProperties2) {
  TasksSchemaProperties2["Tasks"] = "tasks";
  TasksSchemaProperties2["SuppressTaskName"] = "tasks.suppressTaskName";
  TasksSchemaProperties2["Windows"] = "tasks.windows";
  TasksSchemaProperties2["Osx"] = "tasks.osx";
  TasksSchemaProperties2["Linux"] = "tasks.linux";
  TasksSchemaProperties2["ShowOutput"] = "tasks.showOutput";
  TasksSchemaProperties2["IsShellCommand"] = "tasks.isShellCommand";
  TasksSchemaProperties2["ServiceTestSetting"] = "tasks.service.testSetting";
})(TasksSchemaProperties || (TasksSchemaProperties = {}));
var TaskDefinition;
(function(TaskDefinition2) {
  function createTaskIdentifier(external, reporter) {
    const definition = $aQ.get(external.type);
    if (definition === void 0) {
      const copy2 = $Lv(external);
      delete copy2._key;
      return KeyedTaskIdentifier.create(copy2);
    }
    const literal = /* @__PURE__ */ Object.create(null);
    literal.type = definition.taskType;
    const required = /* @__PURE__ */ new Set();
    definition.required.forEach((element) => required.add(element));
    const properties = definition.properties;
    for (const property of Object.keys(properties)) {
      const value = external[property];
      if (value !== void 0 && value !== null) {
        literal[property] = value;
      } else if (required.has(property)) {
        const schema = properties[property];
        if (schema.default !== void 0) {
          literal[property] = $Lv(schema.default);
        } else {
          switch (schema.type) {
            case "boolean":
              literal[property] = false;
              break;
            case "number":
            case "integer":
              literal[property] = 0;
              break;
            case "string":
              literal[property] = "";
              break;
            default:
              reporter.error(localize(10353, null, JSON.stringify(external, void 0, 0), property));
              return void 0;
          }
        }
      }
    }
    return KeyedTaskIdentifier.create(literal);
  }
  TaskDefinition2.createTaskIdentifier = createTaskIdentifier;
})(TaskDefinition || (TaskDefinition = {}));

// out-build/vs/workbench/api/common/extHostTask.js
var TaskDefinitionDTO;
(function(TaskDefinitionDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return value;
  }
  TaskDefinitionDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return value;
  }
  TaskDefinitionDTO2.to = to;
})(TaskDefinitionDTO || (TaskDefinitionDTO = {}));
var TaskPresentationOptionsDTO;
(function(TaskPresentationOptionsDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return value;
  }
  TaskPresentationOptionsDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return value;
  }
  TaskPresentationOptionsDTO2.to = to;
})(TaskPresentationOptionsDTO || (TaskPresentationOptionsDTO = {}));
var ProcessExecutionOptionsDTO;
(function(ProcessExecutionOptionsDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return value;
  }
  ProcessExecutionOptionsDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return value;
  }
  ProcessExecutionOptionsDTO2.to = to;
})(ProcessExecutionOptionsDTO || (ProcessExecutionOptionsDTO = {}));
var ProcessExecutionDTO;
(function(ProcessExecutionDTO2) {
  function is(value) {
    if (value) {
      const candidate = value;
      return candidate && !!candidate.process;
    } else {
      return false;
    }
  }
  ProcessExecutionDTO2.is = is;
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    const result = {
      process: value.process,
      args: value.args
    };
    if (value.options) {
      result.options = ProcessExecutionOptionsDTO.from(value.options);
    }
    return result;
  }
  ProcessExecutionDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return new $nU(value.process, value.args, value.options);
  }
  ProcessExecutionDTO2.to = to;
})(ProcessExecutionDTO || (ProcessExecutionDTO = {}));
var ShellExecutionOptionsDTO;
(function(ShellExecutionOptionsDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return value;
  }
  ShellExecutionOptionsDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return value;
  }
  ShellExecutionOptionsDTO2.to = to;
})(ShellExecutionOptionsDTO || (ShellExecutionOptionsDTO = {}));
var ShellExecutionDTO;
(function(ShellExecutionDTO2) {
  function is(value) {
    if (value) {
      const candidate = value;
      return candidate && (!!candidate.commandLine || !!candidate.command);
    } else {
      return false;
    }
  }
  ShellExecutionDTO2.is = is;
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    const result = {};
    if (value.commandLine !== void 0) {
      result.commandLine = value.commandLine;
    } else {
      result.command = value.command;
      result.args = value.args;
    }
    if (value.options) {
      result.options = ShellExecutionOptionsDTO.from(value.options);
    }
    return result;
  }
  ShellExecutionDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null || value.command === void 0 && value.commandLine === void 0) {
      return void 0;
    }
    if (value.commandLine) {
      return new $oU(value.commandLine, value.options);
    } else {
      return new $oU(value.command, value.args ? value.args : [], value.options);
    }
  }
  ShellExecutionDTO2.to = to;
})(ShellExecutionDTO || (ShellExecutionDTO = {}));
var CustomExecutionDTO;
(function(CustomExecutionDTO2) {
  function is(value) {
    if (value) {
      const candidate = value;
      return candidate && candidate.customExecution === "customExecution";
    } else {
      return false;
    }
  }
  CustomExecutionDTO2.is = is;
  function from(value) {
    return {
      customExecution: "customExecution"
    };
  }
  CustomExecutionDTO2.from = from;
  function to(taskId, providedCustomExeutions) {
    return providedCustomExeutions.get(taskId);
  }
  CustomExecutionDTO2.to = to;
})(CustomExecutionDTO || (CustomExecutionDTO = {}));
var TaskHandleDTO;
(function(TaskHandleDTO2) {
  function from(value, workspaceService) {
    let folder;
    if (value.scope !== void 0 && typeof value.scope !== "number") {
      folder = value.scope.uri;
    } else if (value.scope !== void 0 && typeof value.scope === "number") {
      if (value.scope === TaskScope.Workspace && workspaceService && workspaceService.workspaceFile) {
        folder = workspaceService.workspaceFile;
      } else {
        folder = $bQ;
      }
    }
    return {
      id: value._id,
      workspaceFolder: folder
    };
  }
  TaskHandleDTO2.from = from;
})(TaskHandleDTO || (TaskHandleDTO = {}));
var TaskGroupDTO;
(function(TaskGroupDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return { _id: value.id, isDefault: value.isDefault };
  }
  TaskGroupDTO2.from = from;
})(TaskGroupDTO || (TaskGroupDTO = {}));
var TaskDTO;
(function(TaskDTO2) {
  function fromMany(tasks, extension) {
    if (tasks === void 0 || tasks === null) {
      return [];
    }
    const result = [];
    for (const task of tasks) {
      const converted = from(task, extension);
      if (converted) {
        result.push(converted);
      }
    }
    return result;
  }
  TaskDTO2.fromMany = fromMany;
  function from(value, extension) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    let execution;
    if (value.execution instanceof $nU) {
      execution = ProcessExecutionDTO.from(value.execution);
    } else if (value.execution instanceof $oU) {
      execution = ShellExecutionDTO.from(value.execution);
    } else if (value.execution && value.execution instanceof $pU) {
      execution = CustomExecutionDTO.from(value.execution);
    }
    const definition = TaskDefinitionDTO.from(value.definition);
    let scope;
    if (value.scope) {
      if (typeof value.scope === "number") {
        scope = value.scope;
      } else {
        scope = value.scope.uri;
      }
    } else {
      scope = TaskScope.Workspace;
    }
    if (!definition || !scope) {
      return void 0;
    }
    const result = {
      _id: value._id,
      definition,
      name: value.name,
      source: {
        extensionId: extension.identifier.value,
        label: value.source,
        scope
      },
      execution,
      isBackground: value.isBackground,
      group: TaskGroupDTO.from(value.group),
      presentationOptions: TaskPresentationOptionsDTO.from(value.presentationOptions),
      problemMatchers: $5b(value.problemMatchers),
      hasDefinedMatchers: value.hasDefinedMatchers,
      runOptions: value.runOptions ? value.runOptions : { reevaluateOnRerun: true },
      detail: value.detail
    };
    return result;
  }
  TaskDTO2.from = from;
  async function to(value, workspace, providedCustomExeutions) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    let execution;
    if (ProcessExecutionDTO.is(value.execution)) {
      execution = ProcessExecutionDTO.to(value.execution);
    } else if (ShellExecutionDTO.is(value.execution)) {
      execution = ShellExecutionDTO.to(value.execution);
    } else if (CustomExecutionDTO.is(value.execution)) {
      execution = CustomExecutionDTO.to(value._id, providedCustomExeutions);
    }
    const definition = TaskDefinitionDTO.to(value.definition);
    let scope;
    if (value.source) {
      if (value.source.scope !== void 0) {
        if (typeof value.source.scope === "number") {
          scope = value.source.scope;
        } else {
          scope = await workspace.resolveWorkspaceFolder(URI.revive(value.source.scope));
        }
      } else {
        scope = TaskScope.Workspace;
      }
    }
    if (!definition || !scope) {
      return void 0;
    }
    const result = new $qU(definition, scope, value.name, value.source.label, execution, value.problemMatchers);
    if (value.isBackground !== void 0) {
      result.isBackground = value.isBackground;
    }
    if (value.group !== void 0) {
      result.group = $mU.from(value.group._id);
      if (result.group && value.group.isDefault) {
        result.group = new $mU(result.group.id, result.group.label);
        if (value.group.isDefault === true) {
          result.group.isDefault = value.group.isDefault;
        }
      }
    }
    if (value.presentationOptions) {
      result.presentationOptions = TaskPresentationOptionsDTO.to(value.presentationOptions);
    }
    if (value._id) {
      result._id = value._id;
    }
    if (value.detail) {
      result.detail = value.detail;
    }
    return result;
  }
  TaskDTO2.to = to;
})(TaskDTO || (TaskDTO = {}));
var TaskFilterDTO;
(function(TaskFilterDTO2) {
  function from(value) {
    return value;
  }
  TaskFilterDTO2.from = from;
  function to(value) {
    if (!value) {
      return void 0;
    }
    return Object.assign(/* @__PURE__ */ Object.create(null), value);
  }
  TaskFilterDTO2.to = to;
})(TaskFilterDTO || (TaskFilterDTO = {}));
var TaskExecutionImpl = class {
  #tasks;
  constructor(tasks, _id, a) {
    this._id = _id;
    this.a = a;
    this.#tasks = tasks;
  }
  get task() {
    return this.a;
  }
  terminate() {
    this.#tasks.terminateTask(this);
  }
  fireDidStartProcess(value) {
  }
  fireDidEndProcess(value) {
  }
};
var $Lyc = class $Lyc2 {
  constructor(extHostRpc, initData, workspaceService, editorService, configurationService, extHostTerminalService, logService, deprecationService) {
    this.q = new $ze();
    this.r = new $ze();
    this.s = new $ze();
    this.u = new $ze();
    this.a = extHostRpc.getProxy($xT.MainThreadTask);
    this.b = workspaceService;
    this.c = editorService;
    this.d = configurationService;
    this.e = extHostTerminalService;
    this.h = 0;
    this.j = /* @__PURE__ */ new Map();
    this.k = /* @__PURE__ */ new Map();
    this.l = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    this.n = /* @__PURE__ */ new Set();
    this.o = /* @__PURE__ */ new Map();
    this.f = logService;
    this.g = deprecationService;
    this.a.$registerSupportedExecutions(true);
  }
  registerTaskProvider(extension, type, provider) {
    if (!provider) {
      return new $zT(() => {
      });
    }
    const handle = this.x();
    this.j.set(handle, { type, provider, extension });
    this.a.$registerTaskProvider(handle, type);
    return new $zT(() => {
      this.j.delete(handle);
      this.a.$unregisterTaskProvider(handle);
    });
  }
  registerTaskSystem(scheme, info) {
    this.a.$registerTaskSystem(scheme, info);
  }
  fetchTasks(filter) {
    return this.a.$fetchTasks(TaskFilterDTO.from(filter)).then(async (values) => {
      const result = [];
      for (const value of values) {
        const task = await TaskDTO.to(value, this.b, this.m);
        if (task) {
          result.push(task);
        }
      }
      return result;
    });
  }
  get taskExecutions() {
    const result = [];
    this.k.forEach((value) => result.push(value));
    return result;
  }
  terminateTask(execution) {
    if (!(execution instanceof TaskExecutionImpl)) {
      throw new Error("No valid task execution provided");
    }
    return this.a.$terminateTask(execution._id);
  }
  get onDidStartTask() {
    return this.q.event;
  }
  async $onDidStartTask(execution, terminalId, resolvedDefinition) {
    const customExecution = this.m.get(execution.id);
    if (customExecution) {
      this.o.set(execution.id, customExecution);
      this.e.attachPtyToTerminal(terminalId, await customExecution.callback(resolvedDefinition));
    }
    this.p = execution.id;
    this.q.fire({
      execution: await this.z(execution)
    });
  }
  get onDidEndTask() {
    return this.r.event;
  }
  async $OnDidEndTask(execution) {
    if (!this.l.has(execution.id)) {
      return;
    }
    const _execution = await this.z(execution);
    this.l.delete(execution.id);
    this.k.delete(execution.id);
    this.B(execution);
    this.r.fire({
      execution: _execution
    });
  }
  get onDidStartTaskProcess() {
    return this.s.event;
  }
  async $onDidStartTaskProcess(value) {
    const execution = await this.z(value.id);
    this.s.fire({
      execution,
      processId: value.processId
    });
  }
  get onDidEndTaskProcess() {
    return this.u.event;
  }
  async $onDidEndTaskProcess(value) {
    const execution = await this.z(value.id);
    this.u.fire({
      execution,
      exitCode: value.exitCode
    });
  }
  $provideTasks(handle, validTypes) {
    const handler = this.j.get(handle);
    if (!handler) {
      return Promise.reject(new Error("no handler found"));
    }
    const taskIdPromises = [];
    const fetchPromise = $Nh(() => handler.provider.provideTasks(CancellationToken.None)).then((value) => {
      return this.v(validTypes, taskIdPromises, handler, value);
    });
    return new Promise((resolve) => {
      fetchPromise.then((result) => {
        Promise.all(taskIdPromises).then(() => {
          resolve(result);
        });
      });
    });
  }
  async $resolveTask(handle, taskDTO) {
    const handler = this.j.get(handle);
    if (!handler) {
      return Promise.reject(new Error("no handler found"));
    }
    if (taskDTO.definition.type !== handler.type) {
      throw new Error(`Unexpected: Task of type [${taskDTO.definition.type}] cannot be resolved by provider of type [${handler.type}].`);
    }
    const task = await TaskDTO.to(taskDTO, this.b, this.m);
    if (!task) {
      throw new Error("Unexpected: Task cannot be resolved.");
    }
    const resolvedTask = await handler.provider.resolveTask(task, CancellationToken.None);
    if (!resolvedTask) {
      return;
    }
    this.A(resolvedTask, handler);
    const resolvedTaskDTO = TaskDTO.from(resolvedTask, handler.extension);
    if (!resolvedTaskDTO) {
      throw new Error("Unexpected: Task cannot be resolved.");
    }
    if (resolvedTask.definition !== task.definition) {
      throw new Error("Unexpected: The resolved task definition must be the same object as the original task definition. The task definition cannot be changed.");
    }
    if (CustomExecutionDTO.is(resolvedTaskDTO.execution)) {
      await this.y(resolvedTaskDTO, resolvedTask, true);
    }
    return await this.w(resolvedTaskDTO);
  }
  x() {
    return this.h++;
  }
  async y(taskDTO, task, isProvided) {
    const taskId = await this.a.$createTaskId(taskDTO);
    if (!isProvided && !this.m.has(taskId)) {
      this.n.add(taskId);
      this.o.set(taskId, task.execution);
    }
    this.m.set(taskId, task.execution);
  }
  async z(execution, task) {
    if (typeof execution === "string") {
      const taskExecution = this.l.get(execution);
      if (!taskExecution) {
        throw new $ub("Unexpected: The specified task is missing an execution");
      }
      return taskExecution;
    }
    const result = this.l.get(execution.id);
    if (result) {
      return result;
    }
    let executionPromise;
    if (!task) {
      executionPromise = TaskDTO.to(execution.task, this.b, this.m).then((t) => {
        if (!t) {
          throw new $ub("Unexpected: Task does not exist.");
        }
        return new TaskExecutionImpl(this, execution.id, t);
      });
    } else {
      executionPromise = Promise.resolve(new TaskExecutionImpl(this, execution.id, task));
    }
    this.l.set(execution.id, executionPromise);
    return executionPromise.then((taskExecution) => {
      this.k.set(execution.id, taskExecution);
      return taskExecution;
    });
  }
  A(task, handler) {
    const tTask = task;
    if (tTask._deprecated) {
      this.g.report("Task.constructor", handler.extension, "Use the Task constructor that takes a `scope` instead.");
    }
  }
  B(execution) {
    const extensionCallback2 = this.o.get(execution.id);
    if (extensionCallback2) {
      this.o.delete(execution.id);
    }
    if (this.n.has(execution.id) && this.p !== execution.id) {
      this.m.delete(execution.id);
      this.n.delete(execution.id);
    }
    const iterator = this.n.values();
    let iteratorResult = iterator.next();
    while (!iteratorResult.done) {
      if (!this.o.has(iteratorResult.value) && this.p !== iteratorResult.value) {
        this.m.delete(iteratorResult.value);
        this.n.delete(iteratorResult.value);
      }
      iteratorResult = iterator.next();
    }
  }
};
$Lyc = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $0wc),
  __param(3, $rW),
  __param(4, $axc),
  __param(5, $yxc),
  __param(6, $wn),
  __param(7, $Lwc)
], $Lyc);
var $Myc = class $Myc2 extends $Lyc {
  constructor(extHostRpc, initData, workspaceService, editorService, configurationService, extHostTerminalService, logService, deprecationService) {
    super(extHostRpc, initData, workspaceService, editorService, configurationService, extHostTerminalService, logService, deprecationService);
    this.registerTaskSystem(Schemas.vscodeRemote, {
      scheme: Schemas.vscodeRemote,
      authority: "",
      platform: $k(
        0
        /* Platform.Platform.Web */
      )
    });
  }
  async executeTask(extension, task) {
    if (!task.execution) {
      throw new Error("Tasks to execute must include an execution");
    }
    const dto = TaskDTO.from(task, extension);
    if (dto === void 0) {
      throw new Error("Task is not valid");
    }
    if (CustomExecutionDTO.is(dto.execution)) {
      await this.y(dto, task, false);
    } else {
      throw new $sb();
    }
    const execution = await this.z(await this.a.$getTaskExecution(dto), task);
    this.a.$executeTask(dto).catch((error) => {
      throw new Error(error);
    });
    return execution;
  }
  v(validTypes, taskIdPromises, handler, value) {
    const taskDTOs = [];
    if (value) {
      for (const task of value) {
        this.A(task, handler);
        if (!task.definition || !validTypes[task.definition.type]) {
          const source = task.source ? task.source : "No task source";
          this.f.warn(`The task [${source}, ${task.name}] uses an undefined task type. The task will be ignored in the future.`);
        }
        const taskDTO = TaskDTO.from(task, handler.extension);
        if (taskDTO && CustomExecutionDTO.is(taskDTO.execution)) {
          taskDTOs.push(taskDTO);
          taskIdPromises.push(this.y(taskDTO, task, true));
        } else {
          this.f.warn("Only custom execution tasks supported.");
        }
      }
    }
    return {
      tasks: taskDTOs,
      extension: handler.extension
    };
  }
  async w(resolvedTaskDTO) {
    if (CustomExecutionDTO.is(resolvedTaskDTO.execution)) {
      return resolvedTaskDTO;
    } else {
      this.f.warn("Only custom execution tasks supported.");
    }
    return void 0;
  }
  async $resolveVariables(uriComponents, toResolve) {
    const result = {
      process: void 0,
      variables: /* @__PURE__ */ Object.create(null)
    };
    return result;
  }
  async $jsonTasksSupported() {
    return false;
  }
  async $findExecutable(command, cwd2, paths) {
    return void 0;
  }
};
$Myc = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $0wc),
  __param(3, $rW),
  __param(4, $axc),
  __param(5, $yxc),
  __param(6, $wn),
  __param(7, $Lwc)
], $Myc);
var $Nyc = $Qk("IExtHostTask");

// out-build/vs/workbench/contrib/debug/common/abstractDebugAdapter.js
var $xOb = class {
  constructor() {
    this.f = /* @__PURE__ */ new Map();
    this.m = [];
    this.n = new $ze();
    this.o = new $ze();
    this.d = 1;
  }
  get onError() {
    return this.n.event;
  }
  get onExit() {
    return this.o.event;
  }
  onMessage(callback) {
    if (this.k) {
      this.n.fire(new Error(`attempt to set more than one 'Message' callback`));
    }
    this.k = callback;
  }
  onEvent(callback) {
    if (this.j) {
      this.n.fire(new Error(`attempt to set more than one 'Event' callback`));
    }
    this.j = callback;
  }
  onRequest(callback) {
    if (this.g) {
      this.n.fire(new Error(`attempt to set more than one 'Request' callback`));
    }
    this.g = callback;
  }
  sendResponse(response) {
    if (response.seq > 0) {
      this.n.fire(new Error(`attempt to send more than one response for command ${response.command}`));
    } else {
      this.u("response", response);
    }
  }
  sendRequest(command, args2, clb, timeout) {
    const request = {
      command
    };
    if (args2 && Object.keys(args2).length > 0) {
      request.arguments = args2;
    }
    this.u("request", request);
    if (typeof timeout === "number") {
      const timer2 = setTimeout(() => {
        clearTimeout(timer2);
        const clb2 = this.f.get(request.seq);
        if (clb2) {
          this.f.delete(request.seq);
          const err = {
            type: "response",
            seq: 0,
            request_seq: request.seq,
            success: false,
            command,
            message: localize(6102, null, timeout, command)
          };
          clb2(err);
        }
      }, timeout);
    }
    if (clb) {
      this.f.set(request.seq, clb);
    }
    return request.seq;
  }
  acceptMessage(message) {
    if (this.k) {
      this.k(message);
    } else {
      this.m.push(message);
      if (this.m.length === 1) {
        this.s();
      }
    }
  }
  /**
   * Returns whether we should insert a timeout between processing messageA
   * and messageB. Artificially queueing protocol messages guarantees that any
   * microtasks for previous message finish before next message is processed.
   * This is essential ordering when using promises anywhere along the call path.
   *
   * For example, take the following, where `chooseAndSendGreeting` returns
   * a person name and then emits a greeting event:
   *
   * ```
   * let person: string;
   * adapter.onGreeting(() => console.log('hello', person));
   * person = await adapter.chooseAndSendGreeting();
   * ```
   *
   * Because the event is dispatched synchronously, it may fire before person
   * is assigned if they're processed in the same task. Inserting a task
   * boundary avoids this issue.
   */
  q(messageA, messageB) {
    return messageA.type !== "event" || messageB.type !== "event";
  }
  /**
   * Reads and dispatches items from the queue until it is empty.
   */
  async s() {
    let message;
    while (this.m.length) {
      if (!message || this.q(this.m[0], message)) {
        await $Wh(0);
      }
      message = this.m.shift();
      if (!message) {
        return;
      }
      switch (message.type) {
        case "event":
          this.j?.(message);
          break;
        case "request":
          this.g?.(message);
          break;
        case "response": {
          const response = message;
          const clb = this.f.get(response.request_seq);
          if (clb) {
            this.f.delete(response.request_seq);
            clb(response);
          }
          break;
        }
      }
    }
  }
  u(typ, message) {
    message.type = typ;
    message.seq = this.d++;
    this.sendMessage(message);
  }
  async w() {
    if (this.f.size === 0) {
      return Promise.resolve();
    }
    const pending = /* @__PURE__ */ new Map();
    this.f.forEach((value, key) => pending.set(key, value));
    await $Wh(500);
    pending.forEach((callback, request_seq) => {
      const err = {
        type: "response",
        seq: 0,
        request_seq,
        success: false,
        command: "canceled",
        message: "canceled"
      };
      callback(err);
      this.f.delete(request_seq);
    });
  }
  getPendingRequestIds() {
    return Array.from(this.f.keys());
  }
  dispose() {
    this.m = [];
  }
};

// out-build/vs/workbench/contrib/debug/common/debugUtils.js
function $rP(dbg) {
  return dbg.type && (dbg.label || dbg.program || dbg.runtime);
}
var _schemePattern2 = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/;
function $uP(s) {
  return !!(s && s.match(_schemePattern2));
}
function stringToUri(source) {
  if (typeof source.path === "string") {
    if (typeof source.sourceReference === "number" && source.sourceReference > 0) {
    } else {
      if ($uP(source.path)) {
        return URI.parse(source.path);
      } else {
        if ($mc(source.path)) {
          return URI.file(source.path);
        } else {
        }
      }
    }
  }
  return source.path;
}
function uriToString(source) {
  if (typeof source.path === "object") {
    const u = URI.revive(source.path);
    if (u) {
      if (u.scheme === Schemas.file) {
        return u.fsPath;
      } else {
        return u.toString();
      }
    }
  }
  return source.path;
}
function $vP(message, toUri) {
  const fixPath = toUri ? stringToUri : uriToString;
  const msg = $Lv(message);
  convertPaths(msg, (toDA, source) => {
    if (toDA && source) {
      source.path = fixPath(source);
    }
  });
  return msg;
}
function $wP(message, toUri) {
  const fixPath = toUri ? stringToUri : uriToString;
  const msg = $Lv(message);
  convertPaths(msg, (toDA, source) => {
    if (!toDA && source) {
      source.path = fixPath(source);
    }
  });
  return msg;
}
function convertPaths(msg, fixSourcePath) {
  switch (msg.type) {
    case "event": {
      const event = msg;
      switch (event.event) {
        case "output":
          fixSourcePath(false, event.body.source);
          break;
        case "loadedSource":
          fixSourcePath(false, event.body.source);
          break;
        case "breakpoint":
          fixSourcePath(false, event.body.breakpoint.source);
          break;
        default:
          break;
      }
      break;
    }
    case "request": {
      const request = msg;
      switch (request.command) {
        case "setBreakpoints":
          fixSourcePath(true, request.arguments.source);
          break;
        case "breakpointLocations":
          fixSourcePath(true, request.arguments.source);
          break;
        case "source":
          fixSourcePath(true, request.arguments.source);
          break;
        case "gotoTargets":
          fixSourcePath(true, request.arguments.source);
          break;
        case "launchVSCode":
          request.arguments.args.forEach((arg) => fixSourcePath(false, arg));
          break;
        default:
          break;
      }
      break;
    }
    case "response": {
      const response = msg;
      if (response.success && response.body) {
        switch (response.command) {
          case "stackTrace":
            response.body.stackFrames.forEach((frame) => fixSourcePath(false, frame.source));
            break;
          case "loadedSources":
            response.body.sources.forEach((source) => fixSourcePath(false, source));
            break;
          case "scopes":
            response.body.scopes.forEach((scope) => fixSourcePath(false, scope.source));
            break;
          case "setFunctionBreakpoints":
            response.body.breakpoints.forEach((bp) => fixSourcePath(false, bp.source));
            break;
          case "setBreakpoints":
            response.body.breakpoints.forEach((bp) => fixSourcePath(false, bp.source));
            break;
          case "disassemble":
            {
              const di = response;
              di.body?.instructions.forEach((di2) => fixSourcePath(false, di2.location));
            }
            break;
          case "locations":
            fixSourcePath(false, response.body?.source);
            break;
          default:
            break;
        }
      }
      break;
    }
  }
}

// out-build/vs/workbench/api/common/extHostEditorTabs.js
var $mxc = $Qk("IExtHostEditorTabs");
var ExtHostEditorTab = class {
  constructor(dto, parentGroup, activeTabIdGetter) {
    this.e = activeTabIdGetter;
    this.d = parentGroup;
    this.acceptDtoUpdate(dto);
  }
  get apiObject() {
    if (!this.a) {
      const that = this;
      const obj = {
        get isActive() {
          return that.b.id === that.e();
        },
        get label() {
          return that.b.label;
        },
        get input() {
          return that.c;
        },
        get isDirty() {
          return that.b.isDirty;
        },
        get isPinned() {
          return that.b.isPinned;
        },
        get isPreview() {
          return that.b.isPreview;
        },
        get group() {
          return that.d.apiObject;
        }
      };
      this.a = Object.freeze(obj);
    }
    return this.a;
  }
  get tabId() {
    return this.b.id;
  }
  acceptDtoUpdate(dto) {
    this.b = dto;
    this.c = this.f();
  }
  f() {
    switch (this.b.input.kind) {
      case 1:
        return new $rV(URI.revive(this.b.input.uri));
      case 2:
        return new $sV(URI.revive(this.b.input.original), URI.revive(this.b.input.modified));
      case 3:
        return new $tV(URI.revive(this.b.input.base), URI.revive(this.b.input.input1), URI.revive(this.b.input.input2), URI.revive(this.b.input.result));
      case 6:
        return new $uV(URI.revive(this.b.input.uri), this.b.input.viewType);
      case 7:
        return new $vV(this.b.input.viewType);
      case 4:
        return new $wV(URI.revive(this.b.input.uri), this.b.input.notebookType);
      case 5:
        return new $xV(URI.revive(this.b.input.original), URI.revive(this.b.input.modified), this.b.input.notebookType);
      case 8:
        return new $yV();
      case 9:
        return new $zV(URI.revive(this.b.input.uri), URI.revive(this.b.input.inputBoxUri));
      case 10:
        return new $AV();
      case 11:
        return new $BV(this.b.input.diffEditors.map((diff2) => new $sV(URI.revive(diff2.original), URI.revive(diff2.modified))));
      default:
        return void 0;
    }
  }
};
var ExtHostEditorTabGroup = class {
  constructor(dto, activeGroupIdGetter) {
    this.c = [];
    this.d = "";
    this.b = dto;
    this.e = activeGroupIdGetter;
    for (const tabDto of dto.tabs) {
      if (tabDto.isActive) {
        this.d = tabDto.id;
      }
      this.c.push(new ExtHostEditorTab(tabDto, this, () => this.activeTabId()));
    }
  }
  get apiObject() {
    if (!this.a) {
      const that = this;
      const obj = {
        get isActive() {
          return that.b.groupId === that.e();
        },
        get viewColumn() {
          return ViewColumn2.to(that.b.viewColumn);
        },
        get activeTab() {
          return that.c.find((tab) => tab.tabId === that.d)?.apiObject;
        },
        get tabs() {
          return Object.freeze(that.c.map((tab) => tab.apiObject));
        }
      };
      this.a = Object.freeze(obj);
    }
    return this.a;
  }
  get groupId() {
    return this.b.groupId;
  }
  get tabs() {
    return this.c;
  }
  acceptGroupDtoUpdate(dto) {
    this.b = dto;
  }
  acceptTabOperation(operation) {
    if (operation.kind === 0) {
      const tab2 = new ExtHostEditorTab(operation.tabDto, this, () => this.activeTabId());
      this.c.splice(operation.index, 0, tab2);
      if (operation.tabDto.isActive) {
        this.d = tab2.tabId;
      }
      return tab2;
    } else if (operation.kind === 1) {
      const tab2 = this.c.splice(operation.index, 1)[0];
      if (!tab2) {
        throw new Error(`Tab close updated received for index ${operation.index} which does not exist`);
      }
      if (tab2.tabId === this.d) {
        this.d = "";
      }
      return tab2;
    } else if (operation.kind === 3) {
      if (operation.oldIndex === void 0) {
        throw new Error("Invalid old index on move IPC");
      }
      const tab2 = this.c.splice(operation.oldIndex, 1)[0];
      if (!tab2) {
        throw new Error(`Tab move updated received for index ${operation.oldIndex} which does not exist`);
      }
      this.c.splice(operation.index, 0, tab2);
      return tab2;
    }
    const tab = this.c.find((extHostTab) => extHostTab.tabId === operation.tabDto.id);
    if (!tab) {
      throw new Error("INVALID tab");
    }
    if (operation.tabDto.isActive) {
      this.d = operation.tabDto.id;
    } else if (this.d === operation.tabDto.id && !operation.tabDto.isActive) {
      this.d = "";
    }
    tab.acceptDtoUpdate(operation.tabDto);
    return tab;
  }
  // Not a getter since it must be a function to be used as a callback for the tabs
  activeTabId() {
    return this.d;
  }
};
var $nxc = class $nxc2 {
  constructor(extHostRpc) {
    this.b = new $ze();
    this.c = new $ze();
    this.e = [];
    this.a = extHostRpc.getProxy($xT.MainThreadEditorTabs);
  }
  get tabGroups() {
    if (!this.f) {
      const that = this;
      const obj = {
        // never changes -> simple value
        onDidChangeTabGroups: that.c.event,
        onDidChangeTabs: that.b.event,
        // dynamic -> getters
        get all() {
          return Object.freeze(that.e.map((group) => group.apiObject));
        },
        get activeTabGroup() {
          const activeTabGroupId = that.d;
          const activeTabGroup = $Kg(that.e.find((candidate) => candidate.groupId === activeTabGroupId)?.apiObject);
          return activeTabGroup;
        },
        close: async (tabOrTabGroup, preserveFocus) => {
          const tabsOrTabGroups = Array.isArray(tabOrTabGroup) ? tabOrTabGroup : [tabOrTabGroup];
          if (!tabsOrTabGroups.length) {
            return true;
          }
          if (isTabGroup(tabsOrTabGroups[0])) {
            return this.j(tabsOrTabGroups, preserveFocus);
          } else {
            return this.i(tabsOrTabGroups, preserveFocus);
          }
        }
        // move: async (tab: vscode.Tab, viewColumn: ViewColumn, index: number, preserveFocus?: boolean) => {
        // 	const extHostTab = this._findExtHostTabFromApi(tab);
        // 	if (!extHostTab) {
        // 		throw new Error('Invalid tab');
        // 	}
        // 	this._proxy.$moveTab(extHostTab.tabId, index, typeConverters.ViewColumn.from(viewColumn), preserveFocus);
        // 	return;
        // }
      };
      this.f = Object.freeze(obj);
    }
    return this.f;
  }
  $acceptEditorTabModel(tabGroups) {
    const groupIdsBefore = new Set(this.e.map((group) => group.groupId));
    const groupIdsAfter = new Set(tabGroups.map((dto) => dto.groupId));
    const diff2 = $b(groupIdsBefore, groupIdsAfter);
    const closed = this.e.filter((group) => diff2.removed.includes(group.groupId)).map((group) => group.apiObject);
    const opened = [];
    const changed = [];
    this.e = tabGroups.map((tabGroup) => {
      const group = new ExtHostEditorTabGroup(tabGroup, () => this.d);
      if (diff2.added.includes(group.groupId)) {
        opened.push(group.apiObject);
      } else {
        changed.push(group.apiObject);
      }
      return group;
    });
    const activeTabGroupId = $Kg(tabGroups.find((group) => group.isActive === true)?.groupId);
    if (activeTabGroupId !== void 0 && this.d !== activeTabGroupId) {
      this.d = activeTabGroupId;
    }
    this.c.fire(Object.freeze({ opened, closed, changed }));
  }
  $acceptTabGroupUpdate(groupDto) {
    const group = this.e.find((group2) => group2.groupId === groupDto.groupId);
    if (!group) {
      throw new Error("Update Group IPC call received before group creation.");
    }
    group.acceptGroupDtoUpdate(groupDto);
    if (groupDto.isActive) {
      this.d = groupDto.groupId;
    }
    this.c.fire(Object.freeze({ changed: [group.apiObject], opened: [], closed: [] }));
  }
  $acceptTabOperation(operation) {
    const group = this.e.find((group2) => group2.groupId === operation.groupId);
    if (!group) {
      throw new Error("Update Tabs IPC call received before group creation.");
    }
    const tab = group.acceptTabOperation(operation);
    switch (operation.kind) {
      case 0:
        this.b.fire(Object.freeze({
          opened: [tab.apiObject],
          closed: [],
          changed: []
        }));
        return;
      case 1:
        this.b.fire(Object.freeze({
          opened: [],
          closed: [tab.apiObject],
          changed: []
        }));
        return;
      case 3:
      case 2:
        this.b.fire(Object.freeze({
          opened: [],
          closed: [],
          changed: [tab.apiObject]
        }));
        return;
    }
  }
  g(apiTab) {
    for (const group of this.e) {
      for (const tab of group.tabs) {
        if (tab.apiObject === apiTab) {
          return tab;
        }
      }
    }
    return;
  }
  h(apiTabGroup) {
    return this.e.find((candidate) => candidate.apiObject === apiTabGroup);
  }
  async i(tabs, preserveFocus) {
    const extHostTabIds = [];
    for (const tab of tabs) {
      const extHostTab = this.g(tab);
      if (!extHostTab) {
        throw new Error("Tab close: Invalid tab not found!");
      }
      extHostTabIds.push(extHostTab.tabId);
    }
    return this.a.$closeTab(extHostTabIds, preserveFocus);
  }
  async j(groups, preserverFoucs) {
    const extHostGroupIds = [];
    for (const group of groups) {
      const extHostGroup = this.h(group);
      if (!extHostGroup) {
        throw new Error("Group close: Invalid group not found!");
      }
      extHostGroupIds.push(extHostGroup.groupId);
    }
    return this.a.$closeGroup(extHostGroupIds, preserverFoucs);
  }
};
$nxc = __decorate([
  __param(0, $gW)
], $nxc);
function isTabGroup(obj) {
  const tabGroup = obj;
  if (tabGroup.tabs !== void 0) {
    return true;
  }
  return false;
}

// out-build/vs/workbench/api/common/extHostTesting.js
var followupCounter = 0;
var testResultInternalIDs = /* @__PURE__ */ new WeakMap();
var $Oxc = $Qk("IExtHostTesting");
var $Pxc = class $Pxc2 extends $3c {
  constructor(rpc, C, D, F) {
    super();
    this.C = C;
    this.D = D;
    this.F = F;
    this.f = this.B(new $ze());
    this.g = /* @__PURE__ */ new Map();
    this.w = this.B(new $ze());
    this.y = /* @__PURE__ */ new Set();
    this.z = /* @__PURE__ */ new Map();
    this.onResultsChanged = this.f.event;
    this.results = [];
    this.h = rpc.getProxy($xT.MainThreadTesting);
    this.m = new TestObservers(this.h);
    this.j = new $Qxc(this.h, C);
    D.registerArgumentProcessor({
      processArgument: (arg) => {
        switch (arg?.$mid) {
          case 16: {
            const cast = arg;
            const targetTest = cast.tests[cast.tests.length - 1].item.extId;
            const controller = this.g.get($mQ.root(targetTest));
            return controller?.collection.tree.get(targetTest)?.actual ?? $sW(arg);
          }
          case 18: {
            const { test, message } = arg;
            const extId = test.item.extId;
            return {
              test: this.g.get($mQ.root(extId))?.collection.tree.get(extId)?.actual ?? $sW({ $mid: 16, tests: [test] }),
              message: TestMessage.to(message)
            };
          }
          default:
            return arg;
        }
      }
    });
    D.registerCommand(false, "testing.getExplorerSelection", async () => {
      const inner = await D.executeCommand(
        "_testing.getExplorerSelection"
        /* TestCommandId.GetExplorerSelection */
      );
      const lookup = (i) => {
        const controller = this.g.get($mQ.root(i));
        if (!controller) {
          return void 0;
        }
        return $mQ.isRoot(i) ? controller.controller : controller.collection.tree.get(i)?.actual;
      };
      return {
        include: inner?.include.map(lookup).filter($Hg) || [],
        exclude: inner?.exclude.map(lookup).filter($Hg) || []
      };
    });
  }
  //#region public API
  /**
   * Implements vscode.test.registerTestProvider
   */
  createTestController(extension, controllerId, label, refreshHandler) {
    if (this.g.has(controllerId)) {
      throw new Error(`Attempt to insert a duplicate controller with ID "${controllerId}"`);
    }
    const disposable = new $2c();
    const collection = disposable.add(new $vW(controllerId, label, this.F));
    collection.root.label = label;
    const profiles = /* @__PURE__ */ new Map();
    const activeProfiles = /* @__PURE__ */ new Set();
    const proxy = this.h;
    const getCapability = () => {
      let cap = 0;
      if (refreshHandler) {
        cap |= 2;
      }
      const rcp = info.relatedCodeProvider;
      if (rcp) {
        if (rcp?.provideRelatedTests) {
          cap |= 8;
        }
        if (rcp?.provideRelatedCode) {
          cap |= 4;
        }
      }
      return cap;
    };
    const controller = {
      items: collection.root.children,
      get label() {
        return label;
      },
      set label(value) {
        label = value;
        collection.root.label = value;
        proxy.$updateController(controllerId, { label });
      },
      get refreshHandler() {
        return refreshHandler;
      },
      set refreshHandler(value) {
        refreshHandler = value;
        proxy.$updateController(controllerId, { capabilities: getCapability() });
      },
      get id() {
        return controllerId;
      },
      get relatedCodeProvider() {
        return info.relatedCodeProvider;
      },
      set relatedCodeProvider(value) {
        $AN(extension, "testRelatedCode");
        info.relatedCodeProvider = value;
        proxy.$updateController(controllerId, { capabilities: getCapability() });
      },
      createRunProfile: (label2, group, runHandler, isDefault, tag2, supportsContinuousRun) => {
        let profileId = $Xi(label2);
        while (profiles.has(profileId)) {
          profileId++;
        }
        return new $Sxc(this.h, profiles, activeProfiles, this.w.event, controllerId, profileId, label2, group, runHandler, isDefault, tag2, supportsContinuousRun);
      },
      createTestItem(id2, label2, uri) {
        return new $tW(controllerId, id2, label2, uri);
      },
      createTestRun: (request, name, persist = true) => {
        return this.j.createTestRun(extension, controllerId, collection, request, name, persist);
      },
      invalidateTestResults: (items) => {
        if (items === void 0) {
          this.h.$markTestRetired(void 0);
        } else {
          const itemsArr = items instanceof Array ? items : [items];
          this.h.$markTestRetired(itemsArr.map((i) => $mQ.fromExtHostTestItem(i, controllerId).toString()));
        }
      },
      set resolveHandler(fn) {
        collection.resolveHandler = fn;
      },
      get resolveHandler() {
        return collection.resolveHandler;
      },
      dispose: () => {
        disposable.dispose();
      }
    };
    const info = { controller, collection, profiles, extension, activeProfiles };
    proxy.$registerTestController(controllerId, label, getCapability());
    disposable.add($1c(() => proxy.$unregisterTestController(controllerId)));
    this.g.set(controllerId, info);
    disposable.add($1c(() => this.g.delete(controllerId)));
    disposable.add(collection.onDidGenerateDiff((diff2) => proxy.$publishDiff(controllerId, diff2.map(TestsDiffOp.serialize))));
    return controller;
  }
  /**
   * Implements vscode.test.createTestObserver
   */
  createTestObserver() {
    return this.m.checkout();
  }
  /**
   * Implements vscode.test.runTests
   */
  async runTests(req, token = CancellationToken.None) {
    const profile = tryGetProfileFromTestRunReq(req);
    if (!profile) {
      throw new Error("The request passed to `vscode.test.runTests` must include a profile");
    }
    const controller = this.g.get(profile.controllerId);
    if (!controller) {
      throw new Error("Controller not found");
    }
    await this.h.$runTests({
      preserveFocus: req.preserveFocus ?? true,
      group: TestRunProfileKind2.from(profile.kind),
      targets: [{
        testIds: req.include?.map((t) => $mQ.fromExtHostTestItem(t, controller.collection.root.id).toString()) ?? [controller.collection.root.id],
        profileId: profile.profileId,
        controllerId: profile.controllerId
      }],
      exclude: req.exclude?.map((t) => t.id)
    }, token);
  }
  /**
   * Implements vscode.test.registerTestFollowupProvider
   */
  registerTestFollowupProvider(provider) {
    this.y.add(provider);
    return { dispose: () => {
      this.y.delete(provider);
    } };
  }
  //#endregion
  //#region RPC methods
  /**
   * @inheritdoc
   */
  async $getTestsRelatedToCode(uri, _position, token) {
    const doc = this.F.getDocument(URI.revive(uri));
    if (!doc) {
      return [];
    }
    const position = Position.to(_position);
    const related = [];
    await Promise.all([...this.g.values()].map(async (c) => {
      let tests;
      try {
        tests = await c.relatedCodeProvider?.provideRelatedTests?.(doc.document, position, token);
      } catch (e) {
        if (!token.isCancellationRequested) {
          this.C.warn(`Error thrown while providing related tests for ${c.controller.label}`, e);
        }
      }
      if (tests) {
        for (const test of tests) {
          related.push($mQ.fromExtHostTestItem(test, c.controller.id).toString());
        }
        c.collection.flushDiff();
      }
    }));
    return related;
  }
  /**
   * @inheritdoc
   */
  async $getCodeRelatedToTest(testId, token) {
    const controller = this.g.get($mQ.root(testId));
    if (!controller) {
      return [];
    }
    const test = controller.collection.tree.get(testId);
    if (!test) {
      return [];
    }
    const locations = await controller.relatedCodeProvider?.provideRelatedCode?.(test.actual, token);
    return locations?.map(location.from) ?? [];
  }
  /**
   * @inheritdoc
   */
  $syncTests() {
    for (const { collection } of this.g.values()) {
      collection.flushDiff();
    }
    return Promise.resolve();
  }
  /**
   * @inheritdoc
   */
  async $getCoverageDetails(coverageId, testId, token) {
    const details = await this.j.getCoverageDetails(coverageId, testId, token);
    return details?.map(TestCoverage.fromDetails);
  }
  /**
   * @inheritdoc
   */
  async $disposeRun(runId) {
    this.j.disposeTestRun(runId);
  }
  /** @inheritdoc */
  $configureRunProfile(controllerId, profileId) {
    this.g.get(controllerId)?.profiles.get(profileId)?.configureHandler?.();
  }
  /** @inheritdoc */
  $setDefaultRunProfiles(profiles) {
    const evt = /* @__PURE__ */ new Map();
    for (const [controllerId, profileIds] of Object.entries(profiles)) {
      const ctrl = this.g.get(controllerId);
      if (!ctrl) {
        continue;
      }
      const changes = /* @__PURE__ */ new Map();
      const added = profileIds.filter((id2) => !ctrl.activeProfiles.has(id2));
      const removed = [...ctrl.activeProfiles].filter((id2) => !profileIds.includes(id2));
      for (const id2 of added) {
        changes.set(id2, true);
        ctrl.activeProfiles.add(id2);
      }
      for (const id2 of removed) {
        changes.set(id2, false);
        ctrl.activeProfiles.delete(id2);
      }
      if (changes.size) {
        evt.set(controllerId, changes);
      }
    }
    this.w.fire(evt);
  }
  /** @inheritdoc */
  async $refreshTests(controllerId, token) {
    await this.g.get(controllerId)?.controller.refreshHandler?.(token);
  }
  /**
   * Updates test results shown to extensions.
   * @override
   */
  $publishTestResults(results) {
    this.results = Object.freeze(results.map((r) => {
      const o = TestResults.to(r);
      const taskWithCoverage = r.tasks.findIndex((t) => t.hasCoverage);
      if (taskWithCoverage !== -1) {
        o.getDetailedCoverage = (uri, token = CancellationToken.None) => this.h.$getCoverageDetails(r.id, taskWithCoverage, uri, token).then((r2) => r2.map(TestCoverage.to));
      }
      testResultInternalIDs.set(o, r.id);
      return o;
    }).concat(this.results).sort((a, b) => b.completedAt - a.completedAt).slice(0, 32));
    this.f.fire();
  }
  /**
   * Expands the nodes in the test tree. If levels is less than zero, it will
   * be treated as infinite.
   */
  async $expandTest(testId, levels) {
    const collection = this.g.get($mQ.fromString(testId).controllerId)?.collection;
    if (collection) {
      await collection.expand(testId, levels < 0 ? Infinity : levels);
      collection.flushDiff();
    }
  }
  /**
   * Receives a test update from the main thread. Called (eventually) whenever
   * tests change.
   */
  $acceptDiff(diff2) {
    this.m.applyDiff(diff2.map((d) => TestsDiffOp.deserialize({ asCanonicalUri: (u) => u }, d)));
  }
  /**
   * Runs tests with the given set of IDs. Allows for test from multiple
   * providers to be run.
   * @inheritdoc
   */
  async $runControllerTests(reqs, token) {
    return Promise.all(reqs.map((req) => this.G(req, false, token)));
  }
  /**
   * Starts continuous test runs with the given set of IDs. Allows for test from
   * multiple providers to be run.
   * @inheritdoc
   */
  async $startContinuousRun(reqs, token) {
    const cts = new $ad(token);
    const res = await Promise.all(reqs.map((req) => this.G(req, true, cts.token)));
    if (!token.isCancellationRequested && !res.some((r) => r.error)) {
      await new Promise((r) => token.onCancellationRequested(r));
    }
    cts.dispose(true);
    return res;
  }
  /** @inheritdoc */
  async $provideTestFollowups(req, token) {
    const results = this.results.find((r) => testResultInternalIDs.get(r) === req.resultId);
    const test = results && findTestInResultSnapshot($mQ.fromString(req.extId), results?.results);
    if (!test) {
      return [];
    }
    let followups = [];
    await Promise.all([...this.y].map(async (provider) => {
      try {
        const r = await provider.provideFollowup(results, test, req.taskIndex, req.messageIndex, token);
        if (r) {
          followups = followups.concat(r);
        }
      } catch (e) {
        this.C.error(`Error thrown while providing followup for test message`, e);
      }
    }));
    if (token.isCancellationRequested) {
      return [];
    }
    return followups.map((command) => {
      const id2 = followupCounter++;
      this.z.set(id2, command);
      return { title: command.title, id: id2 };
    });
  }
  $disposeTestFollowups(id2) {
    for (const i of id2) {
      this.z.delete(i);
    }
  }
  $executeTestFollowup(id2) {
    const command = this.z.get(id2);
    if (!command) {
      return Promise.resolve();
    }
    return this.D.executeCommand(command.command, ...command.arguments || []);
  }
  /**
   * Cancels an ongoing test run.
   */
  $cancelExtensionTestRun(runId, taskId) {
    if (runId === void 0) {
      this.j.cancelAllRuns();
    } else {
      this.j.cancelRunById(runId, taskId);
    }
  }
  //#endregion
  getMetadataForRun(run) {
    for (const tracker of this.j.trackers) {
      const taskId = tracker.getTaskIdForRun(run);
      if (taskId) {
        return { taskId, runId: tracker.id };
      }
    }
    return void 0;
  }
  async G(req, isContinuous, token) {
    const lookup = this.g.get(req.controllerId);
    if (!lookup) {
      return {};
    }
    const { collection, profiles, extension } = lookup;
    const profile = profiles.get(req.profileId);
    if (!profile) {
      return {};
    }
    const includeTests = req.testIds.map((testId) => collection.tree.get(testId)).filter($Hg);
    const excludeTests = req.excludeExtIds.map((id2) => lookup.collection.tree.get(id2)).filter($Hg).filter((exclude) => includeTests.some(
      (include) => include.fullId.compare(exclude.fullId) === 2
      /* TestPosition.IsChild */
    ));
    if (!includeTests.length) {
      return {};
    }
    const publicReq = new $gV(includeTests.some((i) => i.actual instanceof $uW) ? void 0 : includeTests.map((t) => t.actual), excludeTests.map((t) => t.actual), profile, isContinuous);
    const tracker = $qQ(req) && this.j.prepareForMainThreadTestRun(extension, publicReq, $Rxc.fromInternal(req, lookup.collection), profile, token);
    try {
      await profile.runHandler(publicReq, token);
      return {};
    } catch (e) {
      return { error: String(e) };
    } finally {
      if (tracker) {
        if (tracker.hasRunningTasks && !token.isCancellationRequested) {
          await Event.toPromise(tracker.onEnd);
        }
      }
    }
  }
};
$Pxc = __decorate([
  __param(0, $gW),
  __param(1, $wn),
  __param(2, $CW),
  __param(3, $rW)
], $Pxc);
var RUN_CANCEL_DEADLINE = 1e4;
var TestRunTrackerState;
(function(TestRunTrackerState2) {
  TestRunTrackerState2[TestRunTrackerState2["Running"] = 0] = "Running";
  TestRunTrackerState2[TestRunTrackerState2["Cancelling"] = 1] = "Cancelling";
  TestRunTrackerState2[TestRunTrackerState2["Ended"] = 2] = "Ended";
})(TestRunTrackerState || (TestRunTrackerState = {}));
var TestRunTracker = class extends $3c {
  /**
   * Gets whether there are any tests running.
   */
  get hasRunningTasks() {
    return this.g > 0;
  }
  /**
   * Gets the run ID.
   */
  get id() {
    return this.C.id;
  }
  constructor(C, D, F, G, H, parentToken) {
    super();
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.f = 0;
    this.g = 0;
    this.h = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Set();
    this.w = this.B(new $ze());
    this.z = /* @__PURE__ */ new Map();
    this.onEnd = this.w.event;
    this.m = this.B(new $ad(parentToken));
    const forciblyEnd = this.B(new $8h(() => this.I(), RUN_CANCEL_DEADLINE));
    this.B(this.m.token.onCancellationRequested(() => forciblyEnd.schedule()));
    const didDisposeEmitter = new $ze();
    this.y = didDisposeEmitter.event;
    this.B($1c(() => {
      didDisposeEmitter.fire();
      didDisposeEmitter.dispose();
    }));
  }
  /** Gets the task ID from a test run object. */
  getTaskIdForRun(run) {
    for (const [taskId, { run: r }] of this.h) {
      if (r === run) {
        return taskId;
      }
    }
    return void 0;
  }
  /** Requests cancellation of the run. On the second call, forces cancellation. */
  cancel(taskId) {
    if (taskId) {
      this.h.get(taskId)?.cts.cancel();
    } else if (this.f === 0) {
      this.m.cancel();
      this.f = 1;
    } else if (this.f === 1) {
      this.I();
    }
  }
  /** Gets details for a previously-emitted coverage object. */
  async getCoverageDetails(id2, testId, token) {
    const [, taskId] = $mQ.fromString(id2).path;
    const coverage = this.z.get(id2);
    if (!coverage) {
      return [];
    }
    const { report, extIds } = coverage;
    const task = this.h.get(taskId);
    if (!task) {
      throw new Error("unreachable: run task was not found");
    }
    let testItem;
    if (testId && report instanceof $mV) {
      const index = extIds.indexOf(testId);
      if (index === -1) {
        return [];
      }
      testItem = report.includesTests[index];
    }
    const details = testItem ? this.G?.loadDetailedCoverageForTest?.(task.run, report, testItem, token) : this.G?.loadDetailedCoverage?.(task.run, report, token);
    return await details ?? [];
  }
  /** Creates the public test run interface to give to extensions. */
  createRun(name) {
    const runId = this.C.id;
    const ctrlId = this.C.controllerId;
    const taskId = $ps();
    const guardTestMutation = (fn) => (test, ...args2) => {
      if (ended) {
        this.F.warn(`Setting the state of test "${test.id}" is a no-op after the run ends.`);
        return;
      }
      this.L(test);
      fn(test, ...args2);
    };
    const appendMessages = (test, messages) => {
      const converted = messages instanceof Array ? messages.map(TestMessage.from) : [TestMessage.from(messages)];
      if (test.uri && test.range) {
        const defaultLocation = { range: Range.from(test.range), uri: test.uri };
        for (const message of converted) {
          message.location = message.location || defaultLocation;
        }
      }
      this.D.$appendTestMessagesInRun(runId, taskId, $mQ.fromExtHostTestItem(test, ctrlId).toString(), converted);
    };
    let ended = false;
    const cts = this.B(new $ad(this.m.token));
    const run = {
      isPersisted: this.C.isPersisted,
      token: cts.token,
      name,
      onDidDispose: this.y,
      addCoverage: (coverage) => {
        if (ended) {
          return;
        }
        const includesTests = coverage instanceof $mV ? coverage.includesTests : [];
        if (includesTests.length) {
          for (const test of includesTests) {
            this.L(test);
          }
        }
        const uriStr = coverage.uri.toString();
        const id2 = new $mQ([runId, taskId, uriStr]).toString();
        this.z.set(id2, { report: coverage, extIds: includesTests.map((t) => $mQ.fromExtHostTestItem(t, ctrlId).toString()) });
        this.D.$appendCoverage(runId, taskId, TestCoverage.fromFile(ctrlId, id2, coverage));
      },
      //#region state mutation
      enqueued: guardTestMutation((test) => {
        this.D.$updateTestStateInRun(
          runId,
          taskId,
          $mQ.fromExtHostTestItem(test, ctrlId).toString(),
          1
          /* TestResultState.Queued */
        );
      }),
      skipped: guardTestMutation((test) => {
        this.D.$updateTestStateInRun(
          runId,
          taskId,
          $mQ.fromExtHostTestItem(test, ctrlId).toString(),
          5
          /* TestResultState.Skipped */
        );
      }),
      started: guardTestMutation((test) => {
        this.D.$updateTestStateInRun(
          runId,
          taskId,
          $mQ.fromExtHostTestItem(test, ctrlId).toString(),
          2
          /* TestResultState.Running */
        );
      }),
      errored: guardTestMutation((test, messages, duration) => {
        appendMessages(test, messages);
        this.D.$updateTestStateInRun(runId, taskId, $mQ.fromExtHostTestItem(test, ctrlId).toString(), 6, duration);
      }),
      failed: guardTestMutation((test, messages, duration) => {
        appendMessages(test, messages);
        this.D.$updateTestStateInRun(runId, taskId, $mQ.fromExtHostTestItem(test, ctrlId).toString(), 4, duration);
      }),
      passed: guardTestMutation((test, duration) => {
        this.D.$updateTestStateInRun(runId, taskId, $mQ.fromExtHostTestItem(test, this.C.controllerId).toString(), 3, duration);
      }),
      //#endregion
      appendOutput: (output, location2, test) => {
        if (ended) {
          return;
        }
        if (test) {
          this.L(test);
        }
        this.D.$appendOutputToRun(runId, taskId, $Ci.fromString(output), location2 && location.from(location2), test && $mQ.fromExtHostTestItem(test, ctrlId).toString());
      },
      end: () => {
        if (ended) {
          return;
        }
        ended = true;
        this.D.$finishedTestRunTask(runId, taskId);
        if (!--this.g) {
          this.J();
        }
      }
    };
    this.g++;
    this.h.set(taskId, { run, cts });
    this.D.$startedTestRunTask(runId, {
      id: taskId,
      ctrlId: this.C.controllerId,
      name: name || this.H.displayName || this.H.identifier.value,
      running: true
    });
    return run;
  }
  I() {
    for (const { run } of this.h.values()) {
      run.end();
    }
  }
  J() {
    if (this.f !== 2) {
      this.f = 2;
      this.w.fire();
    }
  }
  L(test) {
    if (!(test instanceof $tW)) {
      throw new $$V(test.id);
    }
    if (this.j.has($mQ.fromExtHostTestItem(test, this.C.controllerId).toString())) {
      return;
    }
    const chain = [];
    const root = this.C.colllection.root;
    while (true) {
      const converted = TestItem.from(test);
      chain.unshift(converted);
      if (this.j.has(converted.extId)) {
        break;
      }
      this.j.add(converted.extId);
      if (test === root) {
        break;
      }
      test = test.parent || root;
    }
    this.D.$addTestsToRun(this.C.controllerId, this.C.id, chain);
  }
  dispose() {
    this.J();
    super.dispose();
  }
};
var $Qxc = class {
  get trackers() {
    return this.f.values();
  }
  constructor(h, j) {
    this.h = h;
    this.j = j;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
  }
  /**
   * Gets a coverage report for a given run and task ID.
   */
  getCoverageDetails(id2, testId, token) {
    const runId = $mQ.root(id2);
    return this.g.get(runId)?.getCoverageDetails(id2, testId, token) || [];
  }
  /**
   * Disposes the test run, called when the main thread is no longer interested
   * in associated data.
   */
  disposeTestRun(runId) {
    this.g.get(runId)?.dispose();
    this.g.delete(runId);
    for (const [req, { id: id2 }] of this.f) {
      if (id2 === runId) {
        this.f.delete(req);
      }
    }
  }
  /**
   * Registers a request as being invoked by the main thread, so
   * `$startedExtensionTestRun` is not invoked. The run must eventually
   * be cancelled manually.
   */
  prepareForMainThreadTestRun(extension, req, dto, profile, token) {
    return this.k(req, dto, profile, extension, token);
  }
  /**
   * Cancels an existing test run via its cancellation token.
   */
  cancelRunById(runId, taskId) {
    this.g.get(runId)?.cancel(taskId);
  }
  /**
   * Cancels an existing test run via its cancellation token.
   */
  cancelAllRuns() {
    for (const tracker of this.f.values()) {
      tracker.cancel();
    }
  }
  /**
   * Implements the public `createTestRun` API.
   */
  createTestRun(extension, controllerId, collection, request, name, persist) {
    const existing = this.f.get(request);
    if (existing) {
      return existing.createRun(name);
    }
    const dto = $Rxc.fromPublic(controllerId, collection, request, persist);
    const profile = tryGetProfileFromTestRunReq(request);
    this.h.$startedExtensionTestRun({
      controllerId,
      continuous: !!request.continuous,
      profile: profile && { group: TestRunProfileKind2.from(profile.kind), id: profile.profileId },
      exclude: request.exclude?.map((t) => $mQ.fromExtHostTestItem(t, collection.root.id).toString()) ?? [],
      id: dto.id,
      include: request.include?.map((t) => $mQ.fromExtHostTestItem(t, collection.root.id).toString()) ?? [collection.root.id],
      preserveFocus: request.preserveFocus ?? true,
      persist
    });
    const tracker = this.k(request, dto, request.profile, extension);
    Event.once(tracker.onEnd)(() => {
      this.h.$finishedExtensionTestRun(dto.id);
    });
    return tracker.createRun(name);
  }
  k(req, dto, profile, extension, token) {
    const tracker = new TestRunTracker(dto, this.h, this.j, profile, extension, token);
    this.f.set(req, tracker);
    this.g.set(tracker.id, tracker);
    return tracker;
  }
};
var tryGetProfileFromTestRunReq = (request) => {
  if (!request.profile) {
    return void 0;
  }
  if (!(request.profile instanceof $Sxc)) {
    throw new Error(`TestRunRequest.profile is not an instance created from TestController.createRunProfile`);
  }
  return request.profile;
};
var $Rxc = class _$Rxc {
  static fromPublic(controllerId, collection, request, persist) {
    return new _$Rxc(controllerId, $ps(), persist, collection);
  }
  static fromInternal(request, collection) {
    return new _$Rxc(request.controllerId, request.runId, true, collection);
  }
  constructor(controllerId, id2, isPersisted, colllection) {
    this.controllerId = controllerId;
    this.id = id2;
    this.isPersisted = isPersisted;
    this.colllection = colllection;
  }
};
var MirroredChangeCollector = class {
  get isEmpty() {
    return this.f.size === 0 && this.h.size === 0 && this.g.size === 0;
  }
  constructor(k) {
    this.k = k;
    this.f = /* @__PURE__ */ new Set();
    this.g = /* @__PURE__ */ new Set();
    this.h = /* @__PURE__ */ new Set();
    this.j = /* @__PURE__ */ new Set();
  }
  /**
   * @inheritdoc
   */
  add(node) {
    this.f.add(node);
  }
  /**
   * @inheritdoc
   */
  update(node) {
    Object.assign(node.revived, TestItem.toPlain(node.item));
    if (!this.f.has(node)) {
      this.g.add(node);
    }
  }
  /**
   * @inheritdoc
   */
  remove(node) {
    if (this.f.has(node)) {
      this.f.delete(node);
      return;
    }
    this.g.delete(node);
    const parentId = $mQ.parentId(node.item.extId);
    if (parentId && this.j.has(parentId.toString())) {
      this.j.add(node.item.extId);
      return;
    }
    this.h.add(node);
  }
  /**
   * @inheritdoc
   */
  getChangeEvent() {
    const { f: added, g: updated, h: removed } = this;
    return {
      get added() {
        return [...added].map((n) => n.revived);
      },
      get updated() {
        return [...updated].map((n) => n.revived);
      },
      get removed() {
        return [...removed].map((n) => n.revived);
      }
    };
  }
  complete() {
    if (!this.isEmpty) {
      this.k.fire(this.getChangeEvent());
    }
  }
};
var MirroredTestCollection = class extends $wQ {
  constructor() {
    super(...arguments);
    this.z = new $ze();
    this.onDidChangeTests = this.z.event;
  }
  /**
   * Gets a list of root test items.
   */
  get rootTests() {
    return this.h;
  }
  /**
   *
   * If the test ID exists, returns its underlying ID.
   */
  getMirroredTestDataById(itemId) {
    return this.g.get(itemId);
  }
  /**
   * If the test item is a mirrored test item, returns its underlying ID.
   */
  getMirroredTestDataByReference(item) {
    return this.g.get(item.id);
  }
  /**
   * @override
   */
  y(item, parent) {
    return {
      ...item,
      // todo@connor4312: make this work well again with children
      revived: TestItem.toPlain(item.item),
      depth: parent ? parent.depth + 1 : 0,
      children: /* @__PURE__ */ new Set()
    };
  }
  /**
   * @override
   */
  x() {
    return new MirroredChangeCollector(this.z);
  }
};
var TestObservers = class {
  constructor(g) {
    this.g = g;
  }
  checkout() {
    if (!this.f) {
      this.f = this.h();
    }
    const current = this.f;
    current.observers++;
    return {
      onDidChangeTest: current.tests.onDidChangeTests,
      get tests() {
        return [...current.tests.rootTests].map((t) => t.revived);
      },
      dispose: $Qc(() => {
        if (--current.observers === 0) {
          this.g.$unsubscribeFromDiffs();
          this.f = void 0;
        }
      })
    };
  }
  /**
   * Gets the internal test data by its reference.
   */
  getMirroredTestDataByReference(ref) {
    return this.f?.tests.getMirroredTestDataByReference(ref);
  }
  /**
   * Applies test diffs to the current set of observed tests.
   */
  applyDiff(diff2) {
    this.f?.tests.apply(diff2);
  }
  h() {
    const tests = new MirroredTestCollection({ asCanonicalUri: (u) => u });
    this.g.$subscribeToDiffs();
    return { observers: 0, tests };
  }
};
var updateProfile = (impl, proxy, initial, update) => {
  if (initial) {
    Object.assign(initial, update);
  } else {
    proxy.$updateTestRunConfig(impl.controllerId, impl.profileId, update);
  }
};
var $Sxc = class extends $fV {
  #proxy;
  #activeProfiles;
  #onDidChangeDefaultProfiles;
  #initialPublish;
  #profiles;
  get label() {
    return this.g;
  }
  set label(label) {
    if (label !== this.g) {
      this.g = label;
      updateProfile(this, this.#proxy, this.#initialPublish, { label });
    }
  }
  get supportsContinuousRun() {
    return this.j;
  }
  set supportsContinuousRun(supports) {
    if (supports !== this.j) {
      this.j = supports;
      updateProfile(this, this.#proxy, this.#initialPublish, { supportsContinuousRun: supports });
    }
  }
  get isDefault() {
    return this.#activeProfiles.has(this.profileId);
  }
  set isDefault(isDefault) {
    if (isDefault !== this.isDefault) {
      if (isDefault) {
        this.#activeProfiles.add(this.profileId);
      } else {
        this.#activeProfiles.delete(this.profileId);
      }
      updateProfile(this, this.#proxy, this.#initialPublish, { isDefault });
    }
  }
  get tag() {
    return this._tag;
  }
  set tag(tag2) {
    if (tag2?.id !== this._tag?.id) {
      this._tag = tag2;
      updateProfile(this, this.#proxy, this.#initialPublish, {
        tag: tag2 ? TestTag.namespace(this.controllerId, tag2.id) : null
      });
    }
  }
  get configureHandler() {
    return this.f;
  }
  set configureHandler(handler) {
    if (handler !== this.f) {
      this.f = handler;
      updateProfile(this, this.#proxy, this.#initialPublish, { hasConfigurationHandler: !!handler });
    }
  }
  get onDidChangeDefault() {
    return Event.chain(this.#onDidChangeDefaultProfiles, ($) => $.map((ev) => ev.get(this.controllerId)?.get(this.profileId)).filter($Hg));
  }
  constructor(proxy, profiles, activeProfiles, onDidChangeActiveProfiles, controllerId, profileId, g, kind, runHandler, _isDefault = false, _tag2 = void 0, j = false) {
    super(controllerId, profileId, kind);
    this.g = g;
    this.runHandler = runHandler;
    this._tag = _tag2;
    this.j = j;
    this.#proxy = proxy;
    this.#profiles = profiles;
    this.#activeProfiles = activeProfiles;
    this.#onDidChangeDefaultProfiles = onDidChangeActiveProfiles;
    profiles.set(profileId, this);
    const groupBitset = TestRunProfileKind2.from(kind);
    if (_isDefault) {
      activeProfiles.add(profileId);
    }
    this.#initialPublish = {
      profileId,
      controllerId,
      tag: _tag2 ? TestTag.namespace(this.controllerId, _tag2.id) : null,
      label: g,
      group: groupBitset,
      isDefault: _isDefault,
      hasConfigurationHandler: false,
      supportsContinuousRun: j
    };
    queueMicrotask(() => {
      if (this.#initialPublish) {
        this.#proxy.$publishTestRunProfile(this.#initialPublish);
        this.#initialPublish = void 0;
      }
    });
  }
  dispose() {
    if (this.#profiles?.delete(this.profileId)) {
      this.#profiles = void 0;
      this.#proxy.$removeTestProfile(this.controllerId, this.profileId);
    }
    this.#initialPublish = void 0;
  }
};
function findTestInResultSnapshot(extId, snapshot) {
  for (let i = 0; i < extId.path.length; i++) {
    const item = snapshot.find((s) => s.id === extId.path[i]);
    if (!item) {
      return void 0;
    }
    if (i === extId.path.length - 1) {
      return item;
    }
    snapshot = item.children;
  }
  return void 0;
}

// out-build/vs/workbench/services/configurationResolver/common/configurationResolver.js
var $nY = $Qk("configurationResolverService");
var VariableKind;
(function(VariableKind2) {
  VariableKind2["Unknown"] = "unknown";
  VariableKind2["Env"] = "env";
  VariableKind2["Config"] = "config";
  VariableKind2["Command"] = "command";
  VariableKind2["Input"] = "input";
  VariableKind2["ExtensionInstallFolder"] = "extensionInstallFolder";
  VariableKind2["WorkspaceFolder"] = "workspaceFolder";
  VariableKind2["Cwd"] = "cwd";
  VariableKind2["WorkspaceFolderBasename"] = "workspaceFolderBasename";
  VariableKind2["UserHome"] = "userHome";
  VariableKind2["LineNumber"] = "lineNumber";
  VariableKind2["SelectedText"] = "selectedText";
  VariableKind2["File"] = "file";
  VariableKind2["FileWorkspaceFolder"] = "fileWorkspaceFolder";
  VariableKind2["FileWorkspaceFolderBasename"] = "fileWorkspaceFolderBasename";
  VariableKind2["RelativeFile"] = "relativeFile";
  VariableKind2["RelativeFileDirname"] = "relativeFileDirname";
  VariableKind2["FileDirname"] = "fileDirname";
  VariableKind2["FileExtname"] = "fileExtname";
  VariableKind2["FileBasename"] = "fileBasename";
  VariableKind2["FileBasenameNoExtension"] = "fileBasenameNoExtension";
  VariableKind2["FileDirnameBasename"] = "fileDirnameBasename";
  VariableKind2["ExecPath"] = "execPath";
  VariableKind2["ExecInstallFolder"] = "execInstallFolder";
  VariableKind2["PathSeparator"] = "pathSeparator";
  VariableKind2["PathSeparatorAlias"] = "/";
})(VariableKind || (VariableKind = {}));
var $oY = class extends $ub {
  constructor(variable, message) {
    super(message);
    this.variable = variable;
  }
};

// out-build/vs/workbench/services/configurationResolver/common/variableResolver.js
var $DY = class _$DY {
  static {
    this.VARIABLE_LHS = "${";
  }
  static {
    this.VARIABLE_REGEXP = /\$\{(.*?)\}/g;
  }
  constructor(_context, _labelService, _userHomePromise, _envVariablesPromise) {
    this.h = /* @__PURE__ */ new Map();
    this.a = _context;
    this.b = _labelService;
    this.g = _userHomePromise;
    if (_envVariablesPromise) {
      this.c = _envVariablesPromise.then((envVariables) => {
        return this.i(envVariables);
      });
    }
  }
  i(envVariables) {
    if ($l) {
      const ev = /* @__PURE__ */ Object.create(null);
      Object.keys(envVariables).forEach((key) => {
        ev[key.toLowerCase()] = envVariables[key];
      });
      return ev;
    }
    return envVariables;
  }
  resolveWithEnvironment(environment, root, value) {
    return this.l({ env: this.i(environment), userHome: void 0 }, root ? root.uri : void 0, value);
  }
  async resolveAsync(root, value) {
    const environment = {
      env: await this.c,
      userHome: await this.g
    };
    return this.l(environment, root ? root.uri : void 0, value);
  }
  async j(workspaceFolder, config, commandValueMapping, resolvedVariables) {
    const result = $Lv(config);
    if ($l && result.windows) {
      Object.keys(result.windows).forEach((key) => result[key] = result.windows[key]);
    } else if ($m && result.osx) {
      Object.keys(result.osx).forEach((key) => result[key] = result.osx[key]);
    } else if ($n && result.linux) {
      Object.keys(result.linux).forEach((key) => result[key] = result.linux[key]);
    }
    delete result.windows;
    delete result.osx;
    delete result.linux;
    const environmentPromises = {
      env: await this.c,
      userHome: await this.g
    };
    return this.l(environmentPromises, workspaceFolder ? workspaceFolder.uri : void 0, result, commandValueMapping, resolvedVariables);
  }
  async resolveAnyAsync(workspaceFolder, config, commandValueMapping) {
    return this.j(workspaceFolder, config, commandValueMapping);
  }
  async resolveAnyMap(workspaceFolder, config, commandValueMapping) {
    const resolvedVariables = /* @__PURE__ */ new Map();
    const newConfig = await this.j(workspaceFolder, config, commandValueMapping, resolvedVariables);
    return { newConfig, resolvedVariables };
  }
  resolveWithInteractionReplace(folder, config, section, variables) {
    throw new Error("resolveWithInteractionReplace not implemented.");
  }
  resolveWithInteraction(folder, config, section, variables) {
    throw new Error("resolveWithInteraction not implemented.");
  }
  contributeVariable(variable, resolution) {
    if (this.h.has(variable)) {
      throw new Error("Variable " + variable + " is contributed twice.");
    } else {
      this.h.set(variable, resolution);
    }
  }
  async l(environment, folderUri, value, commandValueMapping, resolvedVariables) {
    if ($zg(value)) {
      return this.m(environment, folderUri, value, commandValueMapping, resolvedVariables);
    } else if (Array.isArray(value)) {
      return Promise.all(value.map((s) => this.l(environment, folderUri, s, commandValueMapping, resolvedVariables)));
    } else if ($Bg(value)) {
      const result = /* @__PURE__ */ Object.create(null);
      const replaced = await Promise.all(Object.keys(value).map(async (key) => {
        const replaced2 = await this.m(environment, folderUri, key, commandValueMapping, resolvedVariables);
        return [replaced2, await this.l(environment, folderUri, value[key], commandValueMapping, resolvedVariables)];
      }));
      for (const [key, value2] of replaced) {
        result[key] = value2;
      }
      return result;
    }
    return value;
  }
  m(environment, folderUri, value, commandValueMapping, resolvedVariables) {
    return $Sf(value, _$DY.VARIABLE_REGEXP, async (match, variable) => {
      if (variable.includes(_$DY.VARIABLE_LHS)) {
        return match;
      }
      let resolvedValue = await this.o(environment, match, variable, folderUri, commandValueMapping);
      resolvedVariables?.set(variable, resolvedValue);
      if (resolvedValue !== match && $zg(resolvedValue) && resolvedValue.match(_$DY.VARIABLE_REGEXP)) {
        resolvedValue = await this.m(environment, folderUri, resolvedValue, commandValueMapping, resolvedVariables);
      }
      return resolvedValue;
    });
  }
  n(displayUri) {
    return this.b ? this.b.getUriLabel(displayUri, { noPrefix: true }) : displayUri.fsPath;
  }
  async o(environment, match, variable, folderUri, commandValueMapping) {
    let argument;
    const parts = variable.split(":");
    if (parts.length > 1) {
      variable = parts[0];
      argument = parts[1];
    }
    const getFilePath = (variableKind) => {
      const filePath = this.a.getFilePath();
      if (filePath) {
        return $1t(filePath);
      }
      throw new $oY(variableKind, localize(12635, null, match));
    };
    const getFolderPathForFile = (variableKind) => {
      const filePath = getFilePath(variableKind);
      if (this.a.getWorkspaceFolderPathForFile) {
        const folderPath = this.a.getWorkspaceFolderPathForFile();
        if (folderPath) {
          return $1t(folderPath);
        }
      }
      throw new $oY(variableKind, localize(12636, null, match, $rc(filePath)));
    };
    const getFolderUri = (variableKind) => {
      if (argument) {
        const folder = this.a.getFolderUri(argument);
        if (folder) {
          return folder;
        }
        throw new $oY(variableKind, localize(12637, null, match, argument));
      }
      if (folderUri) {
        return folderUri;
      }
      if (this.a.getWorkspaceFolderCount() > 1) {
        throw new $oY(variableKind, localize(12638, null, match));
      }
      throw new $oY(variableKind, localize(12639, null, match));
    };
    switch (variable) {
      case "env":
        if (argument) {
          if (environment.env) {
            const env2 = environment.env[$l ? argument.toLowerCase() : argument];
            if ($zg(env2)) {
              return env2;
            }
          }
          return "";
        }
        throw new $oY(VariableKind.Env, localize(12640, null, match));
      case "config":
        if (argument) {
          const config = this.a.getConfigurationValue(folderUri, argument);
          if ($Ig(config)) {
            throw new $oY(VariableKind.Config, localize(12641, null, match, argument));
          }
          if ($Bg(config)) {
            throw new $oY(VariableKind.Config, localize(12642, null, match, argument));
          }
          return config;
        }
        throw new $oY(VariableKind.Config, localize(12643, null, match));
      case "command":
        return this.p(VariableKind.Command, match, argument, commandValueMapping, "command");
      case "input":
        return this.p(VariableKind.Input, match, argument, commandValueMapping, "input");
      case "extensionInstallFolder":
        if (argument) {
          const ext = await this.a.getExtension(argument);
          if (!ext) {
            throw new $oY(VariableKind.ExtensionInstallFolder, localize(12644, null, match, argument));
          }
          return this.n(ext.extensionLocation);
        }
        throw new $oY(VariableKind.ExtensionInstallFolder, localize(12645, null, match));
      default: {
        switch (variable) {
          case "workspaceRoot":
          case "workspaceFolder":
            return $1t(this.n(getFolderUri(VariableKind.WorkspaceFolder)));
          case "cwd":
            return folderUri || argument ? $1t(this.n(getFolderUri(VariableKind.Cwd))) : cwd();
          case "workspaceRootFolderName":
          case "workspaceFolderBasename":
            return $1t($rc(this.n(getFolderUri(VariableKind.WorkspaceFolderBasename))));
          case "userHome": {
            if (environment.userHome) {
              return environment.userHome;
            }
            throw new $oY(VariableKind.UserHome, localize(12646, null, match));
          }
          case "lineNumber": {
            const lineNumber = this.a.getLineNumber();
            if (lineNumber) {
              return lineNumber;
            }
            throw new $oY(VariableKind.LineNumber, localize(12647, null, match));
          }
          case "selectedText": {
            const selectedText = this.a.getSelectedText();
            if (selectedText) {
              return selectedText;
            }
            throw new $oY(VariableKind.SelectedText, localize(12648, null, match));
          }
          case "file":
            return getFilePath(VariableKind.File);
          case "fileWorkspaceFolder":
            return getFolderPathForFile(VariableKind.FileWorkspaceFolder);
          case "fileWorkspaceFolderBasename":
            return $rc(getFolderPathForFile(VariableKind.FileWorkspaceFolderBasename));
          case "relativeFile":
            if (folderUri || argument) {
              return $pc(this.n(getFolderUri(VariableKind.RelativeFile)), getFilePath(VariableKind.RelativeFile));
            }
            return getFilePath(VariableKind.RelativeFile);
          case "relativeFileDirname": {
            const dirname = $qc(getFilePath(VariableKind.RelativeFileDirname));
            if (folderUri || argument) {
              const relative = $pc(this.n(getFolderUri(VariableKind.RelativeFileDirname)), dirname);
              return relative.length === 0 ? "." : relative;
            }
            return dirname;
          }
          case "fileDirname":
            return $qc(getFilePath(VariableKind.FileDirname));
          case "fileExtname":
            return $sc(getFilePath(VariableKind.FileExtname));
          case "fileBasename":
            return $rc(getFilePath(VariableKind.FileBasename));
          case "fileBasenameNoExtension": {
            const basename = $rc(getFilePath(VariableKind.FileBasenameNoExtension));
            return basename.slice(0, basename.length - $sc(basename).length);
          }
          case "fileDirnameBasename":
            return $rc($qc(getFilePath(VariableKind.FileDirnameBasename)));
          case "execPath": {
            const ep = this.a.getExecPath();
            if (ep) {
              return ep;
            }
            return match;
          }
          case "execInstallFolder": {
            const ar = this.a.getAppRoot();
            if (ar) {
              return ar;
            }
            return match;
          }
          case "pathSeparator":
          case "/":
            return sep;
          default:
            try {
              const key = argument ? `${variable}:${argument}` : variable;
              return this.p(VariableKind.Unknown, match, key, commandValueMapping, void 0);
            } catch (error) {
              return match;
            }
        }
      }
    }
  }
  p(variableKind, match, argument, commandValueMapping, prefix) {
    if (argument && commandValueMapping) {
      const v = prefix === void 0 ? commandValueMapping[argument] : commandValueMapping[prefix + ":" + argument];
      if (typeof v === "string") {
        return v;
      }
      throw new $oY(variableKind, localize(12649, null, match));
    }
    return match;
  }
};

// out-build/vs/workbench/api/common/extHostVariableResolverService.js
var $Txc = $Qk("IExtHostVariableResolverProvider");
var ExtHostVariableResolverService = class extends $DY {
  constructor(extensionService, workspaceService, editorService, editorTabs, configProvider, context, homeDir) {
    function getActiveUri() {
      if (editorService) {
        const activeEditor = editorService.activeEditor();
        if (activeEditor) {
          return activeEditor.document.uri;
        }
        const activeTab = editorTabs.tabGroups.all.find((group) => group.isActive)?.activeTab;
        if (activeTab !== void 0) {
          if (activeTab.input instanceof $sV || activeTab.input instanceof $xV) {
            return activeTab.input.modified;
          } else if (activeTab.input instanceof $rV || activeTab.input instanceof $wV || activeTab.input instanceof $uV) {
            return activeTab.input.uri;
          }
        }
      }
      return void 0;
    }
    super({
      getFolderUri: (folderName) => {
        const found = context.folders.filter((f) => f.name === folderName);
        if (found && found.length > 0) {
          return found[0].uri;
        }
        return void 0;
      },
      getWorkspaceFolderCount: () => {
        return context.folders.length;
      },
      getConfigurationValue: (folderUri, section) => {
        return configProvider.getConfiguration(void 0, folderUri).get(section);
      },
      getAppRoot: () => {
        return cwd();
      },
      getExecPath: () => {
        return env["VSCODE_EXEC_PATH"];
      },
      getFilePath: () => {
        const activeUri = getActiveUri();
        if (activeUri) {
          return $lc(activeUri.fsPath);
        }
        return void 0;
      },
      getWorkspaceFolderPathForFile: () => {
        if (workspaceService) {
          const activeUri = getActiveUri();
          if (activeUri) {
            const ws = workspaceService.getWorkspaceFolder(activeUri);
            if (ws) {
              return $lc(ws.uri.fsPath);
            }
          }
        }
        return void 0;
      },
      getSelectedText: () => {
        if (editorService) {
          const activeEditor = editorService.activeEditor();
          if (activeEditor && !activeEditor.selection.isEmpty) {
            return activeEditor.document.getText(activeEditor.selection);
          }
        }
        return void 0;
      },
      getLineNumber: () => {
        if (editorService) {
          const activeEditor = editorService.activeEditor();
          if (activeEditor) {
            return String(activeEditor.selection.end.line + 1);
          }
        }
        return void 0;
      },
      getExtension: (id2) => {
        return extensionService.getExtension(id2);
      }
    }, void 0, homeDir ? Promise.resolve(homeDir) : void 0, Promise.resolve(env));
  }
};
var $Uxc = class $Uxc2 extends $3c {
  constructor(b, c, g, h, j) {
    super();
    this.b = b;
    this.c = c;
    this.g = g;
    this.h = h;
    this.j = j;
    this.a = new $sf(async () => {
      const configProvider = await this.h.getConfigProvider();
      const folders = await this.c.getWorkspaceFolders2() || [];
      const dynamic = { folders };
      this.B(this.c.onDidChangeWorkspace(async (e) => {
        dynamic.folders = await this.c.getWorkspaceFolders2() || [];
      }));
      return new ExtHostVariableResolverService(this.b, this.c, this.g, this.j, configProvider, dynamic, this.m());
    });
  }
  getResolver() {
    return this.a.value;
  }
  m() {
    return void 0;
  }
};
$Uxc = __decorate([
  __param(0, $Lxc),
  __param(1, $0wc),
  __param(2, $rW),
  __param(3, $axc),
  __param(4, $mxc)
], $Uxc);

// out-build/vs/workbench/api/common/extHostDebugService.js
var $Vxc = $Qk("IExtHostDebugService");
var $Wxc = class $Wxc2 extends $3c {
  get onDidStartDebugSession() {
    return this.y.event;
  }
  get onDidTerminateDebugSession() {
    return this.z.event;
  }
  get onDidChangeActiveDebugSession() {
    return this.C.event;
  }
  get activeDebugSession() {
    return this.D?.api;
  }
  get onDidReceiveDebugSessionCustomEvent() {
    return this.F.event;
  }
  get activeDebugConsole() {
    return this.G.value;
  }
  constructor(extHostRpcService, Z, $, ab, bb, cb, db, eb) {
    super();
    this.Z = Z;
    this.$ = $;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.w = /* @__PURE__ */ new Map();
    this.O = 0;
    this.P = /* @__PURE__ */ new Map();
    this.Q = /* @__PURE__ */ new Map();
    this.R = /* @__PURE__ */ new WeakMap();
    this.S = /* @__PURE__ */ new Map();
    this.W = /* @__PURE__ */ new Map();
    this.X = 0;
    this.f = 0;
    this.g = [];
    this.h = 0;
    this.j = [];
    this.m = 0;
    this.n = [];
    this.M = /* @__PURE__ */ new Map();
    this.N = /* @__PURE__ */ new Map();
    this.y = this.B(new $ze());
    this.z = this.B(new $ze());
    this.C = this.B(new $ze());
    this.F = this.B(new $ze());
    this.u = extHostRpcService.getProxy($xT.MainThreadDebugService);
    this.I = this.B(new $ze());
    this.L = this.B(new $ze());
    this.G = new $Yxc(this.u);
    this.H = /* @__PURE__ */ new Map();
    this.$.getExtensionRegistry().then((extensionRegistry) => {
      this.B(extensionRegistry.onDidChange((_) => {
        this.gb(extensionRegistry);
      }));
      this.gb(extensionRegistry);
    });
    this.Y = extHostRpcService.getProxy($xT.MainThreadTelemetry);
  }
  async $getVisualizerTreeItem(treeId, element) {
    const context = this.hb(element);
    if (!context) {
      return void 0;
    }
    const item = await this.Q.get(treeId)?.getTreeItem?.(context);
    return item ? this.fb(treeId, item) : void 0;
  }
  registerDebugVisualizationTree(manifest, id2, provider) {
    const extensionId = $5z.toKey(manifest.identifier);
    const key = this.zb(extensionId, id2);
    if (this.P.has(key)) {
      throw new Error(`A debug visualization provider with id '${id2}' is already registered`);
    }
    this.Q.set(key, provider);
    this.u.$registerDebugVisualizerTree(key, !!provider.editItem);
    return $1c(() => {
      this.u.$unregisterDebugVisualizerTree(key);
      this.Q.delete(id2);
    });
  }
  async $getVisualizerTreeItemChildren(treeId, element) {
    const item = this.S.get(element)?.item;
    if (!item) {
      return [];
    }
    const children = await this.Q.get(treeId)?.getChildren?.(item);
    return children?.map((i) => this.fb(treeId, i)) || [];
  }
  async $editVisualizerTreeItem(element, value) {
    const e = this.S.get(element);
    if (!e) {
      return void 0;
    }
    const r = await this.Q.get(e.provider)?.editItem?.(e.item, value);
    return this.fb(e.provider, r || e.item);
  }
  $disposeVisualizedTree(element) {
    const root = this.S.get(element);
    if (!root) {
      return;
    }
    const queue = [root.children];
    for (const children of queue) {
      if (children) {
        for (const child of children) {
          queue.push(this.S.get(child)?.children);
          this.S.delete(child);
        }
      }
    }
  }
  fb(treeId, item) {
    let id2 = this.R.get(item);
    if (!id2) {
      id2 = this.O++;
      this.R.set(item, id2);
      this.S.set(id2, { provider: treeId, item });
    }
    return DebugTreeItem.from(item, id2);
  }
  asDebugSourceUri(src, session) {
    const source = src;
    if (typeof source.sourceReference === "number" && source.sourceReference > 0) {
      let debug = `debug:${encodeURIComponent(source.path || "")}`;
      let sep2 = "?";
      if (session) {
        debug += `${sep2}session=${encodeURIComponent(session.id)}`;
        sep2 = "&";
      }
      debug += `${sep2}ref=${source.sourceReference}`;
      return URI.parse(debug);
    } else if (source.path) {
      return URI.file(source.path);
    } else {
      throw new Error(`cannot create uri from DAP 'source' object; properties 'path' and 'sourceReference' are both missing.`);
    }
  }
  gb(extensionRegistry) {
    const debugTypes = [];
    for (const ed of extensionRegistry.getAllExtensionDescriptions()) {
      if (ed.contributes) {
        const debuggers = ed.contributes["debuggers"];
        if (debuggers && debuggers.length > 0) {
          for (const dbg of debuggers) {
            if ($rP(dbg)) {
              debugTypes.push(dbg.type);
            }
          }
        }
      }
    }
    this.u.$registerDebugTypes(debugTypes);
  }
  // extension debug API
  get activeStackItem() {
    return this.J;
  }
  get onDidChangeActiveStackItem() {
    return this.L.event;
  }
  get onDidChangeBreakpoints() {
    return this.I.event;
  }
  get breakpoints() {
    const result = [];
    this.H.forEach((bp) => result.push(bp));
    return result;
  }
  async $resolveDebugVisualizer(id2, token) {
    const visualizer = this.W.get(id2);
    if (!visualizer) {
      throw new Error(`No debug visualizer found with id '${id2}'`);
    }
    let { v, provider, extensionId } = visualizer;
    if (!v.visualization) {
      v = await provider.resolveDebugVisualization?.(v, token) || v;
      visualizer.v = v;
    }
    if (!v.visualization) {
      throw new Error(`No visualization returned from resolveDebugVisualization in '${provider}'`);
    }
    return this.Ab(extensionId, v.visualization);
  }
  async $executeDebugVisualizerCommand(id2) {
    const visualizer = this.W.get(id2);
    if (!visualizer) {
      throw new Error(`No debug visualizer found with id '${id2}'`);
    }
    const command = visualizer.v.visualization;
    if (command && "command" in command) {
      this.db.executeCommand(command.command, ...command.arguments || []);
    }
  }
  hb(context) {
    const session = this.w.get(context.sessionId);
    return session && {
      session: session.api,
      variable: context.variable,
      containerId: context.containerId,
      frameId: context.frameId,
      threadId: context.threadId
    };
  }
  async $provideDebugVisualizers(extensionId, id2, context, token) {
    const contextHydrated = this.hb(context);
    const key = this.zb(extensionId, id2);
    const provider = this.P.get(key);
    if (!contextHydrated || !provider) {
      return [];
    }
    const visualizations = await provider.provideDebugVisualization(contextHydrated, token);
    if (!visualizations) {
      return [];
    }
    return visualizations.map((v) => {
      const id3 = ++this.X;
      this.W.set(id3, { v, provider, extensionId });
      const icon = v.iconPath ? this.Bb(v.iconPath) : void 0;
      return {
        id: id3,
        name: v.name,
        iconClass: icon?.iconClass,
        iconPath: icon?.iconPath,
        visualization: this.Ab(extensionId, v.visualization)
      };
    });
  }
  $disposeDebugVisualizers(ids) {
    for (const id2 of ids) {
      this.W.delete(id2);
    }
  }
  registerDebugVisualizationProvider(manifest, id2, provider) {
    if (!manifest.contributes?.debugVisualizers?.some((r) => r.id === id2)) {
      throw new Error(`Extensions may only call registerDebugVisualizationProvider() for renderers they contribute (got ${id2})`);
    }
    const extensionId = $5z.toKey(manifest.identifier);
    const key = this.zb(extensionId, id2);
    if (this.P.has(key)) {
      throw new Error(`A debug visualization provider with id '${id2}' is already registered`);
    }
    this.P.set(key, provider);
    this.u.$registerDebugVisualizer(extensionId, id2);
    return $1c(() => {
      this.u.$unregisterDebugVisualizer(extensionId, id2);
      this.P.delete(id2);
    });
  }
  addBreakpoints(breakpoints0) {
    const breakpoints = breakpoints0.filter((bp) => {
      const id2 = bp.id;
      if (!this.H.has(id2)) {
        this.H.set(id2, bp);
        return true;
      }
      return false;
    });
    this.wb(breakpoints, [], []);
    const dtos = [];
    const map = /* @__PURE__ */ new Map();
    for (const bp of breakpoints) {
      if (bp instanceof $FU) {
        let dto = map.get(bp.location.uri.toString());
        if (!dto) {
          dto = {
            type: "sourceMulti",
            uri: bp.location.uri,
            lines: []
          };
          map.set(bp.location.uri.toString(), dto);
          dtos.push(dto);
        }
        dto.lines.push({
          id: bp.id,
          enabled: bp.enabled,
          condition: bp.condition,
          hitCondition: bp.hitCondition,
          logMessage: bp.logMessage,
          line: bp.location.range.start.line,
          character: bp.location.range.start.character,
          mode: bp.mode
        });
      } else if (bp instanceof $GU) {
        dtos.push({
          type: "function",
          id: bp.id,
          enabled: bp.enabled,
          hitCondition: bp.hitCondition,
          logMessage: bp.logMessage,
          condition: bp.condition,
          functionName: bp.functionName,
          mode: bp.mode
        });
      }
    }
    return this.u.$registerBreakpoints(dtos);
  }
  removeBreakpoints(breakpoints0) {
    const breakpoints = breakpoints0.filter((b) => this.H.delete(b.id));
    this.wb([], breakpoints, []);
    const ids = breakpoints.filter((bp) => bp instanceof $FU).map((bp) => bp.id);
    const fids = breakpoints.filter((bp) => bp instanceof $GU).map((bp) => bp.id);
    const dids = breakpoints.filter((bp) => bp instanceof $HU).map((bp) => bp.id);
    return this.u.$unregisterBreakpoints(ids, fids, dids);
  }
  startDebugging(folder, nameOrConfig, options2) {
    const testRunMeta = options2.testRun && this.eb.getMetadataForRun(options2.testRun);
    return this.u.$startDebugging(folder ? folder.uri : void 0, nameOrConfig, {
      parentSessionID: options2.parentSession ? options2.parentSession.id : void 0,
      lifecycleManagedByParent: options2.lifecycleManagedByParent,
      repl: options2.consoleMode === DebugConsoleMode.MergeWithParent ? "mergeWithParent" : "separate",
      noDebug: options2.noDebug,
      compact: options2.compact,
      suppressSaveBeforeStart: options2.suppressSaveBeforeStart,
      testRun: testRunMeta && {
        runId: testRunMeta.runId,
        taskId: testRunMeta.taskId
      },
      // Check debugUI for back-compat, #147264
      suppressDebugStatusbar: options2.suppressDebugStatusbar ?? options2.debugUI?.simple,
      suppressDebugToolbar: options2.suppressDebugToolbar ?? options2.debugUI?.simple,
      suppressDebugView: options2.suppressDebugView ?? options2.debugUI?.simple
    });
  }
  stopDebugging(session) {
    return this.u.$stopDebugging(session ? session.id : void 0);
  }
  registerDebugConfigurationProvider(type, provider, trigger) {
    if (!provider) {
      return new $zT(() => {
      });
    }
    const handle = this.f++;
    this.g.push({ type, handle, provider });
    this.u.$registerDebugConfigurationProvider(type, trigger, !!provider.provideDebugConfigurations, !!provider.resolveDebugConfiguration, !!provider.resolveDebugConfigurationWithSubstitutedVariables, handle);
    return new $zT(() => {
      this.g = this.g.filter((p) => p.provider !== provider);
      this.u.$unregisterDebugConfigurationProvider(handle);
    });
  }
  registerDebugAdapterDescriptorFactory(extension, type, factory) {
    if (!factory) {
      return new $zT(() => {
      });
    }
    if (!this.sb(extension, type)) {
      throw new Error(`a DebugAdapterDescriptorFactory can only be registered from the extension that defines the '${type}' debugger.`);
    }
    if (this.pb(type)) {
      throw new Error(`a DebugAdapterDescriptorFactory can only be registered once per a type.`);
    }
    const handle = this.h++;
    this.j.push({ type, handle, factory });
    this.u.$registerDebugAdapterDescriptorFactory(type, handle);
    return new $zT(() => {
      this.j = this.j.filter((p) => p.factory !== factory);
      this.u.$unregisterDebugAdapterDescriptorFactory(handle);
    });
  }
  registerDebugAdapterTrackerFactory(type, factory) {
    if (!factory) {
      return new $zT(() => {
      });
    }
    const handle = this.m++;
    this.n.push({ type, handle, factory });
    return new $zT(() => {
      this.n = this.n.filter((p) => p.factory !== factory);
    });
  }
  // RPC methods (ExtHostDebugServiceShape)
  async $runInTerminal(args2, sessionId) {
    return Promise.resolve(void 0);
  }
  async $substituteVariables(folderUri, config) {
    let ws;
    const folder = await this.yb(folderUri);
    if (folder) {
      ws = {
        uri: folder.uri,
        name: folder.name,
        index: folder.index,
        toResource: () => {
          throw new Error("Not implemented");
        }
      };
    }
    const variableResolver = await this.cb.getResolver();
    return variableResolver.resolveAnyAsync(ws, config);
  }
  ib(adapter, session) {
    if (adapter instanceof $LU) {
      return new DirectDebugAdapter(adapter.implementation);
    }
    return void 0;
  }
  jb() {
    return void 0;
  }
  async $startDASession(debugAdapterHandle, sessionDto) {
    const mythis = this;
    const session = await this.xb(sessionDto);
    return this.ub(this.pb(session.type), session).then((daDescriptor) => {
      if (!daDescriptor) {
        throw new Error(`Couldn't find a debug adapter descriptor for debug type '${session.type}' (extension might have failed to activate)`);
      }
      const da = this.ib(daDescriptor, session);
      if (!da) {
        throw new Error(`Couldn't create a debug adapter for type '${session.type}'.`);
      }
      const debugAdapter = da;
      this.M.set(debugAdapterHandle, debugAdapter);
      return this.tb(session).then((tracker) => {
        if (tracker) {
          this.N.set(debugAdapterHandle, tracker);
        }
        debugAdapter.onMessage(async (message) => {
          if (message.type === "request" && message.command === "handshake") {
            const request = message;
            const response = {
              type: "response",
              seq: 0,
              command: request.command,
              request_seq: request.seq,
              success: true
            };
            if (!this.U) {
              this.U = this.jb();
            }
            try {
              if (this.U) {
                const signature = await this.U.sign(request.arguments.value);
                response.body = {
                  signature
                };
                debugAdapter.sendResponse(response);
              } else {
                throw new Error("no signer");
              }
            } catch (e) {
              response.success = false;
              response.message = e.message;
              debugAdapter.sendResponse(response);
            }
          } else {
            if (tracker && tracker.onDidSendMessage) {
              tracker.onDidSendMessage(message);
            }
            try {
              message = $wP(message, true);
            } catch (e) {
              const type = message.type + "_" + (message.command ?? message.event ?? "");
              this.Y.$publicLog2("debugProtocolMessageError", { type, from: session.type });
              throw e;
            }
            mythis.u.$acceptDAMessage(debugAdapterHandle, message);
          }
        });
        debugAdapter.onError((err) => {
          if (tracker && tracker.onError) {
            tracker.onError(err);
          }
          this.u.$acceptDAError(debugAdapterHandle, err.name, err.message, err.stack);
        });
        debugAdapter.onExit((code) => {
          if (tracker && tracker.onExit) {
            tracker.onExit(code ?? void 0, void 0);
          }
          this.u.$acceptDAExit(debugAdapterHandle, code ?? void 0, void 0);
        });
        if (tracker && tracker.onWillStartSession) {
          tracker.onWillStartSession();
        }
        return debugAdapter.startSession();
      });
    });
  }
  $sendDAMessage(debugAdapterHandle, message) {
    message = $vP(message, false);
    const tracker = this.N.get(debugAdapterHandle);
    if (tracker && tracker.onWillReceiveMessage) {
      tracker.onWillReceiveMessage(message);
    }
    const da = this.M.get(debugAdapterHandle);
    da?.sendMessage(message);
  }
  $stopDASession(debugAdapterHandle) {
    const tracker = this.N.get(debugAdapterHandle);
    this.N.delete(debugAdapterHandle);
    if (tracker && tracker.onWillStopSession) {
      tracker.onWillStopSession();
    }
    const da = this.M.get(debugAdapterHandle);
    this.M.delete(debugAdapterHandle);
    if (da) {
      return da.stopSession();
    } else {
      return Promise.resolve(void 0);
    }
  }
  $acceptBreakpointsDelta(delta2) {
    const a = [];
    const r = [];
    const c = [];
    if (delta2.added) {
      for (const bpd of delta2.added) {
        const id2 = bpd.id;
        if (id2 && !this.H.has(id2)) {
          let bp;
          if (bpd.type === "function") {
            bp = new $GU(bpd.functionName, bpd.enabled, bpd.condition, bpd.hitCondition, bpd.logMessage, bpd.mode);
          } else if (bpd.type === "data") {
            bp = new $HU(bpd.label, bpd.dataId, bpd.canPersist, bpd.enabled, bpd.hitCondition, bpd.condition, bpd.logMessage, bpd.mode);
          } else {
            const uri = URI.revive(bpd.uri);
            bp = new $FU(new $NT(uri, new $AT(bpd.line, bpd.character)), bpd.enabled, bpd.condition, bpd.hitCondition, bpd.logMessage, bpd.mode);
          }
          $DU(bp, id2);
          this.H.set(id2, bp);
          a.push(bp);
        }
      }
    }
    if (delta2.removed) {
      for (const id2 of delta2.removed) {
        const bp = this.H.get(id2);
        if (bp) {
          this.H.delete(id2);
          r.push(bp);
        }
      }
    }
    if (delta2.changed) {
      for (const bpd of delta2.changed) {
        if (bpd.id) {
          const bp = this.H.get(bpd.id);
          if (bp) {
            if (bp instanceof $GU && bpd.type === "function") {
              const fbp = bp;
              fbp.enabled = bpd.enabled;
              fbp.condition = bpd.condition;
              fbp.hitCondition = bpd.hitCondition;
              fbp.logMessage = bpd.logMessage;
              fbp.functionName = bpd.functionName;
            } else if (bp instanceof $FU && bpd.type === "source") {
              const sbp = bp;
              sbp.enabled = bpd.enabled;
              sbp.condition = bpd.condition;
              sbp.hitCondition = bpd.hitCondition;
              sbp.logMessage = bpd.logMessage;
              sbp.location = new $NT(URI.revive(bpd.uri), new $AT(bpd.line, bpd.character));
            }
            c.push(bp);
          }
        }
      }
    }
    this.wb(a, r, c);
  }
  async $acceptStackFrameFocus(focusDto) {
    let focus;
    if (focusDto) {
      const session = await this.xb(focusDto.sessionId);
      if (focusDto.kind === "thread") {
        focus = new $NU(session.api, focusDto.threadId);
      } else {
        focus = new $MU(session.api, focusDto.threadId, focusDto.frameId);
      }
    }
    this.J = focus;
    this.L.fire(this.J);
  }
  $provideDebugConfigurations(configProviderHandle, folderUri, token) {
    return $Nh(async () => {
      const provider = this.rb(configProviderHandle);
      if (!provider) {
        throw new Error("no DebugConfigurationProvider found");
      }
      if (!provider.provideDebugConfigurations) {
        throw new Error("DebugConfigurationProvider has no method provideDebugConfigurations");
      }
      const folder = await this.yb(folderUri);
      return provider.provideDebugConfigurations(folder, token);
    }).then((debugConfigurations) => {
      if (!debugConfigurations) {
        throw new Error("nothing returned from DebugConfigurationProvider.provideDebugConfigurations");
      }
      return debugConfigurations;
    });
  }
  $resolveDebugConfiguration(configProviderHandle, folderUri, debugConfiguration, token) {
    return $Nh(async () => {
      const provider = this.rb(configProviderHandle);
      if (!provider) {
        throw new Error("no DebugConfigurationProvider found");
      }
      if (!provider.resolveDebugConfiguration) {
        throw new Error("DebugConfigurationProvider has no method resolveDebugConfiguration");
      }
      const folder = await this.yb(folderUri);
      return provider.resolveDebugConfiguration(folder, debugConfiguration, token);
    });
  }
  $resolveDebugConfigurationWithSubstitutedVariables(configProviderHandle, folderUri, debugConfiguration, token) {
    return $Nh(async () => {
      const provider = this.rb(configProviderHandle);
      if (!provider) {
        throw new Error("no DebugConfigurationProvider found");
      }
      if (!provider.resolveDebugConfigurationWithSubstitutedVariables) {
        throw new Error("DebugConfigurationProvider has no method resolveDebugConfigurationWithSubstitutedVariables");
      }
      const folder = await this.yb(folderUri);
      return provider.resolveDebugConfigurationWithSubstitutedVariables(folder, debugConfiguration, token);
    });
  }
  async $provideDebugAdapter(adapterFactoryHandle, sessionDto) {
    const adapterDescriptorFactory = this.qb(adapterFactoryHandle);
    if (!adapterDescriptorFactory) {
      return Promise.reject(new Error("no adapter descriptor factory found for handle"));
    }
    const session = await this.xb(sessionDto);
    return this.ub(adapterDescriptorFactory, session).then((adapterDescriptor) => {
      if (!adapterDescriptor) {
        throw new Error(`Couldn't find a debug adapter descriptor for debug type '${session.type}'`);
      }
      return this.kb(adapterDescriptor);
    });
  }
  async $acceptDebugSessionStarted(sessionDto) {
    const session = await this.xb(sessionDto);
    this.y.fire(session.api);
  }
  async $acceptDebugSessionTerminated(sessionDto) {
    const session = await this.xb(sessionDto);
    if (session) {
      this.z.fire(session.api);
      this.w.delete(session.id);
    }
  }
  async $acceptDebugSessionActiveChanged(sessionDto) {
    this.D = sessionDto ? await this.xb(sessionDto) : void 0;
    this.C.fire(this.D?.api);
  }
  async $acceptDebugSessionNameChanged(sessionDto, name) {
    const session = await this.xb(sessionDto);
    session?._acceptNameChanged(name);
  }
  async $acceptDebugSessionCustomEvent(sessionDto, event) {
    const session = await this.xb(sessionDto);
    const ee = {
      session: session.api,
      event: event.event,
      body: event.body
    };
    this.F.fire(ee);
  }
  // private & dto helpers
  kb(x) {
    if (x instanceof $IU) {
      return this.lb(x);
    } else if (x instanceof $JU) {
      return this.mb(x);
    } else if (x instanceof $KU) {
      return this.nb(x);
    } else if (x instanceof $LU) {
      return this.ob(x);
    } else {
      throw new Error("convertToDto unexpected type");
    }
  }
  lb(x) {
    return {
      type: "executable",
      command: x.command,
      args: x.args,
      options: x.options
    };
  }
  mb(x) {
    return {
      type: "server",
      port: x.port,
      host: x.host
    };
  }
  nb(x) {
    return {
      type: "pipeServer",
      path: x.path
    };
  }
  ob(x) {
    return {
      type: "implementation"
    };
  }
  pb(type) {
    const results = this.j.filter((p) => p.type === type);
    if (results.length > 0) {
      return results[0].factory;
    }
    return void 0;
  }
  qb(handle) {
    const results = this.j.filter((p) => p.handle === handle);
    if (results.length > 0) {
      return results[0].factory;
    }
    return void 0;
  }
  rb(handle) {
    const results = this.g.filter((p) => p.handle === handle);
    if (results.length > 0) {
      return results[0].provider;
    }
    return void 0;
  }
  sb(ed, type) {
    if (ed.contributes) {
      const debuggers = ed.contributes["debuggers"];
      if (debuggers && debuggers.length > 0) {
        for (const dbg of debuggers) {
          if (dbg.label && dbg.type) {
            if (dbg.type === type) {
              return true;
            }
          }
        }
      }
    }
    return false;
  }
  tb(session) {
    const config = session.configuration;
    const type = config.type;
    const promises8 = this.n.filter((tuple) => tuple.type === type || tuple.type === "*").map((tuple) => $Nh(() => tuple.factory.createDebugAdapterTracker(session.api)).then((p) => p, (err) => null));
    return Promise.race([
      Promise.all(promises8).then((result) => {
        const trackers = $Mb(result);
        if (trackers.length > 0) {
          return new MultiTracker(trackers);
        }
        return void 0;
      }),
      new Promise((resolve) => setTimeout(() => resolve(void 0), 1e3))
    ]).catch((err) => {
      return void 0;
    });
  }
  async ub(adapterDescriptorFactory, session) {
    const serverPort = session.configuration.debugServer;
    if (typeof serverPort === "number") {
      return Promise.resolve(new $JU(serverPort));
    }
    if (adapterDescriptorFactory) {
      const extensionRegistry2 = await this.$.getExtensionRegistry();
      return $Nh(() => adapterDescriptorFactory.createDebugAdapterDescriptor(session.api, this.vb(session, extensionRegistry2))).then((daDescriptor) => {
        if (daDescriptor) {
          return daDescriptor;
        }
        return void 0;
      });
    }
    const extensionRegistry = await this.$.getExtensionRegistry();
    return Promise.resolve(this.vb(session, extensionRegistry));
  }
  vb(session, extensionRegistry) {
    return void 0;
  }
  wb(added, removed, changed) {
    if (added.length > 0 || removed.length > 0 || changed.length > 0) {
      this.I.fire(Object.freeze({
        added,
        removed,
        changed
      }));
    }
  }
  async xb(dto) {
    if (dto) {
      if (typeof dto === "string") {
        const ds = this.w.get(dto);
        if (ds) {
          return ds;
        }
      } else {
        let ds = this.w.get(dto.id);
        if (!ds) {
          const folder = await this.yb(dto.folderUri);
          const parent = dto.parent ? this.w.get(dto.parent) : void 0;
          ds = new $Xxc(this.u, dto.id, dto.type, dto.name, folder, dto.configuration, parent?.api);
          this.w.set(ds.id, ds);
          this.u.$sessionCached(ds.id);
        }
        return ds;
      }
    }
    throw new Error("cannot find session");
  }
  yb(_folderUri) {
    if (_folderUri) {
      const folderURI = URI.revive(_folderUri);
      return this.Z.resolveWorkspaceFolder(folderURI);
    }
    return Promise.resolve(void 0);
  }
  zb(extensionId, id2) {
    return `${extensionId}\0${id2}`;
  }
  Ab(extensionId, viz) {
    if (!viz) {
      return void 0;
    }
    if ("title" in viz && "command" in viz) {
      return {
        type: 0
        /* DebugVisualizationType.Command */
      };
    }
    if ("treeId" in viz) {
      return { type: 1, id: `${extensionId}\0${viz.treeId}` };
    }
    throw new Error("Unsupported debug visualization type");
  }
  Bb(icon) {
    const iconPathOrIconClass = this.Cb(icon);
    let iconPath;
    let iconClass;
    if ("id" in iconPathOrIconClass) {
      iconClass = ThemeIcon.asClassName(iconPathOrIconClass);
    } else {
      iconPath = iconPathOrIconClass;
    }
    return {
      iconPath,
      iconClass
    };
  }
  Cb(iconPath) {
    if (iconPath instanceof $AU) {
      return { id: iconPath.id };
    }
    const dark = typeof iconPath === "object" && "dark" in iconPath ? iconPath.dark : iconPath;
    const light = typeof iconPath === "object" && "light" in iconPath ? iconPath.light : iconPath;
    return {
      dark: typeof dark === "string" ? URI.file(dark) : dark,
      light: typeof light === "string" ? URI.file(light) : light
    };
  }
};
$Wxc = __decorate([
  __param(0, $gW),
  __param(1, $0wc),
  __param(2, $Lxc),
  __param(3, $axc),
  __param(4, $mxc),
  __param(5, $Txc),
  __param(6, $CW),
  __param(7, $Oxc)
], $Wxc);
var $Xxc = class {
  constructor(f, g, h, j, k, l, m) {
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
  }
  get api() {
    const that = this;
    return this.d ??= Object.freeze({
      id: that.g,
      type: that.h,
      get name() {
        return that.j;
      },
      set name(name) {
        that.j = name;
        that.f.$setDebugSessionName(that.g, name);
      },
      parentSession: that.m,
      workspaceFolder: that.k,
      configuration: that.l,
      customRequest(command, args2) {
        return that.f.$customDebugAdapterRequest(that.g, command, args2);
      },
      getDebugProtocolBreakpoint(breakpoint) {
        return that.f.$getDebugProtocolBreakpoint(that.g, breakpoint.id);
      }
    });
  }
  get id() {
    return this.g;
  }
  get type() {
    return this.h;
  }
  _acceptNameChanged(name) {
    this.j = name;
  }
  get configuration() {
    return this.l;
  }
};
var $Yxc = class {
  constructor(proxy) {
    this.value = Object.freeze({
      append(value) {
        proxy.$appendDebugConsole(value);
      },
      appendLine(value) {
        this.append(value + "\n");
      }
    });
  }
};
var MultiTracker = class {
  constructor(d) {
    this.d = d;
  }
  onWillStartSession() {
    this.d.forEach((t) => t.onWillStartSession ? t.onWillStartSession() : void 0);
  }
  onWillReceiveMessage(message) {
    this.d.forEach((t) => t.onWillReceiveMessage ? t.onWillReceiveMessage(message) : void 0);
  }
  onDidSendMessage(message) {
    this.d.forEach((t) => t.onDidSendMessage ? t.onDidSendMessage(message) : void 0);
  }
  onWillStopSession() {
    this.d.forEach((t) => t.onWillStopSession ? t.onWillStopSession() : void 0);
  }
  onError(error) {
    this.d.forEach((t) => t.onError ? t.onError(error) : void 0);
  }
  onExit(code, signal) {
    this.d.forEach((t) => t.onExit ? t.onExit(code, signal) : void 0);
  }
};
var DirectDebugAdapter = class extends $xOb {
  constructor(h) {
    super();
    this.h = h;
    h.onDidSendMessage((message) => {
      this.acceptMessage(message);
    });
  }
  startSession() {
    return Promise.resolve(void 0);
  }
  sendMessage(message) {
    this.h.handleMessage(message);
  }
  stopSession() {
    this.h.dispose();
    return Promise.resolve(void 0);
  }
};
var $Zxc = class $Zxc2 extends $Wxc {
  constructor(extHostRpcService, workspaceService, extensionService, configurationService, editorTabs, variableResolver, commands, testing) {
    super(extHostRpcService, workspaceService, extensionService, configurationService, editorTabs, variableResolver, commands, testing);
  }
};
$Zxc = __decorate([
  __param(0, $gW),
  __param(1, $0wc),
  __param(2, $Lxc),
  __param(3, $axc),
  __param(4, $mxc),
  __param(5, $Txc),
  __param(6, $CW),
  __param(7, $Oxc)
], $Zxc);

// out-build/vs/workbench/services/search/common/searchExtConversionTypes.js
function isTextSearchMatch(object) {
  return "uri" in object && "ranges" in object && "preview" in object;
}
function newToOldFileProviderOptions(options2) {
  return options2.folderOptions.map((folderOption) => ({
    folder: folderOption.folder,
    excludes: folderOption.excludes.map((e) => typeof e === "string" ? e : e.pattern),
    includes: folderOption.includes,
    useGlobalIgnoreFiles: folderOption.useIgnoreFiles.global,
    useIgnoreFiles: folderOption.useIgnoreFiles.local,
    useParentIgnoreFiles: folderOption.useIgnoreFiles.parent,
    followSymlinks: folderOption.followSymlinks,
    maxResults: options2.maxResults,
    session: options2.session
    // TODO: make sure that we actually use a cancellation token here.
  }));
}
var $ayc = class {
  constructor(a) {
    this.a = a;
  }
  provideFileSearchResults(pattern, options2, token) {
    const getResult = async () => {
      const newOpts = newToOldFileProviderOptions(options2);
      return Promise.all(newOpts.map((o) => this.a.provideFileSearchResults({ pattern }, o, token)));
    };
    return getResult().then((e) => $Mb(e).flat());
  }
};
function newToOldTextProviderOptions(options2) {
  return options2.folderOptions.map((folderOption) => ({
    folder: folderOption.folder,
    excludes: folderOption.excludes.map((e) => typeof e === "string" ? e : e.pattern),
    includes: folderOption.includes,
    useGlobalIgnoreFiles: folderOption.useIgnoreFiles.global,
    useIgnoreFiles: folderOption.useIgnoreFiles.local,
    useParentIgnoreFiles: folderOption.useIgnoreFiles.parent,
    followSymlinks: folderOption.followSymlinks,
    maxResults: options2.maxResults,
    previewOptions: $byc(options2.previewOptions),
    maxFileSize: options2.maxFileSize,
    encoding: folderOption.encoding,
    afterContext: options2.surroundingContext,
    beforeContext: options2.surroundingContext
  }));
}
function $byc(options2) {
  return {
    matchLines: options2?.matchLines ?? $eO.matchLines,
    charsPerLine: options2?.charsPerLine ?? $eO.charsPerLine
  };
}
function $cyc(result) {
  if (isTextSearchMatch(result)) {
    const ranges = $5b(result.ranges).map((r, i) => {
      const previewArr = $5b(result.preview.matches);
      const matchingPreviewRange = previewArr[i];
      return { sourceRange: r, previewRange: matchingPreviewRange };
    });
    return new $LN(result.uri, ranges, result.preview.text);
  } else {
    return new $MN(result.uri, result.text, result.lineNumber);
  }
}
var $dyc = class {
  constructor(a) {
    this.a = a;
  }
  provideTextSearchResults(query, options2, progress, token) {
    const progressShim = (oldResult2) => {
      if (!validateProviderResult(oldResult2)) {
        return;
      }
      progress.report($cyc(oldResult2));
    };
    const getResult = async () => {
      return $Mb(await Promise.all(newToOldTextProviderOptions(options2).map((o) => this.a.provideTextSearchResults(query, o, { report: (e) => progressShim(e) }, token)))).reduce((prev, cur) => ({ limitHit: prev.limitHit || cur.limitHit }), { limitHit: false });
    };
    const oldResult = getResult();
    return oldResult.then((e) => {
      return {
        limitHit: e.limitHit,
        message: $Mb($5b(e.message))
      };
    });
  }
};
function validateProviderResult(result) {
  if ($eyc(result)) {
    if (Array.isArray(result.ranges)) {
      if (!Array.isArray(result.preview.matches)) {
        console.warn("INVALID - A text search provider match's`ranges` and`matches` properties must have the same type.");
        return false;
      }
      if (result.preview.matches.length !== result.ranges.length) {
        console.warn("INVALID - A text search provider match's`ranges` and`matches` properties must have the same length.");
        return false;
      }
    } else {
      if (Array.isArray(result.preview.matches)) {
        console.warn("INVALID - A text search provider match's`ranges` and`matches` properties must have the same length.");
        return false;
      }
    }
  }
  return true;
}
function $eyc(data) {
  return !!data.preview;
}

// out-build/vs/workbench/services/search/common/folderQuerySearchTree.js
var $fyc = class extends $Wk {
  constructor(folderQueries, getFolderQueryInfo, ignorePathCasing2 = () => false) {
    const uriIterator = new $Vk(ignorePathCasing2, () => false);
    super(uriIterator);
    const fqBySameBase = new $Ec();
    folderQueries.forEach((fq, i) => {
      const uriWithoutQueryOrFragment = fq.folder.with({ query: "", fragment: "" });
      if (fqBySameBase.has(uriWithoutQueryOrFragment)) {
        fqBySameBase.get(uriWithoutQueryOrFragment).push({ fq, i });
      } else {
        fqBySameBase.set(uriWithoutQueryOrFragment, [{ fq, i }]);
      }
    });
    fqBySameBase.forEach((values, key) => {
      const folderQueriesWithQueries = /* @__PURE__ */ new Map();
      for (const fqBases of values) {
        const folderQueryInfo = getFolderQueryInfo(fqBases.fq, fqBases.i);
        folderQueriesWithQueries.set(this.l(fqBases.fq.folder), folderQueryInfo);
      }
      super.set(key, folderQueriesWithQueries);
    });
  }
  findQueryFragmentAwareSubstr(key) {
    const baseURIResult = super.findSubstr(key.with({ query: "", fragment: "" }));
    if (!baseURIResult) {
      return void 0;
    }
    const queryAndFragmentKey = this.l(key);
    return baseURIResult.get(queryAndFragmentKey);
  }
  forEachFolderQueryInfo(fn) {
    return this.forEach((elem) => elem.forEach((mapElem) => fn(mapElem)));
  }
  l(key) {
    let str = "";
    if (key.query) {
      str += key.query;
    }
    if (key.fragment) {
      str += "#" + key.fragment;
    }
    return str;
  }
};

// out-build/vs/workbench/services/search/common/fileSearchManager.js
var FileSearchEngine = class {
  constructor(l, o, p) {
    this.l = l;
    this.o = o;
    this.p = p;
    this.f = false;
    this.g = 0;
    this.h = false;
    this.a = l.filePattern;
    this.b = l.includePattern && $Dl(l.includePattern);
    this.c = l.maxResults || void 0;
    this.d = l.exists;
    this.j = /* @__PURE__ */ new Set();
    this.k = l.excludePattern && $Dl(l.excludePattern);
  }
  cancel() {
    this.h = true;
    this.j.forEach((t) => t.cancel());
    this.j = /* @__PURE__ */ new Set();
  }
  search(_onResult) {
    const folderQueries = this.l.folderQueries || [];
    return new Promise((resolve, reject) => {
      const onResult = (match) => {
        this.g++;
        _onResult(match);
      };
      if (this.h) {
        return resolve({ limitHit: this.f });
      }
      if (this.l.extraFileResources) {
        this.l.extraFileResources.forEach((extraFile) => {
          const extraFileStr = extraFile.toString();
          const basename = $rc(extraFileStr);
          if (this.k && this.k(extraFileStr, basename)) {
            return;
          }
          this.w(onResult, { base: extraFile, basename });
        });
      }
      this.q(folderQueries, onResult).then((stats) => {
        resolve({
          limitHit: this.f,
          stats: stats || void 0
          // Only looking at single-folder workspace stats...
        });
      }, (err) => {
        reject(new Error($1m(err)));
      });
    });
  }
  async q(fqs, onResult) {
    const cancellation = new $ad();
    const folderOptions = fqs.map((fq) => this.r(fq));
    const session = this.o instanceof $ayc ? this.p?.tokenSource.token : this.p?.obj;
    const options2 = {
      folderOptions,
      maxResults: this.l.maxResults ?? $SN,
      session
    };
    const getFolderQueryInfo = (fq) => {
      const queryTester = new $aO(this.l, fq);
      const noSiblingsClauses = !queryTester.hasSiblingExcludeClauses();
      return { queryTester, noSiblingsClauses, folder: fq.folder, tree: this.s() };
    };
    const folderMappings = new $fyc(fqs, getFolderQueryInfo);
    let providerSW;
    try {
      this.j.add(cancellation);
      providerSW = $te.create();
      const results = await this.o.provideFileSearchResults(this.l.filePattern || "", options2, cancellation.token);
      const providerTime = providerSW.elapsed();
      const postProcessSW = $te.create();
      if (this.h && !this.f) {
        return null;
      }
      if (results) {
        results.forEach((result) => {
          const fqFolderInfo = folderMappings.findQueryFragmentAwareSubstr(result);
          const relativePath = $kc.relative(fqFolderInfo.folder.path, result.path);
          if (fqFolderInfo.noSiblingsClauses) {
            const basename = $rc(result.path);
            this.w(onResult, { base: fqFolderInfo.folder, relativePath, basename });
            return;
          }
          this.u(fqFolderInfo.tree, fqFolderInfo.folder, relativePath, onResult);
        });
      }
      if (this.h && !this.f) {
        return null;
      }
      folderMappings.forEachFolderQueryInfo((e) => {
        this.v(e.tree, e.queryTester, onResult);
      });
      return {
        providerTime,
        postProcessTime: postProcessSW.elapsed()
      };
    } finally {
      cancellation.dispose();
      this.j.delete(cancellation);
    }
  }
  r(fq) {
    const includes = $_N(this.l.includePattern, fq.includePattern);
    let excludePattern = fq.excludePattern?.map((e) => ({
      folder: e.folder,
      patterns: $_N(this.l.excludePattern, e.pattern)
    }));
    if (!excludePattern?.length) {
      excludePattern = [{
        folder: void 0,
        patterns: $_N(this.l.excludePattern, void 0)
      }];
    }
    const excludes = $dO(excludePattern);
    return {
      folder: fq.folder,
      excludes,
      includes,
      useIgnoreFiles: {
        local: !fq.disregardIgnoreFiles,
        parent: !fq.disregardParentIgnoreFiles,
        global: !fq.disregardGlobalIgnoreFiles
      },
      followSymlinks: !fq.ignoreSymlinks
    };
  }
  s() {
    const tree = {
      rootEntries: [],
      pathToEntries: /* @__PURE__ */ Object.create(null)
    };
    tree.pathToEntries["."] = tree.rootEntries;
    return tree;
  }
  u({ pathToEntries }, base, relativeFile, onResult) {
    if (relativeFile === this.a) {
      const basename = $rc(this.a);
      this.w(onResult, { base, relativePath: this.a, basename });
    }
    function add(relativePath) {
      const basename = $rc(relativePath);
      const dirname = $qc(relativePath);
      let entries = pathToEntries[dirname];
      if (!entries) {
        entries = pathToEntries[dirname] = [];
        add(dirname);
      }
      entries.push({
        base,
        relativePath,
        basename
      });
    }
    add(relativeFile);
  }
  v({ rootEntries, pathToEntries }, queryTester, onResult) {
    const self2 = this;
    const filePattern = this.a;
    function matchDirectory(entries) {
      const hasSibling = $cO(() => entries.map((entry) => entry.basename));
      for (let i = 0, n = entries.length; i < n; i++) {
        const entry = entries[i];
        const { relativePath, basename } = entry;
        if (queryTester.matchesExcludesSync(relativePath, basename, filePattern !== basename ? hasSibling : void 0)) {
          continue;
        }
        const sub = pathToEntries[relativePath];
        if (sub) {
          matchDirectory(sub);
        } else {
          if (relativePath === filePattern) {
            continue;
          }
          self2.w(onResult, entry);
        }
        if (self2.f) {
          break;
        }
      }
    }
    matchDirectory(rootEntries);
  }
  w(onResult, candidate) {
    if (!this.b || candidate.relativePath && this.b(candidate.relativePath, candidate.basename)) {
      if (this.d || this.c && this.g >= this.c) {
        this.f = true;
        this.cancel();
      }
      if (!this.f) {
        onResult(candidate);
      }
    }
  }
};
var SessionLifecycle = class {
  constructor() {
    this.a = new Object();
    this.tokenSource = new $ad();
  }
  get obj() {
    if (this.a) {
      return this.a;
    }
    throw new Error("Session object has been dereferenced.");
  }
  cancel() {
    this.tokenSource.cancel();
    this.a = void 0;
  }
};
var $gyc = class _$gyc {
  constructor() {
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.a = 512;
  }
  fileSearch(config, provider, onBatch, token) {
    const sessionTokenSource = this.c(config.cacheKey);
    const engine = new FileSearchEngine(config, provider, sessionTokenSource);
    let resultCount = 0;
    const onInternalResult = (batch) => {
      resultCount += batch.length;
      onBatch(batch.map((m) => this.d(m)));
    };
    return this.f(engine, _$gyc.a, onInternalResult, token).then((result) => {
      return {
        limitHit: result.limitHit,
        stats: result.stats ? {
          fromCache: false,
          type: "fileSearchProvider",
          resultCount,
          detailStats: result.stats
        } : void 0,
        messages: []
      };
    });
  }
  clearCache(cacheKey) {
    this.b.get(cacheKey)?.cancel();
    this.b.delete(cacheKey);
  }
  c(cacheKey) {
    if (!cacheKey) {
      return void 0;
    }
    if (!this.b.has(cacheKey)) {
      this.b.set(cacheKey, new SessionLifecycle());
    }
    return this.b.get(cacheKey);
  }
  d(match) {
    if (match.relativePath) {
      return {
        resource: $vh(match.base, match.relativePath)
      };
    } else {
      return {
        resource: match.base
      };
    }
  }
  f(engine, batchSize, onResultBatch, token) {
    const listener = token.onCancellationRequested(() => {
      engine.cancel();
    });
    const _onResult = (match) => {
      if (match) {
        batch.push(match);
        if (batchSize > 0 && batch.length >= batchSize) {
          onResultBatch(batch);
          batch = [];
        }
      }
    };
    let batch = [];
    return engine.search(_onResult).then((result) => {
      if (batch.length) {
        onResultBatch(batch);
      }
      listener.dispose();
      return result;
    }, (error) => {
      if (batch.length) {
        onResultBatch(batch);
      }
      listener.dispose();
      return Promise.reject(error);
    });
  }
};

// out-build/vs/workbench/services/search/common/textSearchManager.js
var $hyc = class {
  constructor(f, g, h) {
    this.f = f;
    this.g = g;
    this.h = h;
    this.b = null;
    this.c = false;
    this.d = 0;
  }
  get j() {
    return this.f.query;
  }
  search(onProgress, token) {
    const folderQueries = this.j.folderQueries || [];
    const tokenSource = new $ad(token);
    return new Promise((resolve, reject) => {
      this.b = new $iyc(onProgress);
      let isCanceled = false;
      const onResult = (result, folderIdx) => {
        if (isCanceled) {
          return;
        }
        if (!this.c) {
          const resultSize = this.l(result);
          if (result instanceof $LN && typeof this.j.maxResults === "number" && this.d + resultSize > this.j.maxResults) {
            this.c = true;
            isCanceled = true;
            tokenSource.cancel();
            result = this.m(result, this.j.maxResults - this.d);
          }
          const newResultSize = this.l(result);
          this.d += newResultSize;
          const a = result instanceof $LN;
          if (newResultSize > 0 || !a) {
            this.b.add(result, folderIdx);
          }
        }
      };
      this.n(folderQueries, onResult, tokenSource.token).then((result) => {
        tokenSource.dispose();
        this.b.flush();
        resolve({
          limitHit: this.c || result?.limitHit,
          messages: this.k(result),
          stats: {
            type: this.h
          }
        });
      }, (err) => {
        tokenSource.dispose();
        const errMsg = $1m(err);
        reject(new Error(errMsg));
      });
    });
  }
  k(result) {
    if (!result?.message) {
      return [];
    }
    if (Array.isArray(result.message)) {
      return result.message;
    }
    return [result.message];
  }
  l(result) {
    if (result instanceof $LN) {
      return Array.isArray(result.ranges) ? result.ranges.length : 1;
    } else {
      return 0;
    }
  }
  m(result, size) {
    return new $LN(result.uri, result.ranges.slice(0, size), result.previewText);
  }
  async n(folderQueries, onResult, token) {
    const folderMappings = new $fyc(folderQueries, (fq, i) => {
      const queryTester = new $aO(this.j, fq);
      return { queryTester, folder: fq.folder, folderIdx: i };
    }, () => true);
    const testingPs = [];
    const progress = {
      report: (result2) => {
        if (result2.uri === void 0) {
          throw Error("Text search result URI is undefined. Please check provider implementation.");
        }
        const folderQuery = folderMappings.findQueryFragmentAwareSubstr(result2.uri);
        const hasSibling = folderQuery.folder.scheme === Schemas.file ? $bO(() => {
          return this.g.readdir($uh(result2.uri));
        }) : void 0;
        const relativePath = $xh(folderQuery.folder, result2.uri);
        if (relativePath) {
          const included = folderQuery.queryTester.includedInQuery(relativePath, $rc(relativePath), hasSibling);
          if ($Gh(included)) {
            testingPs.push(included.then((isIncluded) => {
              if (isIncluded) {
                onResult(result2, folderQuery.folderIdx);
              }
            }));
          } else if (included) {
            onResult(result2, folderQuery.folderIdx);
          }
        }
      }
    };
    const folderOptions = folderQueries.map((fq) => this.o(fq));
    const searchOptions = {
      folderOptions,
      maxFileSize: this.j.maxFileSize,
      maxResults: this.j.maxResults ?? $SN,
      previewOptions: this.j.previewOptions ?? $eO,
      surroundingContext: this.j.surroundingContext ?? 0
    };
    if ("usePCRE2" in this.j) {
      searchOptions.usePCRE2 = this.j.usePCRE2;
    }
    let result;
    if (this.f.query.type === 3) {
      result = await this.f.provider.provideAITextSearchResults(this.f.query.contentPattern, searchOptions, progress, token);
    } else {
      result = await this.f.provider.provideTextSearchResults(patternInfoToQuery(this.f.query.contentPattern), searchOptions, progress, token);
    }
    if (testingPs.length) {
      await Promise.all(testingPs);
    }
    return result;
  }
  o(fq) {
    const includes = $_N(this.j.includePattern, fq.includePattern);
    let excludePattern = fq.excludePattern?.map((e) => ({
      folder: e.folder,
      patterns: $_N(this.j.excludePattern, e.pattern)
    }));
    if (!excludePattern || excludePattern.length === 0) {
      excludePattern = [{
        folder: void 0,
        patterns: $_N(this.j.excludePattern, void 0)
      }];
    }
    const excludes = $dO(excludePattern);
    const options2 = {
      folder: URI.from(fq.folder),
      excludes,
      includes,
      useIgnoreFiles: {
        local: !fq.disregardIgnoreFiles,
        parent: !fq.disregardParentIgnoreFiles,
        global: !fq.disregardGlobalIgnoreFiles
      },
      followSymlinks: !fq.ignoreSymlinks,
      encoding: (fq.fileEncoding && this.g.toCanonicalName(fq.fileEncoding)) ?? ""
    };
    return options2;
  }
};
function patternInfoToQuery(patternInfo) {
  return {
    isCaseSensitive: patternInfo.isCaseSensitive || false,
    isRegExp: patternInfo.isRegExp || false,
    isWordMatch: patternInfo.isWordMatch || false,
    isMultiline: patternInfo.isMultiline || false,
    pattern: patternInfo.pattern
  };
}
var $iyc = class {
  constructor(g) {
    this.g = g;
    this.c = -1;
    this.f = null;
    this.b = new $jyc(512, (items) => this.j(items));
  }
  add(data, folderIdx) {
    if (this.f && (this.c !== folderIdx || !$oh(this.d, data.uri))) {
      this.h();
      this.f = null;
    }
    if (!this.f) {
      this.c = folderIdx;
      this.f = {
        resource: data.uri,
        results: []
      };
    }
    this.f.results.push(extensionResultToFrontendResult(data));
  }
  h() {
    const size = this.f && this.f.results ? this.f.results.length : 0;
    this.b.addItem(this.f, size);
  }
  flush() {
    this.h();
    this.b.flush();
  }
  j(items) {
    this.g(items);
  }
};
function extensionResultToFrontendResult(data) {
  if (data instanceof $LN) {
    return {
      previewText: data.previewText,
      rangeLocations: data.ranges.map((r) => ({
        preview: {
          startLineNumber: r.previewRange.start.line,
          startColumn: r.previewRange.start.character,
          endLineNumber: r.previewRange.end.line,
          endColumn: r.previewRange.end.character
        },
        source: {
          startLineNumber: r.sourceRange.start.line,
          startColumn: r.sourceRange.start.character,
          endLineNumber: r.sourceRange.end.line,
          endColumn: r.sourceRange.end.character
        }
      }))
    };
  } else {
    return {
      text: data.text,
      lineNumber: data.lineNumber
    };
  }
}
var $jyc = class _$jyc {
  static {
    this.b = 4e3;
  }
  static {
    this.c = 50;
  }
  constructor(j, k) {
    this.j = j;
    this.k = k;
    this.d = 0;
    this.f = [];
    this.g = 0;
  }
  addItem(item, size) {
    if (!item) {
      return;
    }
    this.l(item, size);
  }
  addItems(items, size) {
    if (!items) {
      return;
    }
    this.m(items, size);
  }
  l(item, size) {
    this.f.push(item);
    this.g += size;
    this.n();
  }
  m(item, size) {
    this.f = this.f.concat(item);
    this.g += size;
    this.n();
  }
  n() {
    if (this.d < _$jyc.c) {
      this.flush();
    } else if (this.g >= this.j) {
      this.flush();
    } else if (!this.h) {
      this.h = setTimeout(() => {
        this.flush();
      }, _$jyc.b);
    }
  }
  flush() {
    if (this.g) {
      this.d += this.g;
      this.k(this.f);
      this.f = [];
      this.g = 0;
      if (this.h) {
        clearTimeout(this.h);
        this.h = 0;
      }
    }
  }
};

// out-build/vs/workbench/api/common/extHostSearch.js
var $kyc = $Qk("IExtHostSearch");
var $lyc = class $lyc2 {
  constructor(o, q, s) {
    this.o = o;
    this.q = q;
    this.s = s;
    this.c = this.o.getProxy($xT.MainThreadSearch);
    this.e = 0;
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Set();
    this.i = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Set();
    this.k = /* @__PURE__ */ new Map();
    this.l = /* @__PURE__ */ new Set();
    this.n = new $gyc();
  }
  t(scheme) {
    return this.q.transformOutgoingScheme(scheme);
  }
  registerTextSearchProviderOld(scheme, provider) {
    if (this.h.has(scheme)) {
      throw new Error(`a text search provider for the scheme '${scheme}' is already registered`);
    }
    this.h.add(scheme);
    const handle = this.e++;
    this.g.set(handle, new $dyc(provider));
    this.c.$registerTextSearchProvider(handle, this.t(scheme));
    return $1c(() => {
      this.h.delete(scheme);
      this.g.delete(handle);
      this.c.$unregisterProvider(handle);
    });
  }
  registerTextSearchProvider(scheme, provider) {
    if (this.h.has(scheme)) {
      throw new Error(`a text search provider for the scheme '${scheme}' is already registered`);
    }
    this.h.add(scheme);
    const handle = this.e++;
    this.g.set(handle, provider);
    this.c.$registerTextSearchProvider(handle, this.t(scheme));
    return $1c(() => {
      this.h.delete(scheme);
      this.g.delete(handle);
      this.c.$unregisterProvider(handle);
    });
  }
  registerAITextSearchProvider(scheme, provider) {
    if (this.j.has(scheme)) {
      throw new Error(`an AI text search provider for the scheme '${scheme}'is already registered`);
    }
    this.j.add(scheme);
    const handle = this.e++;
    this.i.set(handle, provider);
    this.c.$registerAITextSearchProvider(handle, this.t(scheme));
    return $1c(() => {
      this.j.delete(scheme);
      this.i.delete(handle);
      this.c.$unregisterProvider(handle);
    });
  }
  registerFileSearchProviderOld(scheme, provider) {
    if (this.l.has(scheme)) {
      throw new Error(`a file search provider for the scheme '${scheme}' is already registered`);
    }
    this.l.add(scheme);
    const handle = this.e++;
    this.k.set(handle, new $ayc(provider));
    this.c.$registerFileSearchProvider(handle, this.t(scheme));
    return $1c(() => {
      this.l.delete(scheme);
      this.k.delete(handle);
      this.c.$unregisterProvider(handle);
    });
  }
  registerFileSearchProvider(scheme, provider) {
    if (this.l.has(scheme)) {
      throw new Error(`a file search provider for the scheme '${scheme}' is already registered`);
    }
    this.l.add(scheme);
    const handle = this.e++;
    this.k.set(handle, provider);
    this.c.$registerFileSearchProvider(handle, this.t(scheme));
    return $1c(() => {
      this.l.delete(scheme);
      this.k.delete(handle);
      this.c.$unregisterProvider(handle);
    });
  }
  $provideFileSearchResults(handle, session, rawQuery, token) {
    const query = $myc(rawQuery);
    const provider = this.k.get(handle);
    if (provider) {
      return this.n.fileSearch(query, provider, (batch) => {
        this.c.$handleFileMatch(handle, session, batch.map((p) => p.resource));
      }, token);
    } else {
      throw new Error("unknown provider: " + handle);
    }
  }
  async doInternalFileSearchWithCustomCallback(query, token, handleFileMatch) {
    return { messages: [] };
  }
  $clearCache(cacheKey) {
    this.n.clearCache(cacheKey);
    return Promise.resolve(void 0);
  }
  $provideTextSearchResults(handle, session, rawQuery, token) {
    const provider = this.g.get(handle);
    if (!provider || !provider.provideTextSearchResults) {
      throw new Error(`Unknown Text Search Provider ${handle}`);
    }
    const query = $myc(rawQuery);
    const engine = this.v(query, provider);
    return engine.search((progress) => this.c.$handleTextMatch(handle, session, progress), token);
  }
  $provideAITextSearchResults(handle, session, rawQuery, token) {
    const provider = this.i.get(handle);
    if (!provider || !provider.provideAITextSearchResults) {
      throw new Error(`Unknown AI Text Search Provider ${handle}`);
    }
    const query = $myc(rawQuery);
    const engine = this.w(query, provider);
    return engine.search((progress) => this.c.$handleTextMatch(handle, session, progress), token);
  }
  $enableExtensionHostSearch() {
  }
  async $getAIName(handle) {
    const provider = this.i.get(handle);
    if (!provider || !provider.provideAITextSearchResults) {
      return void 0;
    }
    return provider.name ?? "AI";
  }
  v(query, provider) {
    return new $hyc({ query, provider }, {
      readdir: (resource) => Promise.resolve([]),
      toCanonicalName: (encoding) => encoding
    }, "textSearchProvider");
  }
  w(query, provider) {
    return new $hyc({ query, provider }, {
      readdir: (resource) => Promise.resolve([]),
      toCanonicalName: (encoding) => encoding
    }, "aiTextSearchProvider");
  }
};
$lyc = __decorate([
  __param(0, $gW),
  __param(1, $7wc),
  __param(2, $wn)
], $lyc);
function $myc(rawQuery) {
  return {
    ...rawQuery,
    // TODO@rob ???
    ...{
      folderQueries: rawQuery.folderQueries && rawQuery.folderQueries.map(reviveFolderQuery),
      extraFileResources: rawQuery.extraFileResources && rawQuery.extraFileResources.map((components) => URI.revive(components))
    }
  };
}
function reviveFolderQuery(rawFolderQuery) {
  return $cu(rawFolderQuery);
}

// out-build/vs/workbench/api/common/extHostWindow.js
var $Xyc_1;
var $Xyc = class $Xyc2 {
  static {
    $Xyc_1 = this;
  }
  static {
    this.a = {
      focused: true,
      active: true
    };
  }
  getState() {
    const state = this.f;
    return {
      get focused() {
        return state.focused;
      },
      get active() {
        return state.active;
      }
    };
  }
  constructor(initData, extHostRpc) {
    this.c = new $ze();
    this.onDidChangeWindowState = this.c.event;
    this.f = $Xyc_1.a;
    if (initData.handle) {
      this.d = $Vi(initData.handle).buffer;
    }
    this.b = extHostRpc.getProxy($xT.MainThreadWindow);
    this.b.$getInitialState().then(({ isFocused, isActive }) => {
      this.onDidChangeWindowProperty("focused", isFocused);
      this.onDidChangeWindowProperty("active", isActive);
    });
  }
  get nativeHandle() {
    return this.d;
  }
  $onDidChangeActiveNativeWindowHandle(handle) {
    this.d = handle ? $Vi(handle).buffer : void 0;
  }
  $onDidChangeWindowFocus(value) {
    this.onDidChangeWindowProperty("focused", value);
  }
  $onDidChangeWindowActive(value) {
    this.onDidChangeWindowProperty("active", value);
  }
  onDidChangeWindowProperty(property, value) {
    if (value === this.f[property]) {
      return;
    }
    this.f = { ...this.f, [property]: value };
    this.c.fire(this.f);
  }
  openUri(stringOrUri, options2) {
    let uriAsString;
    if (typeof stringOrUri === "string") {
      uriAsString = stringOrUri;
      try {
        stringOrUri = URI.parse(stringOrUri);
      } catch (e) {
        return Promise.reject(`Invalid uri - '${stringOrUri}'`);
      }
    }
    if ($vf(stringOrUri.scheme)) {
      return Promise.reject("Invalid scheme - cannot be empty");
    } else if (stringOrUri.scheme === Schemas.command) {
      return Promise.reject(`Invalid scheme '${stringOrUri.scheme}'`);
    }
    return this.b.$openUri(stringOrUri, uriAsString, options2);
  }
  async asExternalUri(uri, options2) {
    if ($vf(uri.scheme)) {
      return Promise.reject("Invalid scheme - cannot be empty");
    }
    const result = await this.b.$asExternalUri(uri, options2);
    return URI.from(result);
  }
};
$Xyc = $Xyc_1 = __decorate([
  __param(0, $wW),
  __param(1, $gW)
], $Xyc);
var $Yyc = $Qk("IExtHostWindow");

// out-build/vs/workbench/api/common/extHostLoggerService.js
var $2yc = class $2yc2 extends $Hn {
  constructor(rpc, initData) {
    super(initData.logLevel, initData.logsLocation, initData.loggers.map((logger) => $cu(logger)));
    this.r = rpc.getProxy($xT.MainThreadLogger);
  }
  $setLogLevel(logLevel, resource) {
    if (resource) {
      this.setLogLevel(URI.revive(resource), logLevel);
    } else {
      this.setLogLevel(logLevel);
    }
  }
  setVisibility(resource, visibility) {
    super.setVisibility(resource, visibility);
    this.r.$setVisibility(resource, visibility);
  }
  s(resource, logLevel, options2) {
    return new Logger(this.r, resource, logLevel, options2);
  }
};
$2yc = __decorate([
  __param(0, $gW),
  __param(1, $wW)
], $2yc);
var Logger = class extends $Cn {
  constructor(s, t, logLevel, loggerOptions) {
    super(loggerOptions?.logLevel === "always");
    this.s = s;
    this.t = t;
    this.n = false;
    this.r = [];
    this.setLevel(logLevel);
    this.s.$createLogger(t, loggerOptions).then(() => {
      this.w(this.r);
      this.n = true;
    });
  }
  m(level, message) {
    const messages = [[level, message]];
    if (this.n) {
      this.w(messages);
    } else {
      this.r.push(...messages);
    }
  }
  w(messages) {
    this.s.$log(this.t, messages);
  }
  flush() {
    this.s.$flush(this.t);
  }
};

// out-build/vs/workbench/api/common/extHostTerminalShellIntegration.js
var $Oyc = $Qk("IExtHostTerminalShellIntegration");
var $Pyc = class $Pyc2 extends $3c {
  constructor(extHostRpc, h) {
    super();
    this.h = h;
    this.b = /* @__PURE__ */ new Map();
    this.c = new $ze();
    this.onDidChangeTerminalShellIntegration = this.c.event;
    this.f = new $ze();
    this.onDidStartTerminalShellExecution = this.f.event;
    this.g = new $ze();
    this.onDidEndTerminalShellExecution = this.g.event;
    this.a = extHostRpc.getProxy($xT.MainThreadTerminalShellIntegration);
    this.B($1c(() => {
      for (const [_, integration] of this.b) {
        integration.dispose();
      }
      this.b.clear();
    }));
  }
  $shellIntegrationChange(instanceId) {
    const terminal = this.h.getTerminalById(instanceId);
    if (!terminal) {
      return;
    }
    const apiTerminal = terminal.value;
    let shellIntegration = this.b.get(instanceId);
    if (!shellIntegration) {
      shellIntegration = new InternalTerminalShellIntegration(terminal.value, this.f);
      this.b.set(instanceId, shellIntegration);
      shellIntegration.store.add(terminal.onWillDispose(() => this.b.get(instanceId)?.dispose()));
      shellIntegration.store.add(shellIntegration.onDidRequestShellExecution((commandLine) => this.a.$executeCommand(instanceId, commandLine)));
      shellIntegration.store.add(shellIntegration.onDidRequestEndExecution((e) => this.g.fire(e)));
      shellIntegration.store.add(shellIntegration.onDidRequestChangeShellIntegration((e) => this.c.fire(e)));
      terminal.shellIntegration = shellIntegration.value;
    }
    this.c.fire({
      terminal: apiTerminal,
      shellIntegration: shellIntegration.value
    });
  }
  $shellExecutionStart(instanceId, commandLineValue, commandLineConfidence, isTrusted, cwd2) {
    if (!this.b.has(instanceId)) {
      this.$shellIntegrationChange(instanceId);
    }
    const commandLine = {
      value: commandLineValue,
      confidence: commandLineConfidence,
      isTrusted
    };
    this.b.get(instanceId)?.startShellExecution(commandLine, URI.revive(cwd2));
  }
  $shellExecutionEnd(instanceId, commandLineValue, commandLineConfidence, isTrusted, exitCode) {
    const commandLine = {
      value: commandLineValue,
      confidence: commandLineConfidence,
      isTrusted
    };
    this.b.get(instanceId)?.endShellExecution(commandLine, exitCode);
  }
  $shellExecutionData(instanceId, data) {
    this.b.get(instanceId)?.emitData(data);
  }
  $cwdChange(instanceId, cwd2) {
    this.b.get(instanceId)?.setCwd(URI.revive(cwd2));
  }
  $closeTerminal(instanceId) {
    this.b.get(instanceId)?.dispose();
    this.b.delete(instanceId);
  }
};
$Pyc = __decorate([
  __param(0, $gW),
  __param(1, $yxc)
], $Pyc);
var InternalTerminalShellIntegration = class extends $3c {
  get currentExecution() {
    return this.a;
  }
  constructor(j, m) {
    super();
    this.j = j;
    this.m = m;
    this.b = false;
    this.store = this.B(new $2c());
    this.f = this.B(new $ze());
    this.onDidRequestChangeShellIntegration = this.f.event;
    this.g = this.B(new $ze());
    this.onDidRequestShellExecution = this.g.event;
    this.h = this.B(new $ze());
    this.onDidRequestEndExecution = this.h.event;
    const that = this;
    this.value = {
      get cwd() {
        return that.c;
      },
      // executeCommand(commandLine: string): vscode.TerminalShellExecution;
      // executeCommand(executable: string, args: string[]): vscode.TerminalShellExecution;
      executeCommand(commandLineOrExecutable, args2) {
        let commandLineValue = commandLineOrExecutable;
        if (args2) {
          for (const arg of args2) {
            const wrapInQuotes = !arg.match(/["'`]/) && arg.match(/\s/);
            if (wrapInQuotes) {
              commandLineValue += ` "${arg}"`;
            } else {
              commandLineValue += ` ${arg}`;
            }
          }
        }
        that.g.fire(commandLineValue);
        const commandLine = {
          value: commandLineValue,
          confidence: TerminalShellExecutionCommandLineConfidence.High,
          isTrusted: true
        };
        const execution = that.startShellExecution(commandLine, that.c, true).value;
        that.b = true;
        return execution;
      }
    };
  }
  startShellExecution(commandLine, cwd2, fireEventInMicrotask) {
    if (this.b && this.a) {
      this.b = false;
    } else {
      if (this.a) {
        this.a.endExecution(void 0);
        this.h.fire({ terminal: this.j, shellIntegration: this.value, execution: this.a.value, exitCode: void 0 });
      }
      const currentExecution = this.a = new InternalTerminalShellExecution(commandLine, cwd2 ?? this.c);
      if (fireEventInMicrotask) {
        queueMicrotask(() => this.m.fire({ terminal: this.j, shellIntegration: this.value, execution: currentExecution.value }));
      } else {
        this.m.fire({ terminal: this.j, shellIntegration: this.value, execution: this.a.value });
      }
    }
    return this.a;
  }
  emitData(data) {
    this.currentExecution?.emitData(data);
  }
  endShellExecution(commandLine, exitCode) {
    if (this.a) {
      this.a.endExecution(commandLine);
      this.h.fire({ terminal: this.j, shellIntegration: this.value, execution: this.a.value, exitCode });
      this.a = void 0;
    }
  }
  setCwd(cwd2) {
    let wasChanged = false;
    if (URI.isUri(this.c)) {
      wasChanged = !URI.isUri(cwd2) || this.c.toString() !== cwd2.toString();
    } else if (this.c !== cwd2) {
      wasChanged = true;
    }
    if (wasChanged) {
      this.c = cwd2;
      this.f.fire({ terminal: this.j, shellIntegration: this.value });
    }
  }
};
var InternalTerminalShellExecution = class {
  constructor(c, cwd2) {
    this.c = c;
    this.cwd = cwd2;
    this.b = false;
    const that = this;
    this.value = {
      get commandLine() {
        return that.c;
      },
      get cwd() {
        return that.cwd;
      },
      read() {
        return that.d();
      }
    };
  }
  d() {
    if (!this.a) {
      if (this.b) {
        return $ji.EMPTY;
      }
      this.a = new ShellExecutionDataStream();
    }
    return this.a.createIterable();
  }
  emitData(data) {
    this.a?.emitData(data);
  }
  endExecution(commandLine) {
    if (commandLine) {
      this.c = commandLine;
    }
    this.a?.endExecution();
    this.a = void 0;
    this.b = true;
  }
};
var ShellExecutionDataStream = class extends $3c {
  constructor() {
    super(...arguments);
    this.b = [];
  }
  createIterable() {
    if (!this.a) {
      this.a = new $Uh();
    }
    const barrier = this.a;
    const iterable = new $ji(async (emitter) => {
      this.b.push(emitter);
      await barrier.wait();
    });
    return iterable;
  }
  emitData(data) {
    for (const emitter of this.b) {
      emitter.emitOne(data);
    }
  }
  endExecution() {
    this.a?.open();
    this.a = void 0;
  }
};

// out-build/vs/workbench/api/common/extHost.common.services.js
$SC(
  $Gxc,
  $Fxc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $xn,
  $2yc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $Lwc,
  $Mwc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $CW,
  $BW,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Vwc,
  $Wwc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Ywc,
  $Zwc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $axc,
  $$wc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $cxc,
  $bxc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Oxc,
  $Pxc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Vxc,
  $Zxc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $2xc,
  $1xc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $rW,
  $qW,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Hxc,
  $Ixc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Pwc,
  $Owc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Ayc,
  $zyc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $kyc,
  $lyc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $vxc,
  $uxc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Nyc,
  $Myc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $yxc,
  $Bxc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Oyc,
  $Pyc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $6Sb,
  $7Sb,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Yyc,
  $Xyc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $0wc,
  $9wc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Dxc,
  $Cxc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $AW,
  $xW,
  0
  /* InstantiationType.Eager */
);
$SC(
  $mxc,
  $nxc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Txc,
  $Uxc,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/api/node/extHostTerminalService.js
var $8yc = class $8yc2 extends $Axc {
  constructor(extHostCommands, extHostRpc) {
    super(true, extHostCommands, extHostRpc);
  }
  createTerminal(name, shellPath, shellArgs) {
    return this.createTerminalFromOptions({ name, shellPath, shellArgs });
  }
  createTerminalFromOptions(options2, internalOptions) {
    const terminal = new $zxc(this.a, $ps(), options2, options2.name);
    this.f.push(terminal);
    terminal.create(options2, this.S(options2, internalOptions));
    return terminal.value;
  }
};
$8yc = __decorate([
  __param(0, $CW),
  __param(1, $gW)
], $8yc);

// out-build/vs/base/node/processes.js
import { promises as promises3 } from "fs";

// out-build/vs/base/common/processes.js
var Source;
(function(Source2) {
  Source2[Source2["stdout"] = 0] = "stdout";
  Source2[Source2["stderr"] = 1] = "stderr";
})(Source || (Source = {}));
var TerminateResponseCode;
(function(TerminateResponseCode2) {
  TerminateResponseCode2[TerminateResponseCode2["Success"] = 0] = "Success";
  TerminateResponseCode2[TerminateResponseCode2["Unknown"] = 1] = "Unknown";
  TerminateResponseCode2[TerminateResponseCode2["AccessDenied"] = 2] = "AccessDenied";
  TerminateResponseCode2[TerminateResponseCode2["ProcessNotFound"] = 3] = "ProcessNotFound";
})(TerminateResponseCode || (TerminateResponseCode = {}));
function $Ex(env2, ...preserve) {
  const set = preserve.reduce((set2, key) => {
    set2[key] = true;
    return set2;
  }, {});
  const keysToRemove = [
    /^ELECTRON_.+$/,
    /^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,
    /^SNAP(|_.*)$/,
    /^GDK_PIXBUF_.+$/
  ];
  const envKeys = Object.keys(env2);
  envKeys.filter((key) => !set[key]).forEach((envKey) => {
    for (let i = 0; i < keysToRemove.length; i++) {
      if (envKey.search(keysToRemove[i]) !== -1) {
        delete env2[envKey];
        break;
      }
    }
  });
}
function $Fx(env2) {
  if (!env2) {
    return;
  }
  delete env2["DEBUG"];
  if ($n) {
    delete env2["LD_PRELOAD"];
  }
}

// out-build/vs/base/node/processes.js
function $Sx(env2 = env) {
  return env2["comspec"] || "cmd.exe";
}
function $Tx(childProcess2) {
  let msgQueue = [];
  let useQueue = false;
  const send = function(msg) {
    if (useQueue) {
      msgQueue.push(msg);
      return;
    }
    const result = childProcess2.send(msg, (error) => {
      if (error) {
        console.error(error);
      }
      useQueue = false;
      if (msgQueue.length > 0) {
        const msgQueueCopy = msgQueue.slice(0);
        msgQueue = [];
        msgQueueCopy.forEach((entry) => send(entry));
      }
    });
    if (!result || $l) {
      useQueue = true;
    }
  };
  return { send };
}
var win32;
(function(win322) {
  async function findExecutable(command, cwd2, paths) {
    if ($mc(command)) {
      return command;
    }
    if (cwd2 === void 0) {
      cwd2 = cwd();
    }
    const dir = $qc(command);
    if (dir !== ".") {
      return $nc(cwd2, command);
    }
    if (paths === void 0 && $zg(env["PATH"])) {
      paths = env["PATH"].split($xc);
    }
    if (paths === void 0 || paths.length === 0) {
      return $nc(cwd2, command);
    }
    async function fileExists(path) {
      if (await Promises2.exists(path)) {
        let statValue;
        try {
          statValue = await promises3.stat(path);
        } catch (e) {
          if (e.message.startsWith("EACCES")) {
            statValue = await promises3.lstat(path);
          }
        }
        return statValue ? !statValue.isDirectory() : false;
      }
      return false;
    }
    for (const pathEntry of paths) {
      let fullPath;
      if ($mc(pathEntry)) {
        fullPath = $nc(pathEntry, command);
      } else {
        fullPath = $nc(cwd2, pathEntry, command);
      }
      if (await fileExists(fullPath)) {
        return fullPath;
      }
      let withExtension = fullPath + ".com";
      if (await fileExists(withExtension)) {
        return withExtension;
      }
      withExtension = fullPath + ".exe";
      if (await fileExists(withExtension)) {
        return withExtension;
      }
    }
    return $nc(cwd2, command);
  }
  win322.findExecutable = findExecutable;
})(win32 || (win32 = {}));

// out-build/vs/workbench/api/node/extHostTask.js
import { homedir } from "os";
var $9yc = class $9yc2 extends $Lyc {
  constructor(extHostRpc, initData, C, editorService, configurationService, extHostTerminalService, logService, deprecationService, D) {
    super(extHostRpc, initData, C, editorService, configurationService, extHostTerminalService, logService, deprecationService);
    this.C = C;
    this.D = D;
    if (initData.remote.isRemote && initData.remote.authority) {
      this.registerTaskSystem(Schemas.vscodeRemote, {
        scheme: Schemas.vscodeRemote,
        authority: initData.remote.authority,
        platform: process.platform
      });
    } else {
      this.registerTaskSystem(Schemas.file, {
        scheme: Schemas.file,
        authority: "",
        platform: process.platform
      });
    }
    this.a.$registerSupportedExecutions(true, true, true);
  }
  async executeTask(extension, task) {
    const tTask = task;
    if (!task.execution && tTask._id === void 0) {
      throw new Error("Tasks to execute must include an execution");
    }
    if (tTask._id !== void 0) {
      const handleDto = TaskHandleDTO.from(tTask, this.C);
      const executionDTO = await this.a.$getTaskExecution(handleDto);
      if (executionDTO.task === void 0) {
        throw new Error("Task from execution DTO is undefined");
      }
      const execution = await this.z(executionDTO, task);
      this.a.$executeTask(handleDto).catch(() => {
      });
      return execution;
    } else {
      const dto = TaskDTO.from(task, extension);
      if (dto === void 0) {
        return Promise.reject(new Error("Task is not valid"));
      }
      if (CustomExecutionDTO.is(dto.execution)) {
        await this.y(dto, task, false);
      }
      const execution = await this.z(await this.a.$getTaskExecution(dto), task);
      this.a.$executeTask(dto).catch(() => {
      });
      return execution;
    }
  }
  v(validTypes, taskIdPromises, handler, value) {
    const taskDTOs = [];
    if (value) {
      for (const task of value) {
        this.A(task, handler);
        if (!task.definition || !validTypes[task.definition.type]) {
          this.f.warn(`The task [${task.source}, ${task.name}] uses an undefined task type. The task will be ignored in the future.`);
        }
        const taskDTO = TaskDTO.from(task, handler.extension);
        if (taskDTO) {
          taskDTOs.push(taskDTO);
          if (CustomExecutionDTO.is(taskDTO.execution)) {
            taskIdPromises.push(this.y(taskDTO, task, true));
          }
        }
      }
    }
    return {
      tasks: taskDTOs,
      extension: handler.extension
    };
  }
  async w(resolvedTaskDTO) {
    return resolvedTaskDTO;
  }
  async G(workspaceFolders) {
    let folder = workspaceFolders && workspaceFolders.length > 0 ? workspaceFolders[0] : void 0;
    if (!folder) {
      const userhome = URI.file(homedir());
      folder = new $$k({ uri: userhome, name: $sh(userhome), index: 0 });
    }
    return {
      uri: folder.uri,
      name: folder.name,
      index: folder.index,
      toResource: () => {
        throw new Error("Not implemented");
      }
    };
  }
  async $resolveVariables(uriComponents, toResolve) {
    const uri = URI.revive(uriComponents);
    const result = {
      process: void 0,
      variables: /* @__PURE__ */ Object.create(null)
    };
    const workspaceFolder = await this.b.resolveWorkspaceFolder(uri);
    const workspaceFolders = await this.b.getWorkspaceFolders2() ?? [];
    const resolver = await this.D.getResolver();
    const ws = workspaceFolder ? {
      uri: workspaceFolder.uri,
      name: workspaceFolder.name,
      index: workspaceFolder.index,
      toResource: () => {
        throw new Error("Not implemented");
      }
    } : await this.G(workspaceFolders);
    for (const variable of toResolve.variables) {
      result.variables[variable] = await resolver.resolveAsync(ws, variable);
    }
    if (toResolve.process !== void 0) {
      let paths = void 0;
      if (toResolve.process.path !== void 0) {
        paths = toResolve.process.path.split($xc);
        for (let i = 0; i < paths.length; i++) {
          paths[i] = await resolver.resolveAsync(ws, paths[i]);
        }
      }
      result.process = await win32.findExecutable(await resolver.resolveAsync(ws, toResolve.process.name), toResolve.process.cwd !== void 0 ? await resolver.resolveAsync(ws, toResolve.process.cwd) : void 0, paths);
    }
    return result;
  }
  async $jsonTasksSupported() {
    return true;
  }
  async $findExecutable(command, cwd2, paths) {
    return win32.findExecutable(command, cwd2, paths);
  }
};
$9yc = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $0wc),
  __param(3, $rW),
  __param(4, $axc),
  __param(5, $yxc),
  __param(6, $wn),
  __param(7, $Lwc),
  __param(8, $Txc)
], $9yc);

// out-build/vs/platform/externalTerminal/node/externalTerminalService.js
import * as cp from "child_process";

// out-build/vs/platform/externalTerminal/common/externalTerminal.js
var $9x = $Qk("externalTerminal");
var $0x = "Terminal.app";

// out-build/vs/platform/externalTerminal/node/externalTerminalService.js
var TERMINAL_TITLE = localize(1896, null);
var ExternalTerminalService = class {
  async getDefaultTerminalForPlatforms() {
    return {
      windows: $_x.getDefaultTerminalWindows(),
      linux: await $by.getDefaultTerminalLinuxReady(),
      osx: "xterm"
    };
  }
};
var $_x = class _$_x extends ExternalTerminalService {
  static {
    this.b = "cmd.exe";
  }
  openTerminal(configuration, cwd2) {
    return this.spawnTerminal(cp, configuration, $Sx(), cwd2);
  }
  spawnTerminal(spawner, configuration, command, cwd2) {
    const exec3 = configuration.windowsExec || _$_x.getDefaultTerminalWindows();
    if (cwd2 && cwd2[1] === ":") {
      cwd2 = cwd2[0].toUpperCase() + cwd2.substr(1);
    }
    const basename = $rc(exec3, ".exe").toLowerCase();
    if (basename === "cmder") {
      spawner.spawn(exec3, cwd2 ? [cwd2] : void 0);
      return Promise.resolve(void 0);
    }
    const cmdArgs = ["/c", "start", "/wait"];
    if (exec3.indexOf(" ") >= 0) {
      cmdArgs.push(exec3);
    }
    cmdArgs.push(exec3);
    if (basename === "wt") {
      cmdArgs.push("-d .");
    }
    return new Promise((c, e) => {
      const env2 = getSanitizedEnvironment(process);
      const child = spawner.spawn(command, cmdArgs, { cwd: cwd2, env: env2, detached: true });
      child.on("error", e);
      child.on("exit", () => c());
    });
  }
  async runInTerminal(title, dir, args2, envVars, settings) {
    const exec3 = "windowsExec" in settings && settings.windowsExec ? settings.windowsExec : _$_x.getDefaultTerminalWindows();
    const wt = await _$_x.f();
    return new Promise((resolve, reject) => {
      const title2 = `"${dir} - ${TERMINAL_TITLE}"`;
      const command = `"${args2.join('" "')}" & pause`;
      const env2 = Object.assign({}, getSanitizedEnvironment(process), envVars);
      Object.keys(env2).filter((v) => env2[v] === null).forEach((key) => delete env2[key]);
      const options2 = {
        cwd: dir,
        env: env2,
        windowsVerbatimArguments: true
      };
      let spawnExec;
      let cmdArgs;
      if ($rc(exec3, ".exe") === "wt") {
        spawnExec = exec3;
        cmdArgs = ["-d", ".", _$_x.b, "/c", command];
      } else if (wt) {
        spawnExec = wt;
        cmdArgs = ["-d", ".", exec3, "/c", command];
      } else {
        spawnExec = _$_x.b;
        cmdArgs = ["/c", "start", title2, "/wait", exec3, "/c", `"${command}"`];
      }
      const cmd = cp.spawn(spawnExec, cmdArgs, options2);
      cmd.on("error", (err) => {
        reject(improveError(err));
      });
      resolve(void 0);
    });
  }
  static getDefaultTerminalWindows() {
    if (!_$_x.d) {
      const isWoW64 = !!process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432");
      _$_x.d = `${process.env.windir ? process.env.windir : "C:\\Windows"}\\${isWoW64 ? "Sysnative" : "System32"}\\cmd.exe`;
    }
    return _$_x.d;
  }
  static async f() {
    try {
      const wtPath = await win32.findExecutable("wt");
      return await Promises2.exists(wtPath) ? wtPath : void 0;
    } catch {
      return void 0;
    }
  }
};
__decorate([
  $0t
], $_x, "f", null);
var $ay = class _$ay extends ExternalTerminalService {
  static {
    this.b = "/usr/bin/osascript";
  }
  // osascript is the AppleScript interpreter on OS X
  openTerminal(configuration, cwd2) {
    return this.spawnTerminal(cp, configuration, cwd2);
  }
  runInTerminal(title, dir, args2, envVars, settings) {
    const terminalApp = settings.osxExec || $0x;
    return new Promise((resolve, reject) => {
      if (terminalApp === $0x || terminalApp === "iTerm.app") {
        const script = terminalApp === $0x ? "TerminalHelper" : "iTermHelper";
        const scriptpath = $ih.asFileUri(`vs/workbench/contrib/externalTerminal/node/${script}.scpt`).fsPath;
        const osaArgs = [
          scriptpath,
          "-t",
          title || TERMINAL_TITLE,
          "-w",
          dir
        ];
        for (const a of args2) {
          osaArgs.push("-a");
          osaArgs.push(a);
        }
        if (envVars) {
          const env2 = Object.assign({}, getSanitizedEnvironment(process), envVars);
          for (const key in env2) {
            const value = env2[key];
            if (value === null) {
              osaArgs.push("-u");
              osaArgs.push(key);
            } else {
              osaArgs.push("-e");
              osaArgs.push(`${key}=${value}`);
            }
          }
        }
        let stderr = "";
        const osa = cp.spawn(_$ay.b, osaArgs);
        osa.on("error", (err) => {
          reject(improveError(err));
        });
        osa.stderr.on("data", (data) => {
          stderr += data.toString();
        });
        osa.on("exit", (code) => {
          if (code === 0) {
            resolve(void 0);
          } else {
            if (stderr) {
              const lines = stderr.split("\n", 1);
              reject(new Error(lines[0]));
            } else {
              reject(new Error(localize(1897, null, script, code)));
            }
          }
        });
      } else {
        reject(new Error(localize(1898, null, terminalApp)));
      }
    });
  }
  spawnTerminal(spawner, configuration, cwd2) {
    const terminalApp = configuration.osxExec || $0x;
    return new Promise((c, e) => {
      const args2 = ["-a", terminalApp];
      if (cwd2) {
        args2.push(cwd2);
      }
      const env2 = getSanitizedEnvironment(process);
      const child = spawner.spawn("/usr/bin/open", args2, { cwd: cwd2, env: env2 });
      child.on("error", e);
      child.on("exit", () => c());
    });
  }
};
var $by = class _$by extends ExternalTerminalService {
  static {
    this.b = localize(1899, null);
  }
  openTerminal(configuration, cwd2) {
    return this.spawnTerminal(cp, configuration, cwd2);
  }
  runInTerminal(title, dir, args2, envVars, settings) {
    const execPromise = settings.linuxExec ? Promise.resolve(settings.linuxExec) : _$by.getDefaultTerminalLinuxReady();
    return new Promise((resolve, reject) => {
      const termArgs = [];
      execPromise.then((exec3) => {
        if (exec3.indexOf("gnome-terminal") >= 0) {
          termArgs.push("-x");
        } else {
          termArgs.push("-e");
        }
        termArgs.push("bash");
        termArgs.push("-c");
        const bashCommand = `${quote(args2)}; echo; read -p "${_$by.b}" -n1;`;
        termArgs.push(`''${bashCommand}''`);
        const env2 = Object.assign({}, getSanitizedEnvironment(process), envVars);
        Object.keys(env2).filter((v) => env2[v] === null).forEach((key) => delete env2[key]);
        const options2 = {
          cwd: dir,
          env: env2
        };
        let stderr = "";
        const cmd = cp.spawn(exec3, termArgs, options2);
        cmd.on("error", (err) => {
          reject(improveError(err));
        });
        cmd.stderr.on("data", (data) => {
          stderr += data.toString();
        });
        cmd.on("exit", (code) => {
          if (code === 0) {
            resolve(void 0);
          } else {
            if (stderr) {
              const lines = stderr.split("\n", 1);
              reject(new Error(lines[0]));
            } else {
              reject(new Error(localize(1900, null, exec3, code)));
            }
          }
        });
      });
    });
  }
  static async getDefaultTerminalLinuxReady() {
    if (!_$by.d) {
      if (!$n) {
        _$by.d = Promise.resolve("xterm");
      } else {
        const isDebian = await Promises2.exists("/etc/debian_version");
        _$by.d = new Promise((r) => {
          if (isDebian) {
            r("x-terminal-emulator");
          } else if (process.env.DESKTOP_SESSION === "gnome" || process.env.DESKTOP_SESSION === "gnome-classic") {
            r("gnome-terminal");
          } else if (process.env.DESKTOP_SESSION === "kde-plasma") {
            r("konsole");
          } else if (process.env.COLORTERM) {
            r(process.env.COLORTERM);
          } else if (process.env.TERM) {
            r(process.env.TERM);
          } else {
            r("xterm");
          }
        });
      }
    }
    return _$by.d;
  }
  spawnTerminal(spawner, configuration, cwd2) {
    const execPromise = configuration.linuxExec ? Promise.resolve(configuration.linuxExec) : _$by.getDefaultTerminalLinuxReady();
    return new Promise((c, e) => {
      execPromise.then((exec3) => {
        const env2 = getSanitizedEnvironment(process);
        const child = spawner.spawn(exec3, [], { cwd: cwd2, env: env2 });
        child.on("error", e);
        child.on("exit", () => c());
      });
    });
  }
};
function getSanitizedEnvironment(process2) {
  const env2 = { ...process2.env };
  $Ex(env2);
  return env2;
}
function improveError(err) {
  if ("errno" in err && err["errno"] === "ENOENT" && "path" in err && typeof err["path"] === "string") {
    return new Error(localize(1901, null, err["path"]));
  }
  return err;
}
function quote(args2) {
  let r = "";
  for (const a of args2) {
    if (a.indexOf(" ") >= 0) {
      r += '"' + a + '"';
    } else {
      r += a;
    }
    r += " ";
  }
  return r;
}

// out-build/vs/platform/sign/common/abstractSignService.js
var $OC = class _$OC {
  constructor() {
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.a = 1;
  }
  async createNewMessage(value) {
    try {
      const validator = await this.c();
      if (validator) {
        const id2 = String(_$OC.a++);
        this.b.set(id2, validator);
        return {
          id: id2,
          data: validator.createNewMessage(value)
        };
      }
    } catch (e) {
    }
    return { id: "", data: value };
  }
  async validate(message, value) {
    if (!message.id) {
      return true;
    }
    const validator = this.b.get(message.id);
    if (!validator) {
      return false;
    }
    this.b.delete(message.id);
    try {
      return validator.validate(value) === "ok";
    } catch (e) {
      return false;
    } finally {
      validator.dispose?.();
    }
  }
  async sign(value) {
    try {
      return await this.d(value);
    } catch (e) {
    }
    return value;
  }
};

// out-build/vs/platform/sign/node/signService.js
var $PC = class extends $OC {
  c() {
    return this.h().then((vsda) => new vsda.validator());
  }
  d(arg) {
    return this.h().then((vsda) => new vsda.signer().sign(arg));
  }
  async h() {
    const mod = "vsda";
    const { default: vsda } = await import(mod);
    return vsda;
  }
};

// out-build/vs/workbench/contrib/debug/node/debugAdapter.js
import * as cp2 from "child_process";
import * as net from "net";
var $0yc = class _$0yc extends $xOb {
  static {
    this.b = "\r\n\r\n";
  }
  static {
    this.i = /\r?\n/;
  }
  static {
    this.l = /: */;
  }
  constructor() {
    super();
    this.r = Buffer.allocUnsafe(0);
    this.t = -1;
  }
  v(readable, writable) {
    this.p = writable;
    this.r = Buffer.allocUnsafe(0);
    this.t = -1;
    readable.on("data", (data) => this.x(data));
  }
  sendMessage(message) {
    if (this.p) {
      const json = JSON.stringify(message);
      this.p.write(`Content-Length: ${Buffer.byteLength(json, "utf8")}${_$0yc.b}${json}`, "utf8");
    }
  }
  x(data) {
    this.r = Buffer.concat([this.r, data]);
    while (true) {
      if (this.t >= 0) {
        if (this.r.length >= this.t) {
          const message = this.r.toString("utf8", 0, this.t);
          this.r = this.r.slice(this.t);
          this.t = -1;
          if (message.length > 0) {
            try {
              this.acceptMessage(JSON.parse(message));
            } catch (e) {
              this.n.fire(new Error((e.message || e) + "\n" + message));
            }
          }
          continue;
        }
      } else {
        const idx = this.r.indexOf(_$0yc.b);
        if (idx !== -1) {
          const header = this.r.toString("utf8", 0, idx);
          const lines = header.split(_$0yc.i);
          for (const h of lines) {
            const kvPair = h.split(_$0yc.l);
            if (kvPair[0] === "Content-Length") {
              this.t = Number(kvPair[1]);
            }
          }
          this.r = this.r.slice(idx + _$0yc.b.length);
          continue;
        }
      }
      break;
    }
  }
};
var $$yc = class extends $0yc {
  startSession() {
    return new Promise((resolve, reject) => {
      let connected = false;
      this.y = this.z(() => {
        this.v(this.y, this.y);
        resolve();
        connected = true;
      });
      this.y.on("close", () => {
        if (connected) {
          this.n.fire(new Error("connection closed"));
        } else {
          reject(new Error("connection closed"));
        }
      });
      this.y.on("error", (error) => {
        if (connected) {
          this.n.fire(error);
        } else {
          reject(error);
        }
      });
    });
  }
  async stopSession() {
    await this.w();
    if (this.y) {
      this.y.end();
      this.y = void 0;
    }
  }
};
var $_yc = class extends $$yc {
  constructor(A) {
    super();
    this.A = A;
  }
  z(connectionListener) {
    return net.createConnection(this.A.port, this.A.host || "127.0.0.1", connectionListener);
  }
};
var $azc = class extends $$yc {
  constructor(A) {
    super();
    this.A = A;
  }
  z(connectionListener) {
    return net.createConnection(this.A.path, connectionListener);
  }
};
var $bzc = class _$bzc extends $0yc {
  constructor(z, A) {
    super();
    this.z = z;
    this.A = A;
  }
  async startSession() {
    const command = this.z.command;
    const args2 = this.z.args;
    const options2 = this.z.options || {};
    try {
      if (command) {
        if ($mc(command)) {
          const commandExists = await Promises2.exists(command);
          if (!commandExists) {
            throw new Error(localize(6240, null, command));
          }
        } else {
          if (command.indexOf("/") < 0 && command.indexOf("\\") < 0) {
          }
        }
      } else {
        throw new Error(localize(6241, null, this.A));
      }
      let env2 = process.env;
      if (options2.env && Object.keys(options2.env).length > 0) {
        env2 = $Ov($Lv(process.env), options2.env);
      }
      if (command === "node") {
        if (Array.isArray(args2) && args2.length > 0) {
          const isElectron = !!process.env["ELECTRON_RUN_AS_NODE"] || !!process.versions["electron"];
          const forkOptions = {
            env: env2,
            execArgv: isElectron ? ["-e", "delete process.env.ELECTRON_RUN_AS_NODE;require(process.argv[1])"] : [],
            silent: true
          };
          if (options2.cwd) {
            forkOptions.cwd = options2.cwd;
          }
          const child = cp2.fork(args2[0], args2.slice(1), forkOptions);
          if (!child.pid) {
            throw new Error(localize(6242, null, args2[0]));
          }
          this.y = child;
        } else {
          throw new Error(localize(6243, null));
        }
      } else {
        let spawnCommand = command;
        let spawnArgs = args2;
        const spawnOptions = {
          env: env2
        };
        if (options2.cwd) {
          spawnOptions.cwd = options2.cwd;
        }
        if ($l && (command.endsWith(".bat") || command.endsWith(".cmd"))) {
          spawnOptions.shell = true;
          spawnCommand = `"${command}"`;
          spawnArgs = args2.map((a) => {
            a = a.replace(/"/g, '\\"');
            return `"${a}"`;
          });
        }
        this.y = cp2.spawn(spawnCommand, spawnArgs, spawnOptions);
      }
      this.y.on("error", (err) => {
        this.n.fire(err);
      });
      this.y.on("exit", (code, signal) => {
        this.o.fire(code);
      });
      this.y.stdout.on("close", () => {
        this.n.fire(new Error("read error"));
      });
      this.y.stdout.on("error", (error) => {
        this.n.fire(error);
      });
      this.y.stdin.on("error", (error) => {
        this.n.fire(error);
      });
      this.y.stderr.resume();
      this.v(this.y.stdout, this.y.stdin);
    } catch (err) {
      this.n.fire(err);
    }
  }
  async stopSession() {
    if (!this.y) {
      return Promise.resolve(void 0);
    }
    await this.w();
    if ($l) {
      return new Promise((c, e) => {
        const killer = cp2.exec(`taskkill /F /T /PID ${this.y.pid}`, function(err, stdout, stderr) {
          if (err) {
            return e(err);
          }
        });
        killer.on("exit", c);
        killer.on("error", e);
      });
    } else {
      this.y.kill("SIGTERM");
      return Promise.resolve(void 0);
    }
  }
  static B(platformContribution, extensionFolderPath) {
    if (!platformContribution) {
      return void 0;
    }
    const result = /* @__PURE__ */ Object.create(null);
    if (platformContribution.runtime) {
      if (platformContribution.runtime.indexOf("./") === 0) {
        result.runtime = $nc(extensionFolderPath, platformContribution.runtime);
      } else {
        result.runtime = platformContribution.runtime;
      }
    }
    if (platformContribution.runtimeArgs) {
      result.runtimeArgs = platformContribution.runtimeArgs;
    }
    if (platformContribution.program) {
      if (!$mc(platformContribution.program)) {
        result.program = $nc(extensionFolderPath, platformContribution.program);
      } else {
        result.program = platformContribution.program;
      }
    }
    if (platformContribution.args) {
      result.args = platformContribution.args;
    }
    const contribution = platformContribution;
    if (contribution.win) {
      result.win = _$bzc.B(contribution.win, extensionFolderPath);
    }
    if (contribution.winx86) {
      result.winx86 = _$bzc.B(contribution.winx86, extensionFolderPath);
    }
    if (contribution.windows) {
      result.windows = _$bzc.B(contribution.windows, extensionFolderPath);
    }
    if (contribution.osx) {
      result.osx = _$bzc.B(contribution.osx, extensionFolderPath);
    }
    if (contribution.linux) {
      result.linux = _$bzc.B(contribution.linux, extensionFolderPath);
    }
    return result;
  }
  static platformAdapterExecutable(extensionDescriptions, debugType) {
    let result = /* @__PURE__ */ Object.create(null);
    debugType = debugType.toLowerCase();
    for (const ed of extensionDescriptions) {
      if (ed.contributes) {
        const debuggers = ed.contributes["debuggers"];
        if (debuggers && debuggers.length > 0) {
          debuggers.filter((dbg) => typeof dbg.type === "string" && $1f(dbg.type, debugType)).forEach((dbg) => {
            const extractedDbg = _$bzc.B(dbg, ed.extensionLocation.fsPath);
            result = $Ov(result, extractedDbg, ed.isBuiltin);
          });
        }
      }
    }
    let platformInfo;
    if ($l && !process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")) {
      platformInfo = result.winx86 || result.win || result.windows;
    } else if ($l) {
      platformInfo = result.win || result.windows;
    } else if ($m) {
      platformInfo = result.osx;
    } else if ($n) {
      platformInfo = result.linux;
    }
    platformInfo = platformInfo || result;
    const program = platformInfo.program || result.program;
    const args2 = platformInfo.args || result.args;
    const runtime = platformInfo.runtime || result.runtime;
    const runtimeArgs = platformInfo.runtimeArgs || result.runtimeArgs;
    if (runtime) {
      return {
        type: "executable",
        command: runtime,
        args: (runtimeArgs || []).concat(typeof program === "string" ? [program] : []).concat(args2 || [])
      };
    } else if (program) {
      return {
        type: "executable",
        command: program,
        args: args2 || []
      };
    }
    return void 0;
  }
};

// out-build/vs/workbench/contrib/debug/node/terminals.js
import * as cp3 from "child_process";
function spawnAsPromised(command, args2) {
  return new Promise((resolve, reject) => {
    let stdout = "";
    const child = cp3.spawn(command, args2);
    if (child.pid) {
      child.stdout.on("data", (data) => {
        stdout += data.toString();
      });
    }
    child.on("error", (err) => {
      reject(err);
    });
    child.on("close", (code) => {
      resolve(stdout);
    });
  });
}
async function $czc(processId) {
  if (processId) {
    if ($l) {
      const windowsProcessTree = await import("@vscode/windows-process-tree");
      return new Promise((resolve) => {
        windowsProcessTree.getProcessTree(processId, (processTree) => {
          resolve(!!processTree && processTree.children.length > 0);
        });
      });
    } else {
      return spawnAsPromised("/usr/bin/pgrep", ["-lP", String(processId)]).then((stdout) => {
        const r = stdout.trim();
        if (r.length === 0 || r.indexOf(" tmux") >= 0) {
          return false;
        } else {
          return true;
        }
      }, (error) => {
        return true;
      });
    }
  }
  return Promise.resolve(true);
}
var ShellType;
(function(ShellType2) {
  ShellType2[ShellType2["cmd"] = 0] = "cmd";
  ShellType2[ShellType2["powershell"] = 1] = "powershell";
  ShellType2[ShellType2["bash"] = 2] = "bash";
})(ShellType || (ShellType = {}));
function $dzc(shell, args2, argsCanBeInterpretedByShell, cwd2, env2) {
  shell = shell.trim().toLowerCase();
  let shellType;
  if (shell.indexOf("powershell") >= 0 || shell.indexOf("pwsh") >= 0) {
    shellType = 1;
  } else if (shell.indexOf("cmd.exe") >= 0) {
    shellType = 0;
  } else if (shell.indexOf("bash") >= 0) {
    shellType = 2;
  } else if ($l) {
    shellType = 0;
  } else {
    shellType = 2;
  }
  let quote2;
  let command = " ";
  switch (shellType) {
    case 1:
      quote2 = (s) => {
        s = s.replace(/\'/g, "''");
        if (s.length > 0 && s.charAt(s.length - 1) === "\\") {
          return `'${s}\\'`;
        }
        return `'${s}'`;
      };
      if (cwd2) {
        const driveLetter = $6g(cwd2);
        if (driveLetter) {
          command += `${driveLetter}:; `;
        }
        command += `cd ${quote2(cwd2)}; `;
      }
      if (env2) {
        for (const key in env2) {
          const value = env2[key];
          if (value === null) {
            command += `Remove-Item env:${key}; `;
          } else {
            command += `\${env:${key}}='${value}'; `;
          }
        }
      }
      if (args2.length > 0) {
        const arg = args2.shift();
        const cmd = argsCanBeInterpretedByShell ? arg : quote2(arg);
        command += cmd[0] === "'" ? `& ${cmd} ` : `${cmd} `;
        for (const a of args2) {
          command += a === "<" || a === ">" || argsCanBeInterpretedByShell ? a : quote2(a);
          command += " ";
        }
      }
      break;
    case 0:
      quote2 = (s) => {
        s = s.replace(/\"/g, '""');
        s = s.replace(/([><!^&|])/g, "^$1");
        return ' "'.split("").some((char) => s.includes(char)) || s.length === 0 ? `"${s}"` : s;
      };
      if (cwd2) {
        const driveLetter = $6g(cwd2);
        if (driveLetter) {
          command += `${driveLetter}: && `;
        }
        command += `cd ${quote2(cwd2)} && `;
      }
      if (env2) {
        command += 'cmd /C "';
        for (const key in env2) {
          let value = env2[key];
          if (value === null) {
            command += `set "${key}=" && `;
          } else {
            value = value.replace(/[&^|<>]/g, (s) => `^${s}`);
            command += `set "${key}=${value}" && `;
          }
        }
      }
      for (const a of args2) {
        command += a === "<" || a === ">" || argsCanBeInterpretedByShell ? a : quote2(a);
        command += " ";
      }
      if (env2) {
        command += '"';
      }
      break;
    case 2: {
      quote2 = (s) => {
        s = s.replace(/(["'\\\$!><#()\[\]*&^| ;{}?`])/g, "\\$1");
        return s.length === 0 ? `""` : s;
      };
      const hardQuote = (s) => {
        return /[^\w@%\/+=,.:^-]/.test(s) ? `'${s.replace(/'/g, "'\\''")}'` : s;
      };
      if (cwd2) {
        command += `cd ${quote2(cwd2)} ; `;
      }
      if (env2) {
        command += "/usr/bin/env";
        for (const key in env2) {
          const value = env2[key];
          if (value === null) {
            command += ` -u ${hardQuote(key)}`;
          } else {
            command += ` ${hardQuote(`${key}=${value}`)}`;
          }
        }
        command += " ";
      }
      for (const a of args2) {
        command += a === "<" || a === ">" || argsCanBeInterpretedByShell ? a : quote2(a);
        command += " ";
      }
      break;
    }
  }
  return command;
}

// out-build/vs/workbench/api/node/extHostDebugService.js
var $ezc = class $ezc2 extends $Wxc {
  constructor(extHostRpcService, workspaceService, extensionService, configurationService, Fb, Gb, editorTabs, variableResolver, commands, testing) {
    super(extHostRpcService, workspaceService, extensionService, configurationService, editorTabs, variableResolver, commands, testing);
    this.Fb = Fb;
    this.Gb = Gb;
    this.Db = new DebugTerminalCollection();
  }
  ib(adapter, session) {
    if (adapter instanceof $IU) {
      return new $bzc(this.lb(adapter), session.type);
    } else if (adapter instanceof $JU) {
      return new $_yc(this.mb(adapter));
    } else if (adapter instanceof $KU) {
      return new $azc(this.nb(adapter));
    } else {
      return super.ib(adapter, session);
    }
  }
  vb(session, extensionRegistry) {
    const dae = $bzc.platformAdapterExecutable(extensionRegistry.getAllExtensionDescriptions(), session.type);
    if (dae) {
      return new $IU(dae.command, dae.args, dae.options);
    }
    return void 0;
  }
  jb() {
    return new $PC();
  }
  async $runInTerminal(args2, sessionId) {
    if (args2.kind === "integrated") {
      if (!this.Eb) {
        this.Eb = this.B(this.Fb.onDidCloseTerminal((terminal2) => {
          this.Db.onTerminalClosed(terminal2);
        }));
      }
      const configProvider = await this.ab.getConfigProvider();
      const shell = this.Fb.getDefaultShell(true);
      const shellArgs = this.Fb.getDefaultShellArgs(true);
      const terminalName = args2.title || localize(2785, null);
      const shellConfig = JSON.stringify({ shell, shellArgs });
      let terminal = await this.Db.checkout(shellConfig, terminalName);
      let cwdForPrepareCommand;
      let giveShellTimeToInitialize = false;
      if (!terminal) {
        const options2 = {
          shellPath: shell,
          shellArgs,
          cwd: args2.cwd,
          name: terminalName,
          iconPath: new $AU("debug")
        };
        giveShellTimeToInitialize = true;
        terminal = this.Fb.createTerminalFromOptions(options2, {
          isFeatureTerminal: true,
          // Since debug termnials are REPLs, we want shell integration to be enabled.
          // Ignore isFeatureTerminal when evaluating shell integration enablement.
          forceShellIntegration: true,
          useShellEnvironment: true
        });
        this.Db.insert(terminal, shellConfig);
      } else {
        cwdForPrepareCommand = args2.cwd;
      }
      terminal.show(true);
      const shellProcessId = await terminal.processId;
      if (giveShellTimeToInitialize) {
        let Timing;
        (function(Timing2) {
          Timing2[Timing2["DataDebounce"] = 500] = "DataDebounce";
          Timing2[Timing2["MaxDelay"] = 5e3] = "MaxDelay";
        })(Timing || (Timing = {}));
        const ds = new $2c();
        await new Promise((resolve) => {
          const scheduler = ds.add(new $8h(
            resolve,
            500
            /* Timing.DataDebounce */
          ));
          ds.add(this.Fb.onDidWriteTerminalData((e) => {
            if (e.terminal === terminal) {
              scheduler.schedule();
            }
          }));
          ds.add(this.Gb.onDidChangeTerminalShellIntegration((e) => {
            if (e.terminal === terminal) {
              resolve();
            }
          }));
          ds.add($Xh(
            resolve,
            5e3
            /* Timing.MaxDelay */
          ));
        });
        ds.dispose();
      } else {
        if (terminal.state.isInteractedWith && !terminal.shellIntegration) {
          terminal.sendText("");
          await $Wh(200);
        }
        if (configProvider.getConfiguration("debug.terminal").get("clearBeforeReusing")) {
          if (shell.indexOf("powershell") >= 0 || shell.indexOf("pwsh") >= 0 || shell.indexOf("cmd.exe") >= 0) {
            terminal.sendText("cls");
          } else if (shell.indexOf("bash") >= 0) {
            terminal.sendText("clear");
          } else if ($l) {
            terminal.sendText("cls");
          } else {
            terminal.sendText("clear");
          }
        }
      }
      const command = $dzc(shell, args2.args, !!args2.argsCanBeInterpretedByShell, cwdForPrepareCommand, args2.env);
      if (terminal.shellIntegration) {
        terminal.shellIntegration.executeCommand(command);
      } else {
        terminal.sendText(command);
      }
      const sessionListener = this.onDidTerminateDebugSession((s) => {
        if (s.id === sessionId) {
          this.Db.free(terminal);
          sessionListener.dispose();
        }
      });
      return shellProcessId;
    } else if (args2.kind === "external") {
      return runInExternalTerminal(args2, await this.ab.getConfigProvider());
    }
    return super.$runInTerminal(args2, sessionId);
  }
};
$ezc = __decorate([
  __param(0, $gW),
  __param(1, $0wc),
  __param(2, $Lxc),
  __param(3, $axc),
  __param(4, $yxc),
  __param(5, $Oyc),
  __param(6, $mxc),
  __param(7, $Txc),
  __param(8, $CW),
  __param(9, $Oxc)
], $ezc);
var externalTerminalService = void 0;
function runInExternalTerminal(args2, configProvider) {
  if (!externalTerminalService) {
    if ($l) {
      externalTerminalService = new $_x();
    } else if ($m) {
      externalTerminalService = new $ay();
    } else if ($n) {
      externalTerminalService = new $by();
    } else {
      throw new Error("external terminals not supported on this platform");
    }
  }
  const config = configProvider.getConfiguration("terminal");
  return externalTerminalService.runInTerminal(args2.title, args2.cwd, args2.args, args2.env || {}, config.external || {});
}
var DebugTerminalCollection = class _DebugTerminalCollection {
  constructor() {
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.a = 1e3;
  }
  async checkout(config, name, cleanupOthersByName = false) {
    const entries = [...this.b.entries()];
    const promises8 = entries.map(([terminal, termInfo]) => $Hh(async (ct) => {
      if (terminal.name !== name) {
        return null;
      }
      if (termInfo.lastUsedAt !== -1 && await $czc(await terminal.processId)) {
        return null;
      }
      const now = Date.now();
      if (termInfo.lastUsedAt + _DebugTerminalCollection.a > now || ct.isCancellationRequested) {
        return null;
      }
      if (termInfo.config !== config) {
        if (cleanupOthersByName) {
          terminal.dispose();
        }
        return null;
      }
      termInfo.lastUsedAt = now;
      return terminal;
    }));
    return await $1h(promises8, (t) => !!t);
  }
  insert(terminal, termConfig) {
    this.b.set(terminal, { lastUsedAt: Date.now(), config: termConfig });
  }
  free(terminal) {
    const info = this.b.get(terminal);
    if (info) {
      info.lastUsedAt = -1;
    }
  }
  onTerminalClosed(terminal) {
    this.b.delete(terminal);
  }
};

// out-build/vs/base/common/comparers.js
var intlFileNameCollatorBaseNumeric = new $sf(() => {
  const collator = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" });
  return {
    collator,
    collatorIsNumeric: collator.resolvedOptions().numeric
  };
});
var intlFileNameCollatorNumeric = new $sf(() => {
  const collator = new Intl.Collator(void 0, { numeric: true });
  return {
    collator
  };
});
var intlFileNameCollatorNumericCaseInsensitive = new $sf(() => {
  const collator = new Intl.Collator(void 0, { numeric: true, sensitivity: "accent" });
  return {
    collator
  };
});
function $EM(one, other, caseSensitive = false) {
  const a = one || "";
  const b = other || "";
  const result = intlFileNameCollatorBaseNumeric.value.collator.compare(a, b);
  if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && a !== b) {
    return a < b ? -1 : 1;
  }
  return result;
}
function comparePathComponents(one, other, caseSensitive = false) {
  if (!caseSensitive) {
    one = one && one.toLowerCase();
    other = other && other.toLowerCase();
  }
  if (one === other) {
    return 0;
  }
  return one < other ? -1 : 1;
}
function $OM(one, other, caseSensitive = false) {
  const oneParts = one.split(sep);
  const otherParts = other.split(sep);
  const lastOne = oneParts.length - 1;
  const lastOther = otherParts.length - 1;
  let endOne, endOther;
  for (let i = 0; ; i++) {
    endOne = lastOne === i;
    endOther = lastOther === i;
    if (endOne && endOther) {
      return $EM(oneParts[i], otherParts[i], caseSensitive);
    } else if (endOne) {
      return -1;
    } else if (endOther) {
      return 1;
    }
    const result = comparePathComponents(oneParts[i], otherParts[i], caseSensitive);
    if (result !== 0) {
      return result;
    }
  }
}
function $PM(one, other, lookFor) {
  const elementAName = one.toLowerCase();
  const elementBName = other.toLowerCase();
  const prefixCompare = $QM(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 = $EM(elementAName, elementBName);
  if (r !== 0) {
    return r;
  }
  return elementAName.localeCompare(elementBName);
}
function $QM(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;
}

// out-build/vs/base/common/fuzzyScorer.js
var NO_MATCH = 0;
var NO_SCORE = [NO_MATCH, []];
function $RM(target, query, queryLower, allowNonContiguousMatches) {
  if (!target || !query) {
    return NO_SCORE;
  }
  const targetLength = target.length;
  const queryLength = query.length;
  if (targetLength < queryLength) {
    return NO_SCORE;
  }
  const targetLower = target.toLowerCase();
  const res = doScoreFuzzy(query, queryLower, queryLength, target, targetLower, targetLength, allowNonContiguousMatches);
  return res;
}
function doScoreFuzzy(query, queryLower, queryLength, target, targetLower, targetLength, allowNonContiguousMatches) {
  const scores = [];
  const matches = [];
  for (let queryIndex2 = 0; queryIndex2 < queryLength; queryIndex2++) {
    const queryIndexOffset = queryIndex2 * targetLength;
    const queryIndexPreviousOffset = queryIndexOffset - targetLength;
    const queryIndexGtNull = queryIndex2 > 0;
    const queryCharAtIndex = query[queryIndex2];
    const queryLowerCharAtIndex = queryLower[queryIndex2];
    for (let targetIndex2 = 0; targetIndex2 < targetLength; targetIndex2++) {
      const targetIndexGtNull = targetIndex2 > 0;
      const currentIndex = queryIndexOffset + targetIndex2;
      const leftIndex = currentIndex - 1;
      const diagIndex = queryIndexPreviousOffset + targetIndex2 - 1;
      const leftScore = targetIndexGtNull ? scores[leftIndex] : 0;
      const diagScore = queryIndexGtNull && targetIndexGtNull ? scores[diagIndex] : 0;
      const matchesSequenceLength = queryIndexGtNull && targetIndexGtNull ? matches[diagIndex] : 0;
      let score;
      if (!diagScore && queryIndexGtNull) {
        score = 0;
      } else {
        score = computeCharScore(queryCharAtIndex, queryLowerCharAtIndex, target, targetLower, targetIndex2, matchesSequenceLength);
      }
      const isValidScore = score && diagScore + score >= leftScore;
      if (isValidScore && // We don't need to check if it's contiguous if we allow non-contiguous matches
      (allowNonContiguousMatches || // We must be looking for a contiguous match.
      // Looking at an index higher than 0 in the query means we must have already
      // found out this is contiguous otherwise there wouldn't have been a score
      queryIndexGtNull || // lastly check if the query is completely contiguous at this index in the target
      targetLower.startsWith(queryLower, targetIndex2))) {
        matches[currentIndex] = matchesSequenceLength + 1;
        scores[currentIndex] = diagScore + score;
      } else {
        matches[currentIndex] = NO_MATCH;
        scores[currentIndex] = leftScore;
      }
    }
  }
  const positions = [];
  let queryIndex = queryLength - 1;
  let targetIndex = targetLength - 1;
  while (queryIndex >= 0 && targetIndex >= 0) {
    const currentIndex = queryIndex * targetLength + targetIndex;
    const match = matches[currentIndex];
    if (match === NO_MATCH) {
      targetIndex--;
    } else {
      positions.push(targetIndex);
      queryIndex--;
      targetIndex--;
    }
  }
  return [scores[queryLength * targetLength - 1], positions.reverse()];
}
function computeCharScore(queryCharAtIndex, queryLowerCharAtIndex, target, targetLower, targetIndex, matchesSequenceLength) {
  let score = 0;
  if (!considerAsEqual(queryLowerCharAtIndex, targetLower[targetIndex])) {
    return score;
  }
  score += 1;
  if (matchesSequenceLength > 0) {
    score += matchesSequenceLength * 5;
  }
  if (queryCharAtIndex === target[targetIndex]) {
    score += 1;
  }
  if (targetIndex === 0) {
    score += 8;
  } else {
    const separatorBonus = scoreSeparatorAtPos(target.charCodeAt(targetIndex - 1));
    if (separatorBonus) {
      score += separatorBonus;
    } else if ($Ol(target.charCodeAt(targetIndex)) && matchesSequenceLength === 0) {
      score += 2;
    }
  }
  return score;
}
function considerAsEqual(a, b) {
  if (a === b) {
    return true;
  }
  if (a === "/" || a === "\\") {
    return b === "/" || b === "\\";
  }
  return false;
}
function scoreSeparatorAtPos(charCode) {
  switch (charCode) {
    case 47:
    case 92:
      return 5;
    case 95:
    case 45:
    case 46:
    case 32:
    case 39:
    case 34:
    case 58:
      return 4;
    default:
      return 0;
  }
}
var NO_ITEM_SCORE = Object.freeze({ score: 0 });
var PATH_IDENTITY_SCORE = 1 << 18;
var LABEL_PREFIX_SCORE_THRESHOLD = 1 << 17;
var LABEL_SCORE_THRESHOLD = 1 << 16;
function getCacheHash(label, description, allowNonContiguousMatches, query) {
  const values = query.values ? query.values : [query];
  const cacheHash = $Xi({
    [query.normalized]: {
      values: values.map((v) => ({ value: v.normalized, expectContiguousMatch: v.expectContiguousMatch })),
      label,
      description,
      allowNonContiguousMatches
    }
  });
  return cacheHash;
}
function $TM(item, query, allowNonContiguousMatches, accessor, cache) {
  if (!item || !query.normalized) {
    return NO_ITEM_SCORE;
  }
  const label = accessor.getItemLabel(item);
  if (!label) {
    return NO_ITEM_SCORE;
  }
  const description = accessor.getItemDescription(item);
  const cacheHash = getCacheHash(label, description, allowNonContiguousMatches, query);
  const cached = cache[cacheHash];
  if (cached) {
    return cached;
  }
  const itemScore = doScoreItemFuzzy(label, description, accessor.getItemPath(item), query, allowNonContiguousMatches);
  cache[cacheHash] = itemScore;
  return itemScore;
}
function doScoreItemFuzzy(label, description, path, query, allowNonContiguousMatches) {
  const preferLabelMatches = !path || !query.containsPathSeparator;
  if (path && ($n ? query.pathNormalized === path : $1f(query.pathNormalized, path))) {
    return { score: PATH_IDENTITY_SCORE, labelMatch: [{ start: 0, end: label.length }], descriptionMatch: description ? [{ start: 0, end: description.length }] : void 0 };
  }
  if (query.values && query.values.length > 1) {
    return doScoreItemFuzzyMultiple(label, description, path, query.values, preferLabelMatches, allowNonContiguousMatches);
  }
  return doScoreItemFuzzySingle(label, description, path, query, preferLabelMatches, allowNonContiguousMatches);
}
function doScoreItemFuzzyMultiple(label, description, path, query, preferLabelMatches, allowNonContiguousMatches) {
  let totalScore = 0;
  const totalLabelMatches = [];
  const totalDescriptionMatches = [];
  for (const queryPiece of query) {
    const { score, labelMatch, descriptionMatch } = doScoreItemFuzzySingle(label, description, path, queryPiece, preferLabelMatches, allowNonContiguousMatches);
    if (score === NO_MATCH) {
      return NO_ITEM_SCORE;
    }
    totalScore += score;
    if (labelMatch) {
      totalLabelMatches.push(...labelMatch);
    }
    if (descriptionMatch) {
      totalDescriptionMatches.push(...descriptionMatch);
    }
  }
  return {
    score: totalScore,
    labelMatch: normalizeMatches(totalLabelMatches),
    descriptionMatch: normalizeMatches(totalDescriptionMatches)
  };
}
function doScoreItemFuzzySingle(label, description, path, query, preferLabelMatches, allowNonContiguousMatches) {
  if (preferLabelMatches || !description) {
    const [labelScore, labelPositions] = $RM(label, query.normalized, query.normalizedLowercase, allowNonContiguousMatches && !query.expectContiguousMatch);
    if (labelScore) {
      const labelPrefixMatch = $Ll(query.normalized, label);
      let baseScore;
      if (labelPrefixMatch) {
        baseScore = LABEL_PREFIX_SCORE_THRESHOLD;
        const prefixLengthBoost = Math.round(query.normalized.length / label.length * 100);
        baseScore += prefixLengthBoost;
      } else {
        baseScore = LABEL_SCORE_THRESHOLD;
      }
      return { score: baseScore + labelScore, labelMatch: labelPrefixMatch || createMatches(labelPositions) };
    }
  }
  if (description) {
    let descriptionPrefix = description;
    if (!!path) {
      descriptionPrefix = `${description}${sep}`;
    }
    const descriptionPrefixLength = descriptionPrefix.length;
    const descriptionAndLabel = `${descriptionPrefix}${label}`;
    const [labelDescriptionScore, labelDescriptionPositions] = $RM(descriptionAndLabel, query.normalized, query.normalizedLowercase, allowNonContiguousMatches && !query.expectContiguousMatch);
    if (labelDescriptionScore) {
      const labelDescriptionMatches = createMatches(labelDescriptionPositions);
      const labelMatch = [];
      const descriptionMatch = [];
      labelDescriptionMatches.forEach((h) => {
        if (h.start < descriptionPrefixLength && h.end > descriptionPrefixLength) {
          labelMatch.push({ start: 0, end: h.end - descriptionPrefixLength });
          descriptionMatch.push({ start: h.start, end: descriptionPrefixLength });
        } else if (h.start >= descriptionPrefixLength) {
          labelMatch.push({ start: h.start - descriptionPrefixLength, end: h.end - descriptionPrefixLength });
        } else {
          descriptionMatch.push(h);
        }
      });
      return { score: labelDescriptionScore, labelMatch, descriptionMatch };
    }
  }
  return NO_ITEM_SCORE;
}
function createMatches(offsets) {
  const ret = [];
  if (!offsets) {
    return ret;
  }
  let last;
  for (const pos of offsets) {
    if (last && last.end === pos) {
      last.end += 1;
    } else {
      last = { start: pos, end: pos + 1 };
      ret.push(last);
    }
  }
  return ret;
}
function normalizeMatches(matches) {
  const sortedMatches = matches.sort((matchA, matchB) => {
    return matchA.start - matchB.start;
  });
  const normalizedMatches = [];
  let currentMatch = void 0;
  for (const match of sortedMatches) {
    if (!currentMatch || !matchOverlaps(currentMatch, match)) {
      currentMatch = match;
      normalizedMatches.push(match);
    } else {
      currentMatch.start = Math.min(currentMatch.start, match.start);
      currentMatch.end = Math.max(currentMatch.end, match.end);
    }
  }
  return normalizedMatches;
}
function matchOverlaps(matchA, matchB) {
  if (matchA.end < matchB.start) {
    return false;
  }
  if (matchB.end < matchA.start) {
    return false;
  }
  return true;
}
function $UM(itemA, itemB, query, allowNonContiguousMatches, accessor, cache) {
  const itemScoreA = $TM(itemA, query, allowNonContiguousMatches, accessor, cache);
  const itemScoreB = $TM(itemB, query, allowNonContiguousMatches, accessor, cache);
  const scoreA = itemScoreA.score;
  const scoreB = itemScoreB.score;
  if (scoreA === PATH_IDENTITY_SCORE || scoreB === PATH_IDENTITY_SCORE) {
    if (scoreA !== scoreB) {
      return scoreA === PATH_IDENTITY_SCORE ? -1 : 1;
    }
  }
  if (scoreA > LABEL_SCORE_THRESHOLD || scoreB > LABEL_SCORE_THRESHOLD) {
    if (scoreA !== scoreB) {
      return scoreA > scoreB ? -1 : 1;
    }
    if (scoreA < LABEL_PREFIX_SCORE_THRESHOLD && scoreB < LABEL_PREFIX_SCORE_THRESHOLD) {
      const comparedByMatchLength = compareByMatchLength(itemScoreA.labelMatch, itemScoreB.labelMatch);
      if (comparedByMatchLength !== 0) {
        return comparedByMatchLength;
      }
    }
    const labelA = accessor.getItemLabel(itemA) || "";
    const labelB = accessor.getItemLabel(itemB) || "";
    if (labelA.length !== labelB.length) {
      return labelA.length - labelB.length;
    }
  }
  if (scoreA !== scoreB) {
    return scoreA > scoreB ? -1 : 1;
  }
  const itemAHasLabelMatches = Array.isArray(itemScoreA.labelMatch) && itemScoreA.labelMatch.length > 0;
  const itemBHasLabelMatches = Array.isArray(itemScoreB.labelMatch) && itemScoreB.labelMatch.length > 0;
  if (itemAHasLabelMatches && !itemBHasLabelMatches) {
    return -1;
  } else if (itemBHasLabelMatches && !itemAHasLabelMatches) {
    return 1;
  }
  const itemAMatchDistance = computeLabelAndDescriptionMatchDistance(itemA, itemScoreA, accessor);
  const itemBMatchDistance = computeLabelAndDescriptionMatchDistance(itemB, itemScoreB, accessor);
  if (itemAMatchDistance && itemBMatchDistance && itemAMatchDistance !== itemBMatchDistance) {
    return itemBMatchDistance > itemAMatchDistance ? -1 : 1;
  }
  return fallbackCompare(itemA, itemB, query, accessor);
}
function computeLabelAndDescriptionMatchDistance(item, score, accessor) {
  let matchStart = -1;
  let matchEnd = -1;
  if (score.descriptionMatch && score.descriptionMatch.length) {
    matchStart = score.descriptionMatch[0].start;
  } else if (score.labelMatch && score.labelMatch.length) {
    matchStart = score.labelMatch[0].start;
  }
  if (score.labelMatch && score.labelMatch.length) {
    matchEnd = score.labelMatch[score.labelMatch.length - 1].end;
    if (score.descriptionMatch && score.descriptionMatch.length) {
      const itemDescription = accessor.getItemDescription(item);
      if (itemDescription) {
        matchEnd += itemDescription.length;
      }
    }
  } else if (score.descriptionMatch && score.descriptionMatch.length) {
    matchEnd = score.descriptionMatch[score.descriptionMatch.length - 1].end;
  }
  return matchEnd - matchStart;
}
function compareByMatchLength(matchesA, matchesB) {
  if (!matchesA && !matchesB || (!matchesA || !matchesA.length) && (!matchesB || !matchesB.length)) {
    return 0;
  }
  if (!matchesB || !matchesB.length) {
    return -1;
  }
  if (!matchesA || !matchesA.length) {
    return 1;
  }
  const matchStartA = matchesA[0].start;
  const matchEndA = matchesA[matchesA.length - 1].end;
  const matchLengthA = matchEndA - matchStartA;
  const matchStartB = matchesB[0].start;
  const matchEndB = matchesB[matchesB.length - 1].end;
  const matchLengthB = matchEndB - matchStartB;
  return matchLengthA === matchLengthB ? 0 : matchLengthB < matchLengthA ? 1 : -1;
}
function fallbackCompare(itemA, itemB, query, accessor) {
  const labelA = accessor.getItemLabel(itemA) || "";
  const labelB = accessor.getItemLabel(itemB) || "";
  const descriptionA = accessor.getItemDescription(itemA);
  const descriptionB = accessor.getItemDescription(itemB);
  const labelDescriptionALength = labelA.length + (descriptionA ? descriptionA.length : 0);
  const labelDescriptionBLength = labelB.length + (descriptionB ? descriptionB.length : 0);
  if (labelDescriptionALength !== labelDescriptionBLength) {
    return labelDescriptionALength - labelDescriptionBLength;
  }
  const pathA = accessor.getItemPath(itemA);
  const pathB = accessor.getItemPath(itemB);
  if (pathA && pathB && pathA.length !== pathB.length) {
    return pathA.length - pathB.length;
  }
  if (labelA !== labelB) {
    return $PM(labelA, labelB, query.normalized);
  }
  if (descriptionA && descriptionB && descriptionA !== descriptionB) {
    return $PM(descriptionA, descriptionB, query.normalized);
  }
  if (pathA && pathB && pathA !== pathB) {
    return $PM(pathA, pathB, query.normalized);
  }
  return 0;
}
function queryExpectsExactMatch(query) {
  return query.startsWith('"') && query.endsWith('"');
}
var MULTIPLE_QUERY_VALUES_SEPARATOR = " ";
function $VM(original) {
  if (typeof original !== "string") {
    original = "";
  }
  const originalLowercase = original.toLowerCase();
  const { pathNormalized, normalized, normalizedLowercase } = normalizeQuery(original);
  const containsPathSeparator = pathNormalized.indexOf(sep) >= 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 ($l) {
    pathNormalized = original.replace(/\//g, sep);
  } else {
    pathNormalized = original.replace(/\\/g, sep);
  }
  const normalized = $If(pathNormalized).replace(/\s|"/g, "");
  return {
    pathNormalized,
    normalized,
    normalizedLowercase: normalized.toLowerCase()
  };
}

// out-build/vs/workbench/services/search/node/fileSearch.js
import * as childProcess from "child_process";
import * as fs3 from "fs";
import { StringDecoder } from "string_decoder";

// out-build/vs/workbench/services/search/node/ripgrepFileSearch.js
import * as cp4 from "child_process";

// out-build/vs/workbench/services/search/node/ripgrepSearchUtils.js
function $fzc(glob) {
  return glob.startsWith("**") || glob.startsWith("/") ? glob : `/${glob}`;
}
function $gzc(range) {
  return new $ZN(range.start.line, range.start.character, range.end.line, range.end.character);
}
function $hzc(range) {
  return new $KN(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
}
var $izc = class $izc2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  appendLine(msg) {
    this.b.debug(`${this.a}#search`, msg);
  }
};
$izc = __decorate([
  __param(1, $wn)
], $izc);

// out-build/vs/workbench/services/search/node/ripgrepFileSearch.js
import { rgPath } from "@vscode/ripgrep";
var rgDiskPath = rgPath.replace(/\bnode_modules\.asar\b/, "node_modules.asar.unpacked");
function $jzc(config, folderQuery, includePattern, excludePattern, numThreads) {
  const rgArgs = getRgArgs(config, folderQuery, includePattern, excludePattern, numThreads);
  const cwd2 = folderQuery.folder.fsPath;
  return {
    cmd: cp4.spawn(rgDiskPath, rgArgs.args, { cwd: cwd2 }),
    rgDiskPath,
    siblingClauses: rgArgs.siblingClauses,
    rgArgs,
    cwd: cwd2
  };
}
function getRgArgs(config, folderQuery, includePattern, excludePattern, numThreads) {
  const args2 = ["--files", "--hidden", "--case-sensitive", "--no-require-git"];
  foldersToIncludeGlobs([folderQuery], includePattern, false).forEach((globArg) => {
    const inclusion = $fzc(globArg);
    args2.push("-g", inclusion);
    if ($m) {
      const normalized = $Rs(inclusion);
      if (normalized !== inclusion) {
        args2.push("-g", normalized);
      }
    }
  });
  const rgGlobs = foldersToRgExcludeGlobs([folderQuery], excludePattern, void 0, false);
  rgGlobs.globArgs.forEach((globArg) => {
    const exclusion = `!${$fzc(globArg)}`;
    args2.push("-g", exclusion);
    if ($m) {
      const normalized = $Rs(exclusion);
      if (normalized !== exclusion) {
        args2.push("-g", normalized);
      }
    }
  });
  if (folderQuery.disregardIgnoreFiles !== false) {
    args2.push("--no-ignore");
  } else if (folderQuery.disregardParentIgnoreFiles !== false) {
    args2.push("--no-ignore-parent");
  }
  if (!folderQuery.ignoreSymlinks) {
    args2.push("--follow");
  }
  if (config.exists) {
    args2.push("--quiet");
  }
  if (numThreads) {
    args2.push("--threads", `${numThreads}`);
  }
  args2.push("--no-config");
  if (folderQuery.disregardGlobalIgnoreFiles) {
    args2.push("--no-ignore-global");
  }
  return {
    args: args2,
    siblingClauses: rgGlobs.siblingClauses
  };
}
function foldersToRgExcludeGlobs(folderQueries, globalExclude, excludesToSkip, absoluteGlobs = true) {
  const globArgs = [];
  let siblingClauses = {};
  folderQueries.forEach((folderQuery) => {
    const totalExcludePattern = Object.assign({}, folderQuery.excludePattern || {}, globalExclude || {});
    const result = globExprsToRgGlobs(totalExcludePattern, absoluteGlobs ? folderQuery.folder.fsPath : void 0, excludesToSkip);
    globArgs.push(...result.globArgs);
    if (result.siblingClauses) {
      siblingClauses = Object.assign(siblingClauses, result.siblingClauses);
    }
  });
  return { globArgs, siblingClauses };
}
function foldersToIncludeGlobs(folderQueries, globalInclude, absoluteGlobs = true) {
  const globArgs = [];
  folderQueries.forEach((folderQuery) => {
    const totalIncludePattern = Object.assign({}, globalInclude || {}, folderQuery.includePattern || {});
    const result = globExprsToRgGlobs(totalIncludePattern, absoluteGlobs ? folderQuery.folder.fsPath : void 0);
    globArgs.push(...result.globArgs);
  });
  return globArgs;
}
function globExprsToRgGlobs(patterns, folder, excludesToSkip) {
  const globArgs = [];
  const siblingClauses = {};
  Object.keys(patterns).forEach((key) => {
    if (excludesToSkip && excludesToSkip.has(key)) {
      return;
    }
    if (!key) {
      return;
    }
    const value = patterns[key];
    key = trimTrailingSlash(folder ? $kzc(folder, key) : key);
    if (key.startsWith("\\\\")) {
      key = "\\\\" + key.substr(2).replace(/\\/g, "/");
    } else {
      key = key.replace(/\\/g, "/");
    }
    if (typeof value === "boolean" && value) {
      if (key.startsWith("\\\\")) {
        key += "**";
      }
      globArgs.push($lzc(key));
    } else if (value && value.when) {
      siblingClauses[key] = value;
    }
  });
  return { globArgs, siblingClauses };
}
function $kzc(folder, key) {
  return $mc(key) ? key : $nc(folder, key);
}
function trimTrailingSlash(str) {
  str = $Gf(str, "\\");
  return $Gf(str, "/");
}
function $lzc(path) {
  const root = $Vg(path);
  return root.toLowerCase() === "c:/" ? path.replace(/^c:[/\\]/i, "/") : path;
}

// out-build/vs/workbench/services/search/node/fileSearch.js
var killCmds = /* @__PURE__ */ new Set();
process.on("exit", () => {
  killCmds.forEach((cmd) => cmd());
});
var $mzc = class {
  constructor(config) {
    this.c = null;
    this.h = null;
    this.l = false;
    this.m = null;
    this.r = null;
    this.s = 0;
    this.a = config;
    this.b = config.filePattern || "";
    this.d = config.includePattern && $Dl(config.includePattern);
    this.f = config.maxResults || null;
    this.g = !!config.exists;
    this.v = /* @__PURE__ */ Object.create(null);
    this.k = 0;
    this.j = false;
    this.o = 0;
    this.p = 0;
    this.q = [];
    if (this.b) {
      this.c = config.shouldGlobMatchFilePattern ? null : $VM(this.b).normalizedLowercase;
    }
    this.u = config.excludePattern && $Dl(config.excludePattern);
    this.t = /* @__PURE__ */ new Map();
    config.folderQueries.forEach((folderQuery) => {
      const folderExcludeExpression = {};
      folderQuery.excludePattern?.forEach((excludePattern) => {
        Object.assign(folderExcludeExpression, excludePattern.pattern || {}, this.a.excludePattern || {});
      });
      if (!folderQuery.excludePattern?.length) {
        Object.assign(folderExcludeExpression, this.a.excludePattern || {});
      }
      const fqPath = folderQuery.folder.fsPath;
      config.folderQueries.map((rootFolderQuery) => rootFolderQuery.folder.fsPath).filter((rootFolder) => rootFolder !== fqPath).forEach((otherRootFolder) => {
        if ($Zg(otherRootFolder, fqPath)) {
          folderExcludeExpression[$pc(fqPath, otherRootFolder)] = true;
        }
      });
      this.t.set(fqPath, new AbsoluteAndRelativeParsedExpression(folderExcludeExpression, fqPath));
    });
  }
  cancel() {
    this.l = true;
    killCmds.forEach((cmd) => cmd());
  }
  walk(folderQueries, extraFiles, numThreads, onResult, onMessage, done) {
    this.m = $te.create(false);
    if (this.l) {
      return done(null, this.j);
    }
    extraFiles.forEach((extraFilePath) => {
      const basename = $rc(extraFilePath.fsPath);
      if (this.u && this.u(extraFilePath.fsPath, basename)) {
        return;
      }
      this.J(onResult, { relativePath: extraFilePath.fsPath, searchPath: void 0 });
    });
    this.r = $te.create(false);
    this.w(folderQueries, (folderQuery, rootFolderDone) => {
      this.x(this.y, this, folderQuery, numThreads, onResult, onMessage, (err) => {
        if (err) {
          const errorMessage = $1m(err);
          console.error(errorMessage);
          this.q.push(errorMessage);
          rootFolderDone(err, void 0);
        } else {
          rootFolderDone(null, void 0);
        }
      });
    }, (errors, _result) => {
      this.m.stop();
      const err = errors ? $Mb(errors)[0] : null;
      done(err, this.j);
    });
  }
  w(list2, fn, callback) {
    const results = new Array(list2.length);
    const errors = new Array(list2.length);
    let didErrorOccur = false;
    let doneCount = 0;
    if (list2.length === 0) {
      return callback(null, []);
    }
    list2.forEach((item, index) => {
      fn(item, (error, result) => {
        if (error) {
          didErrorOccur = true;
          results[index] = null;
          errors[index] = error;
        } else {
          results[index] = result;
          errors[index] = null;
        }
        if (++doneCount === list2.length) {
          return callback(didErrorOccur ? errors : null, results);
        }
      });
    });
  }
  x(fun, that, ...args2) {
    try {
      fun.apply(that, args2);
    } catch (e) {
      args2[args2.length - 1](e);
    }
  }
  y(folderQuery, numThreads, onResult, onMessage, cb) {
    const rootFolder = folderQuery.folder.fsPath;
    const isMac = $m;
    const killCmd = () => cmd && cmd.kill();
    killCmds.add(killCmd);
    let done = (err) => {
      killCmds.delete(killCmd);
      done = () => {
      };
      cb(err);
    };
    let leftover = "";
    const tree = this.D();
    const ripgrep = $jzc(this.a, folderQuery, this.a.includePattern, this.t.get(folderQuery.folder.fsPath).expression, numThreads);
    const cmd = ripgrep.cmd;
    const noSiblingsClauses = !Object.keys(ripgrep.siblingClauses).length;
    const escapedArgs = ripgrep.rgArgs.args.map((arg) => arg.match(/^-/) ? arg : `'${arg}'`).join(" ");
    let rgCmd = `${ripgrep.rgDiskPath} ${escapedArgs}
 - cwd: ${ripgrep.cwd}`;
    if (ripgrep.rgArgs.siblingClauses) {
      rgCmd += `
 - Sibling clauses: ${JSON.stringify(ripgrep.rgArgs.siblingClauses)}`;
    }
    onMessage({ message: rgCmd });
    this.s = 0;
    this.z(cmd, "utf8", onMessage, (err, stdout, last) => {
      if (err) {
        done(err);
        return;
      }
      if (this.j) {
        done();
        return;
      }
      const normalized = leftover + (isMac ? $Qs(stdout || "") : stdout);
      const relativeFiles = normalized.split("\n");
      if (last) {
        const n = relativeFiles.length;
        relativeFiles[n - 1] = relativeFiles[n - 1].trim();
        if (!relativeFiles[n - 1]) {
          relativeFiles.pop();
        }
      } else {
        leftover = relativeFiles.pop() || "";
      }
      if (relativeFiles.length && relativeFiles[0].indexOf("\n") !== -1) {
        done(new Error("Splitting up files failed"));
        return;
      }
      this.s += relativeFiles.length;
      if (noSiblingsClauses) {
        for (const relativePath of relativeFiles) {
          this.J(onResult, { base: rootFolder, relativePath, searchPath: this.N(folderQuery, relativePath) });
          if (this.j) {
            killCmd();
            break;
          }
        }
        if (last || this.j) {
          done();
        }
        return;
      }
      this.G(folderQuery, tree, rootFolder, relativeFiles, onResult);
      if (last) {
        this.H(tree, rootFolder, onResult);
        done();
      }
    });
  }
  /**
   * Public for testing.
   */
  spawnFindCmd(folderQuery) {
    const excludePattern = this.t.get(folderQuery.folder.fsPath);
    const basenames = excludePattern.getBasenameTerms();
    const pathTerms = excludePattern.getPathTerms();
    const args2 = ["-L", "."];
    if (basenames.length || pathTerms.length) {
      args2.push("-not", "(", "(");
      for (const basename of basenames) {
        args2.push("-name", basename);
        args2.push("-o");
      }
      for (const path of pathTerms) {
        args2.push("-path", path);
        args2.push("-o");
      }
      args2.pop();
      args2.push(")", "-prune", ")");
    }
    args2.push("-type", "f");
    return childProcess.spawn("find", args2, { cwd: folderQuery.folder.fsPath });
  }
  /**
   * Public for testing.
   */
  readStdout(cmd, encoding, cb) {
    let all = "";
    this.z(cmd, encoding, () => {
    }, (err, stdout, last) => {
      if (err) {
        cb(err);
        return;
      }
      all += stdout;
      if (last) {
        cb(null, all);
      }
    });
  }
  z(cmd, encoding, onMessage, cb) {
    let onData = (err, stdout, last) => {
      if (err || last) {
        onData = () => {
        };
        this.r?.stop();
      }
      cb(err, stdout, last);
    };
    let gotData = false;
    if (cmd.stdout) {
      this.A(cmd.stdout, encoding, onData);
      cmd.stdout.once("data", () => gotData = true);
    } else {
      onMessage({ message: "stdout is null" });
    }
    let stderr;
    if (cmd.stderr) {
      stderr = this.B(cmd.stderr);
    } else {
      onMessage({ message: "stderr is null" });
    }
    cmd.on("error", (err) => {
      onData(err);
    });
    cmd.on("close", (code) => {
      let stderrText;
      if (!gotData && (stderrText = this.C(stderr, encoding)) && rgErrorMsgForDisplay(stderrText)) {
        onData(new Error(`command failed with error code ${code}: ${this.C(stderr, encoding)}`));
      } else {
        if (this.g && code === 0) {
          this.j = true;
        }
        onData(null, "", true);
      }
    });
  }
  A(stream, encoding, cb) {
    const decoder = new StringDecoder(encoding);
    stream.on("data", (data) => {
      cb(null, decoder.write(data));
    });
    return decoder;
  }
  B(stream) {
    const buffers = [];
    stream.on("data", (data) => {
      buffers.push(data);
    });
    return buffers;
  }
  C(buffers, encoding) {
    const decoder = new StringDecoder(encoding);
    return buffers.map((buffer) => decoder.write(buffer)).join("");
  }
  D() {
    const tree = {
      rootEntries: [],
      pathToEntries: /* @__PURE__ */ Object.create(null)
    };
    tree.pathToEntries["."] = tree.rootEntries;
    return tree;
  }
  G(folderQuery, { pathToEntries }, base, relativeFiles, onResult) {
    if (relativeFiles.indexOf(this.b) !== -1) {
      this.J(onResult, {
        base,
        relativePath: this.b,
        searchPath: this.N(folderQuery, this.b)
      });
    }
    const add = (relativePath) => {
      const basename = $rc(relativePath);
      const dirname = $qc(relativePath);
      let entries = pathToEntries[dirname];
      if (!entries) {
        entries = pathToEntries[dirname] = [];
        add(dirname);
      }
      entries.push({
        base,
        relativePath,
        basename,
        searchPath: this.N(folderQuery, relativePath)
      });
    };
    relativeFiles.forEach(add);
  }
  H({ rootEntries, pathToEntries }, rootFolder, onResult) {
    const self2 = this;
    const excludePattern = this.t.get(rootFolder);
    const filePattern = this.b;
    function matchDirectory(entries) {
      self2.o++;
      const hasSibling = $cO(() => entries.map((entry) => entry.basename));
      for (let i = 0, n = entries.length; i < n; i++) {
        const entry = entries[i];
        const { relativePath, basename } = entry;
        if (excludePattern.test(relativePath, basename, filePattern !== basename ? hasSibling : void 0)) {
          continue;
        }
        const sub = pathToEntries[relativePath];
        if (sub) {
          matchDirectory(sub);
        } else {
          self2.p++;
          if (relativePath === filePattern) {
            continue;
          }
          self2.J(onResult, entry);
        }
        if (self2.j) {
          break;
        }
      }
    }
    matchDirectory(rootEntries);
  }
  getStats() {
    return {
      cmdTime: this.r.elapsed(),
      fileWalkTime: this.m.elapsed(),
      directoriesWalked: this.o,
      filesWalked: this.p,
      cmdResultCount: this.s
    };
  }
  I(folderQuery, relativeParentPath, files, onResult, done) {
    const rootFolder = folderQuery.folder;
    const hasSibling = $cO(() => files);
    this.w(files, (file, clb) => {
      if (this.l || this.j) {
        return clb(null);
      }
      const currentRelativePath = relativeParentPath ? [relativeParentPath, file].join(sep) : file;
      if (this.t.get(folderQuery.folder.fsPath).test(currentRelativePath, file, this.a.filePattern !== file ? hasSibling : void 0)) {
        return clb(null);
      }
      const currentAbsolutePath = [rootFolder.fsPath, currentRelativePath].join(sep);
      fs3.lstat(currentAbsolutePath, (error, lstat2) => {
        if (error || this.l || this.j) {
          return clb(null);
        }
        this.L(currentAbsolutePath, lstat2, (error2, stat2) => {
          if (error2 || this.l || this.j) {
            return clb(null);
          }
          if (stat2.isDirectory()) {
            this.o++;
            return this.M(currentAbsolutePath, lstat2, (error3, realpath3) => {
              if (error3 || this.l || this.j) {
                return clb(null);
              }
              realpath3 = realpath3 || "";
              if (this.v[realpath3]) {
                return clb(null);
              }
              this.v[realpath3] = true;
              return Promises2.readdir(currentAbsolutePath).then((children) => {
                if (this.l || this.j) {
                  return clb(null);
                }
                this.I(folderQuery, currentRelativePath, children, onResult, (err) => clb(err || null));
              }, (error4) => {
                clb(null);
              });
            });
          } else {
            this.p++;
            if (currentRelativePath === this.b) {
              return clb(null, void 0);
            }
            if (this.h && $Dg(stat2.size) && stat2.size > this.h) {
              return clb(null, void 0);
            }
            this.J(onResult, {
              base: rootFolder.fsPath,
              relativePath: currentRelativePath,
              searchPath: this.N(folderQuery, currentRelativePath)
            });
          }
          return clb(null, void 0);
        });
      });
    }, (error) => {
      const filteredErrors = error ? $Mb(error) : error;
      return done(filteredErrors && filteredErrors.length > 0 ? filteredErrors[0] : void 0);
    });
  }
  J(onResult, candidate) {
    if (this.K(candidate) && (!this.d || this.d(candidate.relativePath, $rc(candidate.relativePath)))) {
      this.k++;
      if (this.g || this.f && this.k > this.f) {
        this.j = true;
      }
      if (!this.j) {
        onResult(candidate);
      }
    }
  }
  K(candidate) {
    if (this.b) {
      if (this.b === "*") {
        return true;
      }
      if (this.c) {
        return $0N(candidate, this.c);
      } else if (this.b) {
        return $0N(candidate, this.b, false);
      }
    }
    return true;
  }
  L(path, lstat2, clb) {
    if (lstat2.isSymbolicLink()) {
      return fs3.stat(path, clb);
    }
    return clb(null, lstat2);
  }
  M(path, lstat2, clb) {
    if (lstat2.isSymbolicLink()) {
      return fs3.realpath(path, (error, realpath3) => {
        if (error) {
          return clb(error);
        }
        return clb(null, realpath3);
      });
    }
    return clb(null, path);
  }
  /**
   * If we're searching for files in multiple workspace folders, then better prepend the
   * name of the workspace folder to the path of the file. This way we'll be able to
   * better filter files that are all on the top of a workspace folder and have all the
   * same name. A typical example are `package.json` or `README.md` files.
   */
  N(folderQuery, relativePath) {
    if (folderQuery.folderName) {
      return $nc(folderQuery.folderName, relativePath);
    }
    return relativePath;
  }
};
var $nzc = class {
  constructor(config, numThreads) {
    this.a = config.folderQueries;
    this.b = config.extraFileResources || [];
    this.d = numThreads;
    this.c = new $mzc(config);
  }
  search(onResult, onProgress, done) {
    this.c.walk(this.a, this.b, this.d, onResult, onProgress, (err, isLimitHit) => {
      done(err, {
        limitHit: isLimitHit,
        stats: this.c.getStats(),
        messages: []
      });
    });
  }
  cancel() {
    this.c.cancel();
  }
};
var AbsoluteAndRelativeParsedExpression = class {
  constructor(expression, c) {
    this.expression = expression;
    this.c = c;
    this.d(expression);
  }
  /**
   * Split the IExpression into its absolute and relative components, and glob.parse them separately.
   */
  d(expr) {
    let absoluteGlobExpr;
    let relativeGlobExpr;
    Object.keys(expr).filter((key) => expr[key]).forEach((key) => {
      if ($mc(key)) {
        absoluteGlobExpr = absoluteGlobExpr || $yl();
        absoluteGlobExpr[key] = expr[key];
      } else {
        relativeGlobExpr = relativeGlobExpr || $yl();
        relativeGlobExpr[key] = expr[key];
      }
    });
    this.a = absoluteGlobExpr && $Dl(absoluteGlobExpr, { trimForExclusions: true });
    this.b = relativeGlobExpr && $Dl(relativeGlobExpr, { trimForExclusions: true });
  }
  test(_path, basename, hasSibling) {
    return this.b && this.b(_path, basename, hasSibling) || this.a && this.a($nc(this.c, _path), basename, hasSibling);
  }
  getBasenameTerms() {
    const basenameTerms = [];
    if (this.a) {
      basenameTerms.push(...$Fl(this.a));
    }
    if (this.b) {
      basenameTerms.push(...$Fl(this.b));
    }
    return basenameTerms;
  }
  getPathTerms() {
    const pathTerms = [];
    if (this.a) {
      pathTerms.push(...$Gl(this.a));
    }
    if (this.b) {
      pathTerms.push(...$Gl(this.b));
    }
    return pathTerms;
  }
};
function rgErrorMsgForDisplay(msg) {
  const lines = msg.trim().split("\n");
  const firstLine = lines[0].trim();
  if (firstLine.startsWith("Error parsing regex")) {
    return firstLine;
  }
  if (firstLine.startsWith("regex parse error")) {
    return $rg(lines[lines.length - 1].trim());
  }
  if (firstLine.startsWith("error parsing glob") || firstLine.startsWith("unsupported encoding")) {
    return firstLine.charAt(0).toUpperCase() + firstLine.substr(1);
  }
  if (firstLine === `Literal '\\n' not allowed.`) {
    return `Literal '\\n' currently not supported`;
  }
  if (firstLine.startsWith("Literal ")) {
    return firstLine;
  }
  return void 0;
}

// out-build/vs/workbench/services/search/node/ripgrepTextSearchEngine.js
import * as cp5 from "child_process";
import { EventEmitter } from "events";
import { StringDecoder as StringDecoder2 } from "string_decoder";
import { RegExpParser, RegExpVisitor } from "vscode-regexpp";
import { rgPath as rgPath2 } from "@vscode/ripgrep";
var rgDiskPath2 = rgPath2.replace(/\bnode_modules\.asar\b/, "node_modules.asar.unpacked");
var $ozc = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  provideTextSearchResults(query, options2, progress, token) {
    return Promise.all(options2.folderOptions.map((folderOption) => {
      const extendedOptions = {
        folderOptions: folderOption,
        numThreads: this.b,
        maxResults: options2.maxResults,
        previewOptions: options2.previewOptions,
        maxFileSize: options2.maxFileSize,
        surroundingContext: options2.surroundingContext
      };
      return this.provideTextSearchResultsWithRgOptions(query, extendedOptions, progress, token);
    })).then((e) => {
      const complete = {
        // todo: get this to actually check
        limitHit: e.some((complete2) => !!complete2 && complete2.limitHit)
      };
      return complete;
    });
  }
  provideTextSearchResultsWithRgOptions(query, options2, progress, token) {
    this.a.appendLine(`provideTextSearchResults ${query.pattern}, ${JSON.stringify({
      ...options2,
      ...{
        folder: options2.folderOptions.folder.toString()
      }
    })}`);
    return new Promise((resolve, reject) => {
      token.onCancellationRequested(() => cancel());
      const extendedOptions = {
        ...options2,
        numThreads: this.b
      };
      const rgArgs = $qzc(query, extendedOptions);
      const cwd2 = options2.folderOptions.folder.fsPath;
      const escapedArgs = rgArgs.map((arg) => arg.match(/^-/) ? arg : `'${arg}'`).join(" ");
      this.a.appendLine(`${rgDiskPath2} ${escapedArgs}
 - cwd: ${cwd2}`);
      let rgProc = cp5.spawn(rgDiskPath2, rgArgs, { cwd: cwd2 });
      rgProc.on("error", (e) => {
        console.error(e);
        this.a.appendLine("Error: " + (e && e.message));
        reject($6N(new $4N(e && e.message, SearchErrorCode.rgProcessError)));
      });
      let gotResult = false;
      const ripgrepParser = new $pzc(options2.maxResults ?? $SN, options2.folderOptions.folder, $byc(options2.previewOptions));
      ripgrepParser.on("result", (match) => {
        gotResult = true;
        dataWithoutResult = "";
        progress.report(match);
      });
      let isDone = false;
      const cancel = () => {
        isDone = true;
        rgProc?.kill();
        ripgrepParser?.cancel();
      };
      let limitHit = false;
      ripgrepParser.on("hitLimit", () => {
        limitHit = true;
        cancel();
      });
      let dataWithoutResult = "";
      rgProc.stdout.on("data", (data) => {
        ripgrepParser.handleData(data);
        if (!gotResult) {
          dataWithoutResult += data;
        }
      });
      let gotData = false;
      rgProc.stdout.once("data", () => gotData = true);
      let stderr = "";
      rgProc.stderr.on("data", (data) => {
        const message = data.toString();
        this.a.appendLine(message);
        if (stderr.length + message.length < 1e6) {
          stderr += message;
        }
      });
      rgProc.on("close", () => {
        this.a.appendLine(gotData ? "Got data from stdout" : "No data from stdout");
        this.a.appendLine(gotResult ? "Got result from parser" : "No result from parser");
        if (dataWithoutResult) {
          this.a.appendLine(`Got data without result: ${dataWithoutResult}`);
        }
        this.a.appendLine("");
        if (isDone) {
          resolve({ limitHit });
        } else {
          ripgrepParser.flush();
          rgProc = null;
          let searchError;
          if (stderr && !gotData && (searchError = rgErrorMsgForDisplay2(stderr))) {
            reject($6N(new $4N(searchError.message, searchError.code)));
          } else {
            resolve({ limitHit });
          }
        }
      });
    });
  }
};
function rgErrorMsgForDisplay2(msg) {
  const lines = msg.split("\n");
  const firstLine = lines[0].trim();
  if (lines.some((l) => l.startsWith("regex parse error"))) {
    return new $4N(buildRegexParseError(lines), SearchErrorCode.regexParseError);
  }
  const match = firstLine.match(/grep config error: unknown encoding: (.*)/);
  if (match) {
    return new $4N(`Unknown encoding: ${match[1]}`, SearchErrorCode.unknownEncoding);
  }
  if (firstLine.startsWith("error parsing glob")) {
    return new $4N(firstLine.charAt(0).toUpperCase() + firstLine.substr(1), SearchErrorCode.globParseError);
  }
  if (firstLine.startsWith("the literal")) {
    return new $4N(firstLine.charAt(0).toUpperCase() + firstLine.substr(1), SearchErrorCode.invalidLiteral);
  }
  if (firstLine.startsWith("PCRE2: error compiling pattern")) {
    return new $4N(firstLine, SearchErrorCode.regexParseError);
  }
  return void 0;
}
function buildRegexParseError(lines) {
  const errorMessage = ["Regex parse error"];
  const pcre2ErrorLine = lines.filter((l) => l.startsWith("PCRE2:"));
  if (pcre2ErrorLine.length >= 1) {
    const pcre2ErrorMessage = pcre2ErrorLine[0].replace("PCRE2:", "");
    if (pcre2ErrorMessage.indexOf(":") !== -1 && pcre2ErrorMessage.split(":").length >= 2) {
      const pcre2ActualErrorMessage = pcre2ErrorMessage.split(":")[1];
      errorMessage.push(":" + pcre2ActualErrorMessage);
    }
  }
  return errorMessage.join("");
}
var $pzc = class extends EventEmitter {
  constructor(g, h, j) {
    super();
    this.g = g;
    this.h = h;
    this.j = j;
    this.a = "";
    this.b = false;
    this.c = false;
    this.f = 0;
    this.d = new StringDecoder2();
  }
  cancel() {
    this.b = true;
  }
  flush() {
    this.k(this.d.end());
  }
  on(event, listener) {
    super.on(event, listener);
    return this;
  }
  handleData(data) {
    if (this.b) {
      return;
    }
    const dataStr = typeof data === "string" ? data : this.d.write(data);
    this.k(dataStr);
  }
  k(decodedData) {
    let newlineIdx = decodedData.indexOf("\n");
    const dataStr = this.a + decodedData;
    if (newlineIdx >= 0) {
      newlineIdx += this.a.length;
    } else {
      this.a = dataStr;
      return;
    }
    let prevIdx = 0;
    while (newlineIdx >= 0) {
      this.m(dataStr.substring(prevIdx, newlineIdx).trim());
      prevIdx = newlineIdx + 1;
      newlineIdx = dataStr.indexOf("\n", prevIdx);
    }
    this.a = dataStr.substring(prevIdx);
  }
  m(outputLine) {
    if (this.b || !outputLine) {
      return;
    }
    let parsedLine;
    try {
      parsedLine = JSON.parse(outputLine);
    } catch (e) {
      throw new Error(`malformed line from rg: ${outputLine}`);
    }
    if (parsedLine.type === "match") {
      const matchPath = bytesOrTextToString(parsedLine.data.path);
      const uri = URI.joinPath(this.h, matchPath);
      const result = this.n(parsedLine.data, uri);
      this.p(result);
      if (this.c) {
        this.cancel();
        this.emit("hitLimit");
      }
    } else if (parsedLine.type === "context") {
      const contextPath = bytesOrTextToString(parsedLine.data.path);
      const uri = URI.joinPath(this.h, contextPath);
      const result = this.o(parsedLine.data, uri);
      result.forEach((r) => this.p(r));
    }
  }
  n(data, uri) {
    const lineNumber = data.line_number - 1;
    const fullText = bytesOrTextToString(data.lines);
    const fullTextBytes = Buffer.from(fullText);
    let prevMatchEnd = 0;
    let prevMatchEndCol = 0;
    let prevMatchEndLine = lineNumber;
    if (data.submatches.length === 0) {
      data.submatches.push(fullText.length ? { start: 0, end: 1, match: { text: fullText[0] } } : { start: 0, end: 0, match: { text: "" } });
    }
    const ranges = $Mb(data.submatches.map((match, i) => {
      if (this.c) {
        return null;
      }
      this.f++;
      if (this.f >= this.g) {
        this.c = true;
      }
      const matchText = bytesOrTextToString(match.match);
      const inBetweenText = fullTextBytes.slice(prevMatchEnd, match.start).toString();
      const inBetweenStats = getNumLinesAndLastNewlineLength(inBetweenText);
      const startCol = inBetweenStats.numLines > 0 ? inBetweenStats.lastLineLength : inBetweenStats.lastLineLength + prevMatchEndCol;
      const stats = getNumLinesAndLastNewlineLength(matchText);
      const startLineNumber = inBetweenStats.numLines + prevMatchEndLine;
      const endLineNumber = stats.numLines + startLineNumber;
      const endCol = stats.numLines > 0 ? stats.lastLineLength : stats.lastLineLength + startCol;
      prevMatchEnd = match.end;
      prevMatchEndCol = endCol;
      prevMatchEndLine = endLineNumber;
      return new $KN(startLineNumber, startCol, endLineNumber, endCol);
    }));
    const searchRange = $4b(ranges, $gzc);
    const internalResult = new $YN(fullText, searchRange, this.j);
    return new $LN(uri, internalResult.rangeLocations.map((e) => ({
      sourceRange: $hzc(e.source),
      previewRange: $hzc(e.preview)
    })), internalResult.previewText);
  }
  o(data, uri) {
    const text = bytesOrTextToString(data.lines);
    const startLine = data.line_number;
    return text.replace(/\r?\n$/, "").split("\n").map((line, i) => new $MN(uri, line, startLine + i));
  }
  p(match) {
    this.emit("result", match);
  }
};
function bytesOrTextToString(obj) {
  return obj.bytes ? Buffer.from(obj.bytes, "base64").toString() : obj.text;
}
function getNumLinesAndLastNewlineLength(text) {
  const re = /\n/g;
  let numLines = 0;
  let lastNewlineIdx = -1;
  let match;
  while (match = re.exec(text)) {
    numLines++;
    lastNewlineIdx = match.index;
  }
  const lastLineLength = lastNewlineIdx >= 0 ? text.length - lastNewlineIdx - 1 : text.length;
  return { numLines, lastLineLength };
}
function $qzc(query, options2) {
  const args2 = ["--hidden", "--no-require-git"];
  args2.push(query.isCaseSensitive ? "--case-sensitive" : "--ignore-case");
  const { doubleStarIncludes, otherIncludes } = $a(options2.folderOptions.includes, (include) => include.startsWith("**") ? "doubleStarIncludes" : "otherIncludes");
  if (otherIncludes && otherIncludes.length) {
    const uniqueOthers = /* @__PURE__ */ new Set();
    otherIncludes.forEach((other) => {
      uniqueOthers.add(other);
    });
    args2.push("-g", "!*");
    uniqueOthers.forEach((otherIncude) => {
      spreadGlobComponents(otherIncude).map($fzc).forEach((globArg) => {
        args2.push("-g", globArg);
      });
    });
  }
  if (doubleStarIncludes && doubleStarIncludes.length) {
    doubleStarIncludes.forEach((globArg) => {
      args2.push("-g", globArg);
    });
  }
  options2.folderOptions.excludes.map((e) => typeof e === "string" ? e : e.pattern).map($fzc).forEach((rgGlob) => args2.push("-g", `!${rgGlob}`));
  if (options2.maxFileSize) {
    args2.push("--max-filesize", options2.maxFileSize + "");
  }
  if (options2.folderOptions.useIgnoreFiles.local) {
    if (!options2.folderOptions.useIgnoreFiles.parent) {
      args2.push("--no-ignore-parent");
    }
  } else {
    args2.push("--no-ignore");
  }
  if (options2.folderOptions.followSymlinks) {
    args2.push("--follow");
  }
  if (options2.folderOptions.encoding && options2.folderOptions.encoding !== "utf8") {
    args2.push("--encoding", options2.folderOptions.encoding);
  }
  if (options2.numThreads) {
    args2.push("--threads", `${options2.numThreads}`);
  }
  if (query.pattern === "--") {
    query.isRegExp = true;
    query.pattern = "\\-\\-";
  }
  if (query.isMultiline && !query.isRegExp) {
    query.pattern = $Af(query.pattern);
    query.isRegExp = true;
  }
  if (options2.usePCRE2) {
    args2.push("--pcre2");
  }
  args2.push("--crlf");
  if (query.isRegExp) {
    query.pattern = $rzc(query.pattern);
    args2.push("--engine", "auto");
  }
  let searchPatternAfterDoubleDashes;
  if (query.isWordMatch) {
    const regexp = $Jf(query.pattern, !!query.isRegExp, { wholeWord: query.isWordMatch });
    const regexpStr = regexp.source.replace(/\\\//g, "/");
    args2.push("--regexp", regexpStr);
  } else if (query.isRegExp) {
    let fixedRegexpQuery = $szc(query.pattern);
    fixedRegexpQuery = $tzc(fixedRegexpQuery);
    args2.push("--regexp", fixedRegexpQuery);
  } else {
    searchPatternAfterDoubleDashes = query.pattern;
    args2.push("--fixed-strings");
  }
  args2.push("--no-config");
  if (!options2.folderOptions.useIgnoreFiles.global) {
    args2.push("--no-ignore-global");
  }
  args2.push("--json");
  if (query.isMultiline) {
    args2.push("--multiline");
  }
  if (options2.surroundingContext) {
    args2.push("--before-context", options2.surroundingContext + "");
    args2.push("--after-context", options2.surroundingContext + "");
  }
  args2.push("--");
  if (searchPatternAfterDoubleDashes) {
    args2.push(searchPatternAfterDoubleDashes);
  }
  args2.push(".");
  return args2;
}
function spreadGlobComponents(globComponent) {
  const globComponentWithBraceExpansion = $uzc(globComponent);
  return globComponentWithBraceExpansion.flatMap((globArg) => {
    const components = $Bl(globArg, "/");
    return components.map((_, i) => components.slice(0, i + 1).join("/"));
  });
}
function $rzc(pattern) {
  const unicodePattern = /((?:[^\\]|^)(?:\\\\)*)\\u([a-z0-9]{4})/gi;
  while (pattern.match(unicodePattern)) {
    pattern = pattern.replace(unicodePattern, `$1\\x{$2}`);
  }
  const unicodePatternWithBraces = /((?:[^\\]|^)(?:\\\\)*)\\u\{([a-z0-9]{4})\}/gi;
  while (pattern.match(unicodePatternWithBraces)) {
    pattern = pattern.replace(unicodePatternWithBraces, `$1\\x{$2}`);
  }
  return pattern;
}
var isLookBehind = (node) => node.type === "Assertion" && node.kind === "lookbehind";
function $szc(pattern) {
  let re;
  try {
    re = new RegExpParser().parsePattern(pattern);
  } catch {
    return pattern;
  }
  let output = "";
  let lastEmittedIndex = 0;
  const replace = (start, end, text) => {
    output += pattern.slice(lastEmittedIndex, start) + text;
    lastEmittedIndex = end;
  };
  const context = [];
  const visitor = new RegExpVisitor({
    onCharacterEnter(char) {
      if (char.raw !== "\\n") {
        return;
      }
      const parent = context[0];
      if (!parent) {
        replace(char.start, char.end, "\\r?\\n");
      } else if (context.some(isLookBehind)) {
      } else if (parent.type === "CharacterClass") {
        if (parent.negate) {
          const otherContent = pattern.slice(parent.start + 2, char.start) + pattern.slice(char.end, parent.end - 1);
          if (parent.parent?.type === "Quantifier") {
            replace(parent.start, parent.end, otherContent ? `[^${otherContent}]` : ".");
          } else {
            replace(parent.start, parent.end, "(?!\\r?\\n" + (otherContent ? `|[${otherContent}]` : "") + ")");
          }
        } else {
          const otherContent = pattern.slice(parent.start + 1, char.start) + pattern.slice(char.end, parent.end - 1);
          replace(parent.start, parent.end, otherContent === "" ? "\\r?\\n" : `(?:[${otherContent}]|\\r?\\n)`);
        }
      } else if (parent.type === "Quantifier") {
        replace(char.start, char.end, "(?:\\r?\\n)");
      }
    },
    onQuantifierEnter(node) {
      context.unshift(node);
    },
    onQuantifierLeave() {
      context.shift();
    },
    onCharacterClassRangeEnter(node) {
      context.unshift(node);
    },
    onCharacterClassRangeLeave() {
      context.shift();
    },
    onCharacterClassEnter(node) {
      context.unshift(node);
    },
    onCharacterClassLeave() {
      context.shift();
    },
    onAssertionEnter(node) {
      if (isLookBehind(node)) {
        context.push(node);
      }
    },
    onAssertionLeave(node) {
      if (context[0] === node) {
        context.shift();
      }
    }
  });
  visitor.visit(re);
  output += pattern.slice(lastEmittedIndex);
  return output;
}
function $tzc(pattern) {
  return pattern.replace(/\n/g, "\\r?\\n");
}
function getEscapeAwareSplitStringForRipgrep(pattern) {
  let inBraces = false;
  let escaped = false;
  let fixedStart = "";
  let strInBraces = "";
  for (let i = 0; i < pattern.length; i++) {
    const char = pattern[i];
    switch (char) {
      case "\\":
        if (escaped) {
          if (inBraces) {
            strInBraces += "\\" + char;
          } else {
            fixedStart += "\\" + char;
          }
          escaped = false;
        } else {
          escaped = true;
        }
        break;
      case "{":
        if (escaped) {
          if (inBraces) {
            strInBraces += char;
          } else {
            fixedStart += char;
          }
          escaped = false;
        } else {
          if (inBraces) {
            return { strInBraces: fixedStart + "{" + strInBraces + "{" + pattern.substring(i + 1) };
          } else {
            inBraces = true;
          }
        }
        break;
      case "}":
        if (escaped) {
          if (inBraces) {
            strInBraces += char;
          } else {
            fixedStart += char;
          }
          escaped = false;
        } else if (inBraces) {
          return { fixedStart, strInBraces, fixedEnd: pattern.substring(i + 1) };
        } else {
          fixedStart += char;
        }
        break;
      default:
        if (inBraces) {
          strInBraces += (escaped ? "\\" : "") + char;
        } else {
          fixedStart += (escaped ? "\\" : "") + char;
        }
        escaped = false;
        break;
    }
  }
  return { strInBraces: fixedStart + (inBraces ? "{" + strInBraces : "") };
}
function $uzc(pattern) {
  const { fixedStart, strInBraces, fixedEnd } = getEscapeAwareSplitStringForRipgrep(pattern);
  if (fixedStart === void 0 || fixedEnd === void 0) {
    return [strInBraces];
  }
  let arr = $Bl(strInBraces, ",");
  if (!arr.length) {
    arr = [""];
  }
  const ends = $uzc(fixedEnd);
  return arr.flatMap((elem) => {
    const start = fixedStart + elem;
    return ends.map((end) => {
      return start + end;
    });
  });
}

// out-build/vs/amdX.js
var DefineCall = class {
  constructor(id2, dependencies, callback) {
    this.id = id2;
    this.dependencies = dependencies;
    this.callback = callback;
  }
};
var AMDModuleImporterState;
(function(AMDModuleImporterState2) {
  AMDModuleImporterState2[AMDModuleImporterState2["Uninitialized"] = 1] = "Uninitialized";
  AMDModuleImporterState2[AMDModuleImporterState2["InitializedInternal"] = 2] = "InitializedInternal";
  AMDModuleImporterState2[AMDModuleImporterState2["InitializedExternal"] = 3] = "InitializedExternal";
})(AMDModuleImporterState || (AMDModuleImporterState = {}));
var AMDModuleImporter = class _AMDModuleImporter {
  static {
    this.INSTANCE = new _AMDModuleImporter();
  }
  constructor() {
    this.a = typeof self === "object" && self.constructor && self.constructor.name === "DedicatedWorkerGlobalScope";
    this.b = typeof document === "object";
    this.c = [];
    this.d = AMDModuleImporterState.Uninitialized;
  }
  g() {
    if (this.d === AMDModuleImporterState.Uninitialized) {
      if (globalThis.define) {
        this.d = AMDModuleImporterState.InitializedExternal;
        return;
      }
    } else {
      return;
    }
    this.d = AMDModuleImporterState.InitializedInternal;
    globalThis.define = (id2, dependencies, callback) => {
      if (typeof id2 !== "string") {
        callback = dependencies;
        dependencies = id2;
        id2 = null;
      }
      if (typeof dependencies !== "object" || !Array.isArray(dependencies)) {
        callback = dependencies;
        dependencies = null;
      }
      this.c.push(new DefineCall(id2, dependencies, callback));
    };
    globalThis.define.amd = true;
    if (this.b) {
      this.f = globalThis._VSCODE_WEB_PACKAGE_TTP ?? window.trustedTypes?.createPolicy("amdLoader", {
        createScriptURL(value) {
          if (value.startsWith(window.location.origin)) {
            return value;
          }
          if (value.startsWith(`${Schemas.vscodeFileResource}://${$hh}`)) {
            return value;
          }
          throw new Error(`[trusted_script_src] Invalid script url: ${value}`);
        }
      });
    } else if (this.a) {
      this.f = globalThis._VSCODE_WEB_PACKAGE_TTP ?? globalThis.trustedTypes?.createPolicy("amdLoader", {
        createScriptURL(value) {
          return value;
        }
      });
    }
  }
  async load(scriptSrc) {
    this.g();
    if (this.d === AMDModuleImporterState.InitializedExternal) {
      return new Promise((resolve) => {
        const tmpModuleId = $ps();
        globalThis.define(tmpModuleId, [scriptSrc], function(moduleResult) {
          resolve(moduleResult);
        });
      });
    }
    const defineCall = await (this.a ? this.i(scriptSrc) : this.b ? this.h(scriptSrc) : this.j(scriptSrc));
    if (!defineCall) {
      console.warn(`Did not receive a define call from script ${scriptSrc}`);
      return void 0;
    }
    const exports2 = {};
    const dependencyObjs = [];
    const dependencyModules = [];
    if (Array.isArray(defineCall.dependencies)) {
      for (const mod of defineCall.dependencies) {
        if (mod === "exports") {
          dependencyObjs.push(exports2);
        } else {
          dependencyModules.push(mod);
        }
      }
    }
    if (dependencyModules.length > 0) {
      throw new Error(`Cannot resolve dependencies for script ${scriptSrc}. The dependencies are: ${dependencyModules.join(", ")}`);
    }
    if (typeof defineCall.callback === "function") {
      return defineCall.callback(...dependencyObjs) ?? exports2;
    } else {
      return defineCall.callback;
    }
  }
  h(scriptSrc) {
    return new Promise((resolve, reject) => {
      const scriptElement = document.createElement("script");
      scriptElement.setAttribute("async", "async");
      scriptElement.setAttribute("type", "text/javascript");
      const unbind = () => {
        scriptElement.removeEventListener("load", loadEventListener);
        scriptElement.removeEventListener("error", errorEventListener);
      };
      const loadEventListener = (e) => {
        unbind();
        resolve(this.c.pop());
      };
      const errorEventListener = (e) => {
        unbind();
        reject(e);
      };
      scriptElement.addEventListener("load", loadEventListener);
      scriptElement.addEventListener("error", errorEventListener);
      if (this.f) {
        scriptSrc = this.f.createScriptURL(scriptSrc);
      }
      scriptElement.setAttribute("src", scriptSrc);
      window.document.getElementsByTagName("head")[0].appendChild(scriptElement);
    });
  }
  async i(scriptSrc) {
    if (this.f) {
      scriptSrc = this.f.createScriptURL(scriptSrc);
    }
    await import(scriptSrc);
    return this.c.pop();
  }
  async j(scriptSrc) {
    try {
      const fs7 = (await import(`${"fs"}`)).default;
      const vm = (await import(`${"vm"}`)).default;
      const module2 = (await import(`${"module"}`)).default;
      const filePath = URI.parse(scriptSrc).fsPath;
      const content = fs7.readFileSync(filePath).toString();
      const scriptSource = module2.wrap(content.replace(/^#!.*/, ""));
      const script = new vm.Script(scriptSource);
      const compileWrapper = script.runInThisContext();
      compileWrapper.apply();
      return this.c.pop();
    } catch (error) {
      throw error;
    }
  }
};

// out-build/vs/workbench/services/textfile/common/encoding.js
var AUTO_ENCODING_GUESS_MIN_BYTES = 512 * 8;
var AUTO_ENCODING_GUESS_MAX_BYTES = 512 * 128;
var DecodeStreamErrorKind;
(function(DecodeStreamErrorKind2) {
  DecodeStreamErrorKind2[DecodeStreamErrorKind2["STREAM_IS_BINARY"] = 1] = "STREAM_IS_BINARY";
})(DecodeStreamErrorKind || (DecodeStreamErrorKind = {}));
function $IJ(enc) {
  switch (enc) {
    case "shiftjis":
      return "shift-jis";
    case "utf16le":
      return "utf-16le";
    case "utf16be":
      return "utf-16be";
    case "big5hkscs":
      return "big5-hkscs";
    case "eucjp":
      return "euc-jp";
    case "euckr":
      return "euc-kr";
    case "koi8r":
      return "koi8-r";
    case "koi8u":
      return "koi8-u";
    case "macroman":
      return "x-mac-roman";
    case "utf8bom":
      return "utf8";
    default: {
      const m = enc.match(/windows(\d+)/);
      if (m) {
        return "windows-" + m[1];
      }
      return enc;
    }
  }
}
var $KJ = {
  utf8: {
    labelLong: "UTF-8",
    labelShort: "UTF-8",
    order: 1,
    alias: "utf8bom",
    guessableName: "UTF-8"
  },
  utf8bom: {
    labelLong: "UTF-8 with BOM",
    labelShort: "UTF-8 with BOM",
    encodeOnly: true,
    order: 2,
    alias: "utf8"
  },
  utf16le: {
    labelLong: "UTF-16 LE",
    labelShort: "UTF-16 LE",
    order: 3,
    guessableName: "UTF-16LE"
  },
  utf16be: {
    labelLong: "UTF-16 BE",
    labelShort: "UTF-16 BE",
    order: 4,
    guessableName: "UTF-16BE"
  },
  windows1252: {
    labelLong: "Western (Windows 1252)",
    labelShort: "Windows 1252",
    order: 5,
    guessableName: "windows-1252"
  },
  iso88591: {
    labelLong: "Western (ISO 8859-1)",
    labelShort: "ISO 8859-1",
    order: 6
  },
  iso88593: {
    labelLong: "Western (ISO 8859-3)",
    labelShort: "ISO 8859-3",
    order: 7
  },
  iso885915: {
    labelLong: "Western (ISO 8859-15)",
    labelShort: "ISO 8859-15",
    order: 8
  },
  macroman: {
    labelLong: "Western (Mac Roman)",
    labelShort: "Mac Roman",
    order: 9
  },
  cp437: {
    labelLong: "DOS (CP 437)",
    labelShort: "CP437",
    order: 10
  },
  windows1256: {
    labelLong: "Arabic (Windows 1256)",
    labelShort: "Windows 1256",
    order: 11
  },
  iso88596: {
    labelLong: "Arabic (ISO 8859-6)",
    labelShort: "ISO 8859-6",
    order: 12
  },
  windows1257: {
    labelLong: "Baltic (Windows 1257)",
    labelShort: "Windows 1257",
    order: 13
  },
  iso88594: {
    labelLong: "Baltic (ISO 8859-4)",
    labelShort: "ISO 8859-4",
    order: 14
  },
  iso885914: {
    labelLong: "Celtic (ISO 8859-14)",
    labelShort: "ISO 8859-14",
    order: 15
  },
  windows1250: {
    labelLong: "Central European (Windows 1250)",
    labelShort: "Windows 1250",
    order: 16,
    guessableName: "windows-1250"
  },
  iso88592: {
    labelLong: "Central European (ISO 8859-2)",
    labelShort: "ISO 8859-2",
    order: 17,
    guessableName: "ISO-8859-2"
  },
  cp852: {
    labelLong: "Central European (CP 852)",
    labelShort: "CP 852",
    order: 18
  },
  windows1251: {
    labelLong: "Cyrillic (Windows 1251)",
    labelShort: "Windows 1251",
    order: 19,
    guessableName: "windows-1251"
  },
  cp866: {
    labelLong: "Cyrillic (CP 866)",
    labelShort: "CP 866",
    order: 20,
    guessableName: "IBM866"
  },
  iso88595: {
    labelLong: "Cyrillic (ISO 8859-5)",
    labelShort: "ISO 8859-5",
    order: 21,
    guessableName: "ISO-8859-5"
  },
  koi8r: {
    labelLong: "Cyrillic (KOI8-R)",
    labelShort: "KOI8-R",
    order: 22,
    guessableName: "KOI8-R"
  },
  koi8u: {
    labelLong: "Cyrillic (KOI8-U)",
    labelShort: "KOI8-U",
    order: 23
  },
  iso885913: {
    labelLong: "Estonian (ISO 8859-13)",
    labelShort: "ISO 8859-13",
    order: 24
  },
  windows1253: {
    labelLong: "Greek (Windows 1253)",
    labelShort: "Windows 1253",
    order: 25,
    guessableName: "windows-1253"
  },
  iso88597: {
    labelLong: "Greek (ISO 8859-7)",
    labelShort: "ISO 8859-7",
    order: 26,
    guessableName: "ISO-8859-7"
  },
  windows1255: {
    labelLong: "Hebrew (Windows 1255)",
    labelShort: "Windows 1255",
    order: 27,
    guessableName: "windows-1255"
  },
  iso88598: {
    labelLong: "Hebrew (ISO 8859-8)",
    labelShort: "ISO 8859-8",
    order: 28,
    guessableName: "ISO-8859-8"
  },
  iso885910: {
    labelLong: "Nordic (ISO 8859-10)",
    labelShort: "ISO 8859-10",
    order: 29
  },
  iso885916: {
    labelLong: "Romanian (ISO 8859-16)",
    labelShort: "ISO 8859-16",
    order: 30
  },
  windows1254: {
    labelLong: "Turkish (Windows 1254)",
    labelShort: "Windows 1254",
    order: 31
  },
  iso88599: {
    labelLong: "Turkish (ISO 8859-9)",
    labelShort: "ISO 8859-9",
    order: 32
  },
  windows1258: {
    labelLong: "Vietnamese (Windows 1258)",
    labelShort: "Windows 1258",
    order: 33
  },
  gbk: {
    labelLong: "Simplified Chinese (GBK)",
    labelShort: "GBK",
    order: 34
  },
  gb18030: {
    labelLong: "Simplified Chinese (GB18030)",
    labelShort: "GB18030",
    order: 35
  },
  cp950: {
    labelLong: "Traditional Chinese (Big5)",
    labelShort: "Big5",
    order: 36,
    guessableName: "Big5"
  },
  big5hkscs: {
    labelLong: "Traditional Chinese (Big5-HKSCS)",
    labelShort: "Big5-HKSCS",
    order: 37
  },
  shiftjis: {
    labelLong: "Japanese (Shift JIS)",
    labelShort: "Shift JIS",
    order: 38,
    guessableName: "SHIFT_JIS"
  },
  eucjp: {
    labelLong: "Japanese (EUC-JP)",
    labelShort: "EUC-JP",
    order: 39,
    guessableName: "EUC-JP"
  },
  euckr: {
    labelLong: "Korean (EUC-KR)",
    labelShort: "EUC-KR",
    order: 40,
    guessableName: "EUC-KR"
  },
  windows874: {
    labelLong: "Thai (Windows 874)",
    labelShort: "Windows 874",
    order: 41
  },
  iso885911: {
    labelLong: "Latin/Thai (ISO 8859-11)",
    labelShort: "ISO 8859-11",
    order: 42
  },
  koi8ru: {
    labelLong: "Cyrillic (KOI8-RU)",
    labelShort: "KOI8-RU",
    order: 43
  },
  koi8t: {
    labelLong: "Tajik (KOI8-T)",
    labelShort: "KOI8-T",
    order: 44
  },
  gb2312: {
    labelLong: "Simplified Chinese (GB 2312)",
    labelShort: "GB 2312",
    order: 45,
    guessableName: "GB2312"
  },
  cp865: {
    labelLong: "Nordic DOS (CP 865)",
    labelShort: "CP 865",
    order: 46
  },
  cp850: {
    labelLong: "Western European DOS (CP 850)",
    labelShort: "CP 850",
    order: 47
  }
};
var $LJ = (() => {
  const guessableEncodings = {};
  for (const encoding in $KJ) {
    if ($KJ[encoding].guessableName) {
      guessableEncodings[encoding] = $KJ[encoding];
    }
  }
  return guessableEncodings;
})();

// out-build/vs/workbench/services/search/node/textSearchManager.js
var $vzc = class extends $hyc {
  constructor(query, provider, _pfs = pfs_exports, processType = "searchProcess") {
    super({ query, provider }, {
      readdir: (resource) => _pfs.Promises.readdir(resource.fsPath),
      toCanonicalName: (name) => $IJ(name)
    }, processType);
  }
};

// out-build/vs/workbench/services/search/node/textSearchAdapter.js
var $wzc = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  search(token, onResult, onMessage) {
    if ((!this.a.folderQueries || !this.a.folderQueries.length) && (!this.a.extraFileResources || !this.a.extraFileResources.length)) {
      return Promise.resolve({
        type: "success",
        limitHit: false,
        stats: {
          type: "searchProcess"
        },
        messages: []
      });
    }
    const pretendOutputChannel = {
      appendLine(msg) {
        onMessage({ message: msg });
      }
    };
    const textSearchManager = new $vzc(this.a, new $ozc(pretendOutputChannel, this.b), pfs_exports);
    return new Promise((resolve, reject) => {
      return textSearchManager.search((matches) => {
        onResult(matches.map(fileMatchToSerialized));
      }, token).then((c) => resolve({ limitHit: c.limitHit ?? false, type: "success", stats: c.stats, messages: [] }), reject);
    });
  }
};
function fileMatchToSerialized(match) {
  return {
    path: match.resource && match.resource.fsPath,
    results: match.results,
    numMatches: (match.results || []).reduce((sum, r) => {
      if ($UN(r)) {
        const m = r;
        return sum + m.rangeLocations.length;
      } else {
        return sum + 1;
      }
    }, 0)
  };
}

// out-build/vs/workbench/services/search/node/rawSearchService.js
var $xzc = class _$xzc {
  static {
    this.a = 512;
  }
  constructor(d = "searchProcess", f) {
    this.d = d;
    this.f = f;
    this.b = /* @__PURE__ */ Object.create(null);
  }
  fileSearch(config) {
    let promise;
    const query = reviveQuery(config);
    const emitter = new $ze({
      onDidAddFirstListener: () => {
        promise = $Hh(async (token) => {
          const numThreads = await this.f?.();
          return this.doFileSearchWithEngine($nzc, query, (p) => emitter.fire(p), token, _$xzc.a, numThreads);
        });
        promise.then((c) => emitter.fire(c), (err) => emitter.fire({ type: "error", error: { message: err.message, stack: err.stack } }));
      },
      onDidRemoveLastListener: () => {
        promise.cancel();
      }
    });
    return emitter.event;
  }
  textSearch(rawQuery) {
    let promise;
    const query = reviveQuery(rawQuery);
    const emitter = new $ze({
      onDidAddFirstListener: () => {
        promise = $Hh((token) => {
          return this.g(query, (p) => emitter.fire(p), token);
        });
        promise.then((c) => emitter.fire(c), (err) => emitter.fire({ type: "error", error: { message: err.message, stack: err.stack } }));
      },
      onDidRemoveLastListener: () => {
        promise.cancel();
      }
    });
    return emitter.event;
  }
  async g(config, progressCallback, token) {
    config.maxFileSize = this.h().maxFileSize;
    const numThreads = await this.f?.();
    const engine = new $wzc(config, numThreads);
    return engine.search(token, progressCallback, progressCallback);
  }
  h() {
    return {
      maxFileSize: 16 * $Sm.GB
    };
  }
  doFileSearch(config, numThreads, progressCallback, token) {
    return this.doFileSearchWithEngine($nzc, config, progressCallback, token, _$xzc.a, numThreads);
  }
  doFileSearchWithEngine(EngineClass, config, progressCallback, token, batchSize = _$xzc.a, threads) {
    let resultCount = 0;
    const fileProgressCallback = (progress) => {
      if (Array.isArray(progress)) {
        resultCount += progress.length;
        progressCallback(progress.map((m) => this.j(m)));
      } else if (progress.relativePath) {
        resultCount++;
        progressCallback(this.j(progress));
      } else {
        progressCallback(progress);
      }
    };
    if (config.sortByScore) {
      let sortedSearch = this.n(config, fileProgressCallback, token);
      if (!sortedSearch) {
        const walkerConfig = config.maxResults ? Object.assign({}, config, { maxResults: null }) : config;
        const engine2 = new EngineClass(walkerConfig, threads);
        sortedSearch = this.k(engine2, config, progressCallback, fileProgressCallback, token);
      }
      return new Promise((c, e) => {
        sortedSearch.then(([result, rawMatches]) => {
          const serializedMatches = rawMatches.map((rawMatch) => this.j(rawMatch));
          this.q(serializedMatches, progressCallback, batchSize);
          c(result);
        }, e);
      });
    }
    const engine = new EngineClass(config, threads);
    return this.s(engine, fileProgressCallback, batchSize, token).then((complete) => {
      return {
        limitHit: complete.limitHit,
        type: "success",
        stats: {
          detailStats: complete.stats,
          type: this.d,
          fromCache: false,
          resultCount,
          sortingTime: void 0
        },
        messages: []
      };
    });
  }
  j(match) {
    return { path: match.base ? $nc(match.base, match.relativePath) : match.relativePath };
  }
  k(engine, config, progressCallback, fileProgressCallback, token) {
    const emitter = new $ze();
    let allResultsPromise = $Hh((token2) => {
      let results = [];
      const innerProgressCallback = (progress) => {
        if (Array.isArray(progress)) {
          results = progress;
        } else {
          fileProgressCallback(progress);
          emitter.fire(progress);
        }
      };
      return this.s(engine, innerProgressCallback, -1, token2).then((result) => {
        return [result, results];
      });
    });
    let cache;
    if (config.cacheKey) {
      cache = this.l(config.cacheKey);
      const cacheRow = {
        promise: allResultsPromise,
        event: emitter.event,
        resolved: false
      };
      cache.resultsToSearchCache[config.filePattern || ""] = cacheRow;
      allResultsPromise.then(() => {
        cacheRow.resolved = true;
      }, (err) => {
        delete cache.resultsToSearchCache[config.filePattern || ""];
      });
      allResultsPromise = this.t(allResultsPromise);
    }
    return allResultsPromise.then(([result, results]) => {
      const scorerCache = cache ? cache.scorerCache : /* @__PURE__ */ Object.create(null);
      const sortSW = (typeof config.maxResults !== "number" || config.maxResults > 0) && $te.create(false);
      return this.o(config, results, scorerCache, token).then((sortedResults) => {
        const sortingTime = sortSW ? sortSW.elapsed() : -1;
        return [{
          type: "success",
          stats: {
            detailStats: result.stats,
            sortingTime,
            fromCache: false,
            type: this.d,
            resultCount: sortedResults.length
          },
          messages: result.messages,
          limitHit: result.limitHit || typeof config.maxResults === "number" && results.length > config.maxResults
        }, sortedResults];
      });
    });
  }
  l(cacheKey) {
    const existing = this.b[cacheKey];
    if (existing) {
      return existing;
    }
    return this.b[cacheKey] = new Cache2();
  }
  n(config, progressCallback, token) {
    const cache = config.cacheKey && this.b[config.cacheKey];
    if (!cache) {
      return void 0;
    }
    const cached = this.r(cache, config.filePattern || "", progressCallback, token);
    if (cached) {
      return cached.then(([result, results, cacheStats]) => {
        const sortSW = $te.create(false);
        return this.o(config, results, cache.scorerCache, token).then((sortedResults) => {
          const sortingTime = sortSW.elapsed();
          const stats = {
            fromCache: true,
            detailStats: cacheStats,
            type: this.d,
            resultCount: results.length,
            sortingTime
          };
          return [
            {
              type: "success",
              limitHit: result.limitHit || typeof config.maxResults === "number" && results.length > config.maxResults,
              stats,
              messages: []
            },
            sortedResults
          ];
        });
      });
    }
    return void 0;
  }
  o(config, results, scorerCache, token) {
    const query = $VM(config.filePattern || "");
    const compare3 = (matchA, matchB) => $UM(matchA, matchB, query, true, FileMatchItemAccessor, scorerCache);
    const maxResults = typeof config.maxResults === "number" ? config.maxResults : $SN;
    return $Lb(results, compare3, maxResults, 1e4, token);
  }
  q(results, progressCb, batchSize) {
    if (batchSize && batchSize > 0) {
      for (let i = 0; i < results.length; i += batchSize) {
        progressCb(results.slice(i, i + batchSize));
      }
    } else {
      progressCb(results);
    }
  }
  r(cache, searchValue, progressCallback, token) {
    const cacheLookupSW = $te.create(false);
    const hasPathSep = searchValue.indexOf(sep) >= 0;
    let cachedRow;
    for (const previousSearch in cache.resultsToSearchCache) {
      if (searchValue.startsWith(previousSearch)) {
        if (hasPathSep && previousSearch.indexOf(sep) < 0 && previousSearch !== "") {
          continue;
        }
        const row = cache.resultsToSearchCache[previousSearch];
        cachedRow = {
          promise: this.t(row.promise),
          event: row.event,
          resolved: row.resolved
        };
        break;
      }
    }
    if (!cachedRow) {
      return null;
    }
    const cacheLookupTime = cacheLookupSW.elapsed();
    const cacheFilterSW = $te.create(false);
    const listener = cachedRow.event(progressCallback);
    if (token) {
      token.onCancellationRequested(() => {
        listener.dispose();
      });
    }
    return cachedRow.promise.then(([complete, cachedEntries]) => {
      if (token && token.isCancellationRequested) {
        throw $mb();
      }
      const results = [];
      const normalizedSearchValueLowercase = $VM(searchValue).normalizedLowercase;
      for (const entry of cachedEntries) {
        if (!$0N(entry, normalizedSearchValueLowercase)) {
          continue;
        }
        results.push(entry);
      }
      return [complete, results, {
        cacheWasResolved: cachedRow.resolved,
        cacheLookupTime,
        cacheFilterTime: cacheFilterSW.elapsed(),
        cacheEntryCount: cachedEntries.length
      }];
    });
  }
  s(engine, progressCallback, batchSize, token) {
    return new Promise((c, e) => {
      let batch = [];
      token?.onCancellationRequested(() => engine.cancel());
      engine.search((match) => {
        if (match) {
          if (batchSize) {
            batch.push(match);
            if (batchSize > 0 && batch.length >= batchSize) {
              progressCallback(batch);
              batch = [];
            }
          } else {
            progressCallback(match);
          }
        }
      }, (progress) => {
        progressCallback(progress);
      }, (error, complete) => {
        if (batch.length) {
          progressCallback(batch);
        }
        if (error) {
          progressCallback({ message: "Search finished. Error: " + error.message });
          e(error);
        } else {
          progressCallback({ message: "Search finished. Stats: " + JSON.stringify(complete.stats) });
          c(complete);
        }
      });
    });
  }
  clearCache(cacheKey) {
    delete this.b[cacheKey];
    return Promise.resolve(void 0);
  }
  /**
   * Return a CancelablePromise which is not actually cancelable
   * TODO@rob - Is this really needed?
   */
  t(promise) {
    return new class {
      get [Symbol.toStringTag]() {
        return this.toString();
      }
      cancel() {
      }
      then(resolve, reject) {
        return promise.then(resolve, reject);
      }
      catch(reject) {
        return this.then(void 0, reject);
      }
      finally(onFinally) {
        return promise.finally(onFinally);
      }
    }();
  }
};
var Cache2 = class {
  constructor() {
    this.resultsToSearchCache = /* @__PURE__ */ Object.create(null);
    this.scorerCache = /* @__PURE__ */ Object.create(null);
  }
};
var FileMatchItemAccessor = new class {
  getItemLabel(match) {
    return $rc(match.relativePath);
  }
  getItemDescription(match) {
    return $qc(match.relativePath);
  }
  getItemPath(match) {
    return match.relativePath;
  }
}();
function reviveQuery(rawQuery) {
  return {
    ...rawQuery,
    // TODO
    ...{
      folderQueries: rawQuery.folderQueries && rawQuery.folderQueries.map(reviveFolderQuery2),
      extraFileResources: rawQuery.extraFileResources && rawQuery.extraFileResources.map((components) => URI.revive(components))
    }
  };
}
function reviveFolderQuery2(rawFolderQuery) {
  return $cu(rawFolderQuery);
}

// out-build/vs/workbench/services/search/node/ripgrepSearchProvider.js
var $yzc = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = /* @__PURE__ */ new Set();
    process.once("exit", () => this.f());
  }
  async provideTextSearchResults(query, options2, progress, token) {
    const numThreads = await this.c();
    const engine = new $ozc(this.b, numThreads);
    return Promise.all(options2.folderOptions.map((folderOption) => {
      const extendedOptions = {
        folderOptions: folderOption,
        numThreads,
        maxResults: options2.maxResults,
        previewOptions: options2.previewOptions,
        maxFileSize: options2.maxFileSize,
        surroundingContext: options2.surroundingContext
      };
      if (folderOption.folder.scheme === Schemas.vscodeUserData) {
        const translatedOptions = { ...extendedOptions, folder: folderOption.folder.with({ scheme: Schemas.file }) };
        const progressTranslator = new $VJ((data) => progress.report({ ...data, uri: data.uri.with({ scheme: folderOption.folder.scheme }) }));
        return this.d(token, (token2) => engine.provideTextSearchResultsWithRgOptions(query, translatedOptions, progressTranslator, token2));
      } else {
        return this.d(token, (token2) => engine.provideTextSearchResultsWithRgOptions(query, extendedOptions, progress, token2));
      }
    })).then((e) => {
      const complete = {
        // todo: get this to actually check
        limitHit: e.some((complete2) => !!complete2 && complete2.limitHit)
      };
      return complete;
    });
  }
  async d(token, fn) {
    const merged = mergedTokenSource(token);
    this.a.add(merged);
    const result = await fn(merged.token);
    this.a.delete(merged);
    return result;
  }
  f() {
    this.a.forEach((engine) => engine.cancel());
  }
};
function mergedTokenSource(token) {
  const tokenSource = new $ad();
  token.onCancellationRequested(() => tokenSource.cancel());
  return tokenSource;
}

// out-build/vs/workbench/api/node/extHostSearch.js
var $zzc = class $zzc2 extends $lyc {
  constructor(extHostRpc, initData, _uriTransformer, E, _logService) {
    super(extHostRpc, _uriTransformer, _logService);
    this.E = E;
    this.x = pfs_exports;
    this.y = -1;
    this.z = null;
    this.A = false;
    this.C = new $2c();
    this.D = false;
    this.getNumThreads = this.getNumThreads.bind(this);
    this.getNumThreadsCached = this.getNumThreadsCached.bind(this);
    this.F = this.F.bind(this);
    const outputChannel = new $izc("RipgrepSearchUD", this.s);
    this.C.add(this.registerTextSearchProvider(Schemas.vscodeUserData, new $yzc(outputChannel, this.getNumThreadsCached)));
    if (initData.remote.isRemote && initData.remote.authority) {
      this.G();
    }
    E.getConfigProvider().then((provider) => {
      if (this.D) {
        return;
      }
      this.C.add(provider.onDidChangeConfiguration(this.F));
    });
  }
  F(event) {
    if (!event.affectsConfiguration("search")) {
      return;
    }
    this.B = void 0;
  }
  async getNumThreads() {
    const configProvider = await this.E.getConfigProvider();
    const numThreads = configProvider.getConfiguration("search").get("ripgrep.maxThreads");
    return numThreads;
  }
  async getNumThreadsCached() {
    if (!this.B) {
      this.B = this.getNumThreads();
    }
    return this.B;
  }
  dispose() {
    this.D = true;
    this.C.dispose();
  }
  $enableExtensionHostSearch() {
    this.G();
  }
  G() {
    if (this.A) {
      return;
    }
    this.A = true;
    const outputChannel = new $izc("RipgrepSearchEH", this.s);
    this.C.add(this.registerTextSearchProvider(Schemas.file, new $yzc(outputChannel, this.getNumThreadsCached)));
    this.C.add(this.H(Schemas.file, new $xzc("fileSearchProvider", this.getNumThreadsCached)));
  }
  H(scheme, provider) {
    const handle = this.e++;
    this.z = provider;
    this.y = handle;
    this.c.$registerFileSearchProvider(handle, this.t(scheme));
    return $1c(() => {
      this.z = null;
      this.c.$unregisterProvider(handle);
    });
  }
  $provideFileSearchResults(handle, session, rawQuery, token) {
    const query = $myc(rawQuery);
    if (handle === this.y) {
      const start = Date.now();
      return this.I(handle, session, query, token).then((result) => {
        const elapsed = Date.now() - start;
        this.s.debug(`Ext host file search time: ${elapsed}ms`);
        return result;
      });
    }
    return super.$provideFileSearchResults(handle, session, rawQuery, token);
  }
  async doInternalFileSearchWithCustomCallback(rawQuery, token, handleFileMatch) {
    const onResult = (ev) => {
      if ($9N(ev)) {
        ev = [ev];
      }
      if (Array.isArray(ev)) {
        handleFileMatch(ev.map((m) => URI.file(m.path)));
        return;
      }
      if (ev.message) {
        this.s.debug("ExtHostSearch", ev.message);
      }
    };
    if (!this.z) {
      throw new Error("No internal file search handler");
    }
    const numThreads = await this.getNumThreadsCached();
    return this.z.doFileSearch(rawQuery, numThreads, onResult, token);
  }
  async I(handle, session, rawQuery, token) {
    return this.doInternalFileSearchWithCustomCallback(rawQuery, token, (data) => {
      this.c.$handleFileMatch(handle, session, data);
    });
  }
  $clearCache(cacheKey) {
    this.z?.clearCache(cacheKey);
    return super.$clearCache(cacheKey);
  }
  v(query, provider) {
    return new $vzc(query, provider, void 0, "textSearchProvider");
  }
};
$zzc = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $7wc),
  __param(3, $axc),
  __param(4, $wn)
], $zzc);

// out-build/vs/editor/common/languageSelector.js
function $qE(selector, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType) {
  if (Array.isArray(selector)) {
    let ret = 0;
    for (const filter of selector) {
      const value = $qE(filter, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType);
      if (value === 10) {
        return value;
      }
      if (value > ret) {
        ret = value;
      }
    }
    return ret;
  } else if (typeof selector === "string") {
    if (!candidateIsSynchronized) {
      return 0;
    }
    if (selector === "*") {
      return 5;
    } else if (selector === candidateLanguage) {
      return 10;
    } else {
      return 0;
    }
  } else if (selector) {
    const { language, pattern, scheme, hasAccessToAllModels, notebookType } = selector;
    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 (language) {
      if (language === candidateLanguage) {
        ret = 10;
      } else if (language === "*") {
        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 = { ...pattern, base: $lc(pattern.base) };
      }
      if (normalizedPattern === candidateUri.fsPath || $Cl(normalizedPattern, candidateUri.fsPath)) {
        ret = 10;
      } else {
        return 0;
      }
    }
    return ret;
  } else {
    return 0;
  }
}
function $rE(selector) {
  if (typeof selector === "string") {
    return false;
  } else if (Array.isArray(selector)) {
    return selector.some($rE);
  } else {
    return !!selector.notebookType;
  }
}

// out-build/vs/editor/common/languages/languageConfiguration.js
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 = {}));

// out-build/vs/platform/workspace/common/editSessions.js
var $2M = $Qk("editSessionIdentityService");
var EditSessionIdentityMatch;
(function(EditSessionIdentityMatch2) {
  EditSessionIdentityMatch2[EditSessionIdentityMatch2["Complete"] = 100] = "Complete";
  EditSessionIdentityMatch2[EditSessionIdentityMatch2["Partial"] = 50] = "Partial";
  EditSessionIdentityMatch2[EditSessionIdentityMatch2["None"] = 0] = "None";
})(EditSessionIdentityMatch || (EditSessionIdentityMatch = {}));

// out-build/vs/workbench/api/common/extHostAiRelatedInformation.js
var $Kwc = class {
  constructor(mainContext) {
    this.a = /* @__PURE__ */ new Map();
    this.b = 0;
    this.c = mainContext.getProxy($xT.MainThreadAiRelatedInformation);
  }
  async $provideAiRelatedInformation(handle, query, token) {
    if (this.a.size === 0) {
      throw new Error("No related information providers registered");
    }
    const provider = this.a.get(handle);
    if (!provider) {
      throw new Error("related information provider not found");
    }
    const result = await provider.provideRelatedInformation(query, token) ?? [];
    return result;
  }
  getRelatedInformation(extension, query, types) {
    return this.c.$getAiRelatedInformation(query, types);
  }
  registerRelatedInformationProvider(extension, type, provider) {
    const handle = this.b;
    this.b++;
    this.a.set(handle, provider);
    this.c.$registerAiRelatedInformationProvider(handle, type);
    return new $zT(() => {
      this.c.$unregisterAiRelatedInformationProvider(handle);
      this.a.delete(handle);
    });
  }
};

// out-build/vs/editor/common/services/semanticTokensDto.js
var EncodedSemanticTokensType;
(function(EncodedSemanticTokensType2) {
  EncodedSemanticTokensType2[EncodedSemanticTokensType2["Full"] = 1] = "Full";
  EncodedSemanticTokensType2[EncodedSemanticTokensType2["Delta"] = 2] = "Delta";
})(EncodedSemanticTokensType || (EncodedSemanticTokensType = {}));
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 (!$G()) {
    reverseEndianness(uint8Arr);
  }
  return $Ci.wrap(uint8Arr);
}
function fromLittleEndianBuffer(buff) {
  const uint8Arr = buff.buffer;
  if (!$G()) {
    reverseEndianness(uint8Arr);
  }
  if (uint8Arr.byteOffset % 4 === 0) {
    return new Uint32Array(uint8Arr.buffer, uint8Arr.byteOffset, uint8Arr.length / 4);
  } else {
    const data = new Uint8Array(uint8Arr.byteLength);
    data.set(uint8Arr);
    return new Uint32Array(data.buffer, data.byteOffset, data.length / 4);
  }
}
function $$jb(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 delta2 of semanticTokens.deltas) {
      dest[offset++] = delta2.start;
      dest[offset++] = delta2.deleteCount;
      if (delta2.data) {
        dest[offset++] = delta2.data.length;
        dest.set(delta2.data, offset);
        offset += delta2.data.length;
      } else {
        dest[offset++] = 0;
      }
    }
  }
  return toLittleEndianBuffer(dest);
}
function encodeSemanticTokensDtoSize(semanticTokens) {
  let result = 0;
  result += 1 + 1;
  if (semanticTokens.type === "full") {
    result += 1 + semanticTokens.data.length;
  } else {
    result += 1;
    result += (1 + 1 + 1) * semanticTokens.deltas.length;
    for (const delta2 of semanticTokens.deltas) {
      if (delta2.data) {
        result += delta2.data.length;
      }
    }
  }
  return result;
}
function $_jb(_buff) {
  const src = fromLittleEndianBuffer(_buff);
  let offset = 0;
  const id2 = src[offset++];
  const type = src[offset++];
  if (type === 1) {
    const length = src[offset++];
    const data = src.subarray(offset, offset + length);
    offset += length;
    return {
      id: id2,
      type: "full",
      data
    };
  }
  const deltaCount = src[offset++];
  const deltas = [];
  for (let i = 0; i < deltaCount; i++) {
    const start = src[offset++];
    const deleteCount = src[offset++];
    const length = src[offset++];
    let data;
    if (length > 0) {
      data = src.subarray(offset, offset + length);
      offset += length;
    }
    deltas[i] = { start, deleteCount, data };
  }
  return {
    id: id2,
    type: "delta",
    deltas
  };
}

// out-build/vs/workbench/api/common/extHostApiCommands.js
var newCommands = [
  // -- document highlights
  new $GW("vscode.executeDocumentHighlights", "_executeDocumentHighlights", "Execute document highlight provider.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of DocumentHighlight-instances.", tryMapWith(DocumentHighlight.to))),
  // -- document symbols
  new $GW("vscode.executeDocumentSymbolProvider", "_executeDocumentSymbolProvider", "Execute document symbol provider.", [$EW.Uri], new $FW("A promise that resolves to an array of SymbolInformation and DocumentSymbol instances.", (value, apiArgs) => {
    if ($Pb(value)) {
      return void 0;
    }
    class MergedInfo extends $UT {
      static to(symbol) {
        const res = new MergedInfo(symbol.name, SymbolKind3.to(symbol.kind), symbol.containerName || "", new $NT(apiArgs[0], Range.to(symbol.range)));
        res.detail = symbol.detail;
        res.range = res.location.range;
        res.selectionRange = Range.to(symbol.selectionRange);
        res.children = symbol.children ? symbol.children.map(MergedInfo.to) : [];
        return res;
      }
    }
    return value.map(MergedInfo.to);
  })),
  // -- formatting
  new $GW("vscode.executeFormatDocumentProvider", "_executeFormatDocumentProvider", "Execute document format provider.", [$EW.Uri, new $EW("options", "Formatting options", (_) => true, (v) => v)], new $FW("A promise that resolves to an array of TextEdits.", tryMapWith(TextEdit.to))),
  new $GW("vscode.executeFormatRangeProvider", "_executeFormatRangeProvider", "Execute range format provider.", [$EW.Uri, $EW.Range, new $EW("options", "Formatting options", (_) => true, (v) => v)], new $FW("A promise that resolves to an array of TextEdits.", tryMapWith(TextEdit.to))),
  new $GW("vscode.executeFormatOnTypeProvider", "_executeFormatOnTypeProvider", "Execute format on type provider.", [$EW.Uri, $EW.Position, new $EW("ch", "Trigger character", (v) => typeof v === "string", (v) => v), new $EW("options", "Formatting options", (_) => true, (v) => v)], new $FW("A promise that resolves to an array of TextEdits.", tryMapWith(TextEdit.to))),
  // -- go to symbol (definition, type definition, declaration, impl, references)
  new $GW("vscode.executeDefinitionProvider", "_executeDefinitionProvider", "Execute all definition providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location or LocationLink instances.", mapLocationOrLocationLink)),
  new $GW("vscode.experimental.executeDefinitionProvider_recursive", "_executeDefinitionProvider_recursive", "Execute all definition providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location or LocationLink instances.", mapLocationOrLocationLink)),
  new $GW("vscode.executeTypeDefinitionProvider", "_executeTypeDefinitionProvider", "Execute all type definition providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location or LocationLink instances.", mapLocationOrLocationLink)),
  new $GW("vscode.experimental.executeTypeDefinitionProvider_recursive", "_executeTypeDefinitionProvider_recursive", "Execute all type definition providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location or LocationLink instances.", mapLocationOrLocationLink)),
  new $GW("vscode.executeDeclarationProvider", "_executeDeclarationProvider", "Execute all declaration providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location or LocationLink instances.", mapLocationOrLocationLink)),
  new $GW("vscode.experimental.executeDeclarationProvider_recursive", "_executeDeclarationProvider_recursive", "Execute all declaration providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location or LocationLink instances.", mapLocationOrLocationLink)),
  new $GW("vscode.executeImplementationProvider", "_executeImplementationProvider", "Execute all implementation providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location or LocationLink instances.", mapLocationOrLocationLink)),
  new $GW("vscode.experimental.executeImplementationProvider_recursive", "_executeImplementationProvider_recursive", "Execute all implementation providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location or LocationLink instances.", mapLocationOrLocationLink)),
  new $GW("vscode.executeReferenceProvider", "_executeReferenceProvider", "Execute all reference providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location-instances.", tryMapWith(location.to))),
  new $GW("vscode.experimental.executeReferenceProvider", "_executeReferenceProvider_recursive", "Execute all reference providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Location-instances.", tryMapWith(location.to))),
  // -- hover
  new $GW("vscode.executeHoverProvider", "_executeHoverProvider", "Execute all hover providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Hover-instances.", tryMapWith(Hover.to))),
  new $GW("vscode.experimental.executeHoverProvider_recursive", "_executeHoverProvider_recursive", "Execute all hover providers.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of Hover-instances.", tryMapWith(Hover.to))),
  // -- selection range
  new $GW("vscode.executeSelectionRangeProvider", "_executeSelectionRangeProvider", "Execute selection range provider.", [$EW.Uri, new $EW("position", "A position in a text document", (v) => Array.isArray(v) && v.every((v2) => $AT.isPosition(v2)), (v) => v.map(Position.from))], new $FW("A promise that resolves to an array of ranges.", (result) => {
    return result.map((ranges) => {
      let node;
      for (const range of ranges.reverse()) {
        node = new $YT(Range.to(range), node);
      }
      return node;
    });
  })),
  // -- symbol search
  new $GW("vscode.executeWorkspaceSymbolProvider", "_executeWorkspaceSymbolProvider", "Execute all workspace symbol providers.", [$EW.String.with("query", "Search string")], new $FW("A promise that resolves to an array of SymbolInformation-instances.", (value) => {
    return value.map(WorkspaceSymbol.to);
  })),
  // --- call hierarchy
  new $GW("vscode.prepareCallHierarchy", "_executePrepareCallHierarchy", "Prepare call hierarchy at a position inside a document", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of CallHierarchyItem-instances", (v) => v.map(CallHierarchyItem.to))),
  new $GW("vscode.provideIncomingCalls", "_executeProvideIncomingCalls", "Compute incoming calls for an item", [$EW.CallHierarchyItem], new $FW("A promise that resolves to an array of CallHierarchyIncomingCall-instances", (v) => v.map(CallHierarchyIncomingCall.to))),
  new $GW("vscode.provideOutgoingCalls", "_executeProvideOutgoingCalls", "Compute outgoing calls for an item", [$EW.CallHierarchyItem], new $FW("A promise that resolves to an array of CallHierarchyOutgoingCall-instances", (v) => v.map(CallHierarchyOutgoingCall.to))),
  // --- rename
  new $GW("vscode.prepareRename", "_executePrepareRename", "Execute the prepareRename of rename provider.", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to a range and placeholder text.", (value) => {
    if (!value) {
      return void 0;
    }
    return {
      range: Range.to(value.range),
      placeholder: value.text
    };
  })),
  new $GW("vscode.executeDocumentRenameProvider", "_executeDocumentRenameProvider", "Execute rename provider.", [$EW.Uri, $EW.Position, $EW.String.with("newName", "The new symbol name")], new $FW("A promise that resolves to a WorkspaceEdit.", (value) => {
    if (!value) {
      return void 0;
    }
    if (value.rejectReason) {
      throw new Error(value.rejectReason);
    }
    return WorkspaceEdit.to(value);
  })),
  // --- links
  new $GW("vscode.executeLinkProvider", "_executeLinkProvider", "Execute document link provider.", [$EW.Uri, $EW.Number.with("linkResolveCount", "Number of links that should be resolved, only when links are unresolved.").optional()], new $FW("A promise that resolves to an array of DocumentLink-instances.", (value) => value.map(DocumentLink.to))),
  // --- semantic tokens
  new $GW("vscode.provideDocumentSemanticTokensLegend", "_provideDocumentSemanticTokensLegend", "Provide semantic tokens legend for a document", [$EW.Uri], new $FW("A promise that resolves to SemanticTokensLegend.", (value) => {
    if (!value) {
      return void 0;
    }
    return new $WU(value.tokenTypes, value.tokenModifiers);
  })),
  new $GW("vscode.provideDocumentSemanticTokens", "_provideDocumentSemanticTokens", "Provide semantic tokens for a document", [$EW.Uri], new $FW("A promise that resolves to SemanticTokens.", (value) => {
    if (!value) {
      return void 0;
    }
    const semanticTokensDto = $_jb(value);
    if (semanticTokensDto.type !== "full") {
      return void 0;
    }
    return new $YU(semanticTokensDto.data, void 0);
  })),
  new $GW("vscode.provideDocumentRangeSemanticTokensLegend", "_provideDocumentRangeSemanticTokensLegend", "Provide semantic tokens legend for a document range", [$EW.Uri, $EW.Range.optional()], new $FW("A promise that resolves to SemanticTokensLegend.", (value) => {
    if (!value) {
      return void 0;
    }
    return new $WU(value.tokenTypes, value.tokenModifiers);
  })),
  new $GW("vscode.provideDocumentRangeSemanticTokens", "_provideDocumentRangeSemanticTokens", "Provide semantic tokens for a document range", [$EW.Uri, $EW.Range], new $FW("A promise that resolves to SemanticTokens.", (value) => {
    if (!value) {
      return void 0;
    }
    const semanticTokensDto = $_jb(value);
    if (semanticTokensDto.type !== "full") {
      return void 0;
    }
    return new $YU(semanticTokensDto.data, void 0);
  })),
  // --- completions
  new $GW("vscode.executeCompletionItemProvider", "_executeCompletionItemProvider", "Execute completion item provider.", [
    $EW.Uri,
    $EW.Position,
    $EW.String.with("triggerCharacter", "Trigger completion when the user types the character, like `,` or `(`").optional(),
    $EW.Number.with("itemResolveCount", "Number of completions to resolve (too large numbers slow down completions)").optional()
  ], new $FW("A promise that resolves to a CompletionList-instance.", (value, _args, converter) => {
    if (!value) {
      return new $$T([]);
    }
    const items = value.suggestions.map((suggestion) => CompletionItem.to(suggestion, converter));
    return new $$T(items, value.incomplete);
  })),
  // --- signature help
  new $GW("vscode.executeSignatureHelpProvider", "_executeSignatureHelpProvider", "Execute signature help provider.", [$EW.Uri, $EW.Position, $EW.String.with("triggerCharacter", "Trigger signature help when the user types the character, like `,` or `(`").optional()], new $FW("A promise that resolves to SignatureHelp.", (value) => {
    if (value) {
      return SignatureHelp.to(value);
    }
    return void 0;
  })),
  // --- code lens
  new $GW("vscode.executeCodeLensProvider", "_executeCodeLensProvider", "Execute code lens provider.", [$EW.Uri, $EW.Number.with("itemResolveCount", "Number of lenses that should be resolved and returned. Will only return resolved lenses, will impact performance)").optional()], new $FW("A promise that resolves to an array of CodeLens-instances.", (value, _args, converter) => {
    return tryMapWith((item) => {
      return new $3T(Range.to(item.range), item.command && converter.fromInternal(item.command));
    })(value);
  })),
  // --- code actions
  new $GW("vscode.executeCodeActionProvider", "_executeCodeActionProvider", "Execute code action provider.", [
    $EW.Uri,
    new $EW("rangeOrSelection", "Range in a text document. Some refactoring provider requires Selection object.", (v) => $BT.isRange(v), (v) => $CT.isSelection(v) ? Selection.from(v) : Range.from(v)),
    $EW.String.with("kind", "Code action kind to return code actions for").optional(),
    $EW.Number.with("itemResolveCount", "Number of code actions to resolve (too large numbers slow down code actions)").optional()
  ], new $FW("A promise that resolves to an array of Command-instances.", (value, _args, converter) => {
    return tryMapWith((codeAction) => {
      if (codeAction._isSynthetic) {
        if (!codeAction.command) {
          throw new Error("Synthetic code actions must have a command");
        }
        return converter.fromInternal(codeAction.command);
      } else {
        const ret = new $WT(codeAction.title, codeAction.kind ? new $XT(codeAction.kind) : void 0);
        if (codeAction.edit) {
          ret.edit = WorkspaceEdit.to(codeAction.edit);
        }
        if (codeAction.command) {
          ret.command = converter.fromInternal(codeAction.command);
        }
        ret.isPreferred = codeAction.isPreferred;
        return ret;
      }
    })(value);
  })),
  // --- colors
  new $GW("vscode.executeDocumentColorProvider", "_executeDocumentColorProvider", "Execute document color provider.", [$EW.Uri], new $FW("A promise that resolves to an array of ColorInformation objects.", (result) => {
    if (result) {
      return result.map((ci) => new $eU(Range.to(ci.range), Color.to(ci.color)));
    }
    return [];
  })),
  new $GW("vscode.executeColorPresentationProvider", "_executeColorPresentationProvider", "Execute color presentation provider.", [
    new $EW("color", "The color to show and insert", (v) => v instanceof $dU, Color.from),
    new $EW("context", "Context object with uri and range", (_v) => true, (v) => ({ uri: v.uri, range: Range.from(v.range) }))
  ], new $FW("A promise that resolves to an array of ColorPresentation objects.", (result) => {
    if (result) {
      return result.map(ColorPresentation.to);
    }
    return [];
  })),
  // --- inline hints
  new $GW("vscode.executeInlayHintProvider", "_executeInlayHintProvider", "Execute inlay hints provider", [$EW.Uri, $EW.Range], new $FW("A promise that resolves to an array of Inlay objects", (result, args2, converter) => {
    return result.map(InlayHint.to.bind(void 0, converter));
  })),
  // --- folding
  new $GW("vscode.executeFoldingRangeProvider", "_executeFoldingRangeProvider", "Execute folding range provider", [$EW.Uri], new $FW("A promise that resolves to an array of FoldingRange objects", (result, args2) => {
    if (result) {
      return result.map(FoldingRange.to);
    }
    return void 0;
  })),
  // --- notebooks
  new $GW("vscode.resolveNotebookContentProviders", "_resolveNotebookContentProvider", "Resolve Notebook Content Providers", [
    // new ApiCommandArgument<string, string>('viewType', '', v => typeof v === 'string', v => v),
    // new ApiCommandArgument<string, string>('displayName', '', v => typeof v === 'string', v => v),
    // new ApiCommandArgument<object, object>('options', '', v => typeof v === 'object', v => v),
  ], new $FW("A promise that resolves to an array of NotebookContentProvider static info objects.", tryMapWith((item) => {
    return {
      viewType: item.viewType,
      displayName: item.displayName,
      options: {
        transientOutputs: item.options.transientOutputs,
        transientCellMetadata: item.options.transientCellMetadata,
        transientDocumentMetadata: item.options.transientDocumentMetadata
      },
      filenamePattern: item.filenamePattern.map((pattern) => NotebookExclusiveDocumentPattern.to(pattern))
    };
  }))),
  // --- debug support
  new $GW("vscode.executeInlineValueProvider", "_executeInlineValueProvider", "Execute inline value provider", [
    $EW.Uri,
    $EW.Range,
    new $EW("context", "An InlineValueContext", (v) => v && typeof v.frameId === "number" && v.stoppedLocation instanceof $BT, (v) => InlineValueContext.from(v))
  ], new $FW("A promise that resolves to an array of InlineValue objects", (result) => {
    return result.map(InlineValue.to);
  })),
  // --- open'ish commands
  new $GW("vscode.open", "_workbench.open", "Opens the provided resource in the editor. Can be a text or binary file, or an http(s) URL. If you need more control over the options for opening a text file, use vscode.window.showTextDocument instead.", [
    new $EW("uriOrString", "Uri-instance or string (only http/https)", (v) => URI.isUri(v) || typeof v === "string" && $$g(v, Schemas.http, Schemas.https), (v) => v),
    new $EW("columnOrOptions", "Either the column in which to open or editor options, see vscode.TextDocumentShowOptions", (v) => v === void 0 || typeof v === "number" || typeof v === "object", (v) => !v ? v : typeof v === "number" ? [ViewColumn2.from(v), void 0] : [ViewColumn2.from(v.viewColumn), TextEditorOpenOptions.from(v)]).optional(),
    $EW.String.with("label", "").optional()
  ], $FW.Void),
  new $GW("vscode.openWith", "_workbench.openWith", "Opens the provided resource with a specific editor.", [
    $EW.Uri.with("resource", "Resource to open"),
    $EW.String.with("viewId", "Custom editor view id. This should be the viewType string for custom editors or the notebookType string for notebooks. Use 'default' to use VS Code's default text editor"),
    new $EW("columnOrOptions", "Either the column in which to open or editor options, see vscode.TextDocumentShowOptions", (v) => v === void 0 || typeof v === "number" || typeof v === "object", (v) => !v ? v : typeof v === "number" ? [ViewColumn2.from(v), void 0] : [ViewColumn2.from(v.viewColumn), TextEditorOpenOptions.from(v)]).optional()
  ], $FW.Void),
  new $GW("vscode.diff", "_workbench.diff", "Opens the provided resources in the diff editor to compare their contents.", [
    $EW.Uri.with("left", "Left-hand side resource of the diff editor"),
    $EW.Uri.with("right", "Right-hand side resource of the diff editor"),
    $EW.String.with("title", "Human readable title for the diff editor").optional(),
    new $EW("columnOrOptions", "Either the column in which to open or editor options, see vscode.TextDocumentShowOptions", (v) => v === void 0 || typeof v === "object", (v) => v && [ViewColumn2.from(v.viewColumn), TextEditorOpenOptions.from(v)]).optional()
  ], $FW.Void),
  new $GW("vscode.changes", "_workbench.changes", "Opens a list of resources in the changes editor to compare their contents.", [
    $EW.String.with("title", "Human readable title for the changes editor"),
    new $EW("resourceList", "List of resources to compare", (resources) => {
      for (const resource of resources) {
        if (resource.length !== 3) {
          return false;
        }
        const [label, left, right] = resource;
        if (!URI.isUri(label) || !URI.isUri(left) && left !== void 0 && left !== null || !URI.isUri(right) && right !== void 0 && right !== null) {
          return false;
        }
      }
      return true;
    }, (v) => v)
  ], $FW.Void),
  // --- type hierarchy
  new $GW("vscode.prepareTypeHierarchy", "_executePrepareTypeHierarchy", "Prepare type hierarchy at a position inside a document", [$EW.Uri, $EW.Position], new $FW("A promise that resolves to an array of TypeHierarchyItem-instances", (v) => v.map(TypeHierarchyItem.to))),
  new $GW("vscode.provideSupertypes", "_executeProvideSupertypes", "Compute supertypes for an item", [$EW.TypeHierarchyItem], new $FW("A promise that resolves to an array of TypeHierarchyItem-instances", (v) => v.map(TypeHierarchyItem.to))),
  new $GW("vscode.provideSubtypes", "_executeProvideSubtypes", "Compute subtypes for an item", [$EW.TypeHierarchyItem], new $FW("A promise that resolves to an array of TypeHierarchyItem-instances", (v) => v.map(TypeHierarchyItem.to))),
  // --- testing
  new $GW("vscode.revealTestInExplorer", "_revealTestInExplorer", "Reveals a test instance in the explorer", [$EW.TestItem], $FW.Void),
  new $GW("vscode.startContinuousTestRun", "testing.startContinuousRunFromExtension", "Starts running the given tests with continuous run mode.", [$EW.TestProfile, $EW.Arr($EW.TestItem)], $FW.Void),
  new $GW("vscode.stopContinuousTestRun", "testing.stopContinuousRunFromExtension", "Stops running the given tests with continuous run mode.", [$EW.Arr($EW.TestItem)], $FW.Void),
  // --- continue edit session
  new $GW("vscode.experimental.editSession.continue", "_workbench.editSessions.actions.continueEditSession", "Continue the current edit session in a different workspace", [$EW.Uri.with("workspaceUri", "The target workspace to continue the current edit session in")], $FW.Void),
  // --- context keys
  new $GW("setContext", "_setContext", "Set a custom context key value that can be used in when clauses.", [
    $EW.String.with("name", "The context key name"),
    new $EW("value", "The context key value", () => true, (v) => v)
  ], $FW.Void),
  // --- mapped edits
  new $GW("vscode.executeMappedEditsProvider", "_executeMappedEditsProvider", "Execute Mapped Edits Provider", [
    $EW.Uri,
    $EW.StringArray,
    new $EW("MappedEditsContext", "Mapped Edits Context", (v) => MappedEditsContext.is(v), (v) => MappedEditsContext.from(v))
  ], new $FW("A promise that resolves to a workspace edit or null", (value) => {
    return value ? WorkspaceEdit.to(value) : null;
  })),
  // --- inline chat
  new $GW("vscode.editorChat.start", "inlineChat.start", "Invoke a new editor chat session", [new $EW("Run arguments", "", (_v) => true, (v) => {
    if (!v) {
      return void 0;
    }
    return {
      initialRange: v.initialRange ? Range.from(v.initialRange) : void 0,
      initialSelection: $CT.isSelection(v.initialSelection) ? Selection.from(v.initialSelection) : void 0,
      message: v.message,
      autoSend: v.autoSend,
      position: v.position ? Position.from(v.position) : void 0
    };
  })], $FW.Void)
];
var $Uwc = class {
  static register(commands) {
    newCommands.forEach(commands.registerApiCommand, commands);
    this.a(commands);
  }
  static a(commands) {
    commands.registerCommand(false, "_validateWhenClauses", $8m);
  }
};
function tryMapWith(f) {
  return (value) => {
    if (Array.isArray(value)) {
      return value.map(f);
    }
    return void 0;
  };
}
function mapLocationOrLocationLink(values) {
  if (!Array.isArray(values)) {
    return void 0;
  }
  const result = [];
  for (const item of values) {
    if ($RE(item)) {
      result.push(DefinitionLink.to(item));
    } else {
      result.push(location.to(item));
    }
  }
  return result;
}

// out-build/vs/workbench/api/common/extHostBulkEdits.js
var $Xwc = class $Xwc2 {
  constructor(extHostRpc, extHostDocumentsAndEditors) {
    this.a = extHostRpc.getProxy($xT.MainThreadBulkEdits);
    this.b = {
      getTextDocumentVersion: (uri) => extHostDocumentsAndEditors.getDocument(uri)?.version,
      getNotebookDocumentVersion: () => void 0
    };
  }
  applyWorkspaceEdit(edit2, extension, metadata) {
    const dto = new $ES(WorkspaceEdit.from(edit2, this.b));
    return this.a.$tryApplyWorkspaceEdit(dto, void 0, metadata?.isRefactoring ?? false);
  }
};
$Xwc = __decorate([
  __param(0, $gW)
], $Xwc);

// out-build/vs/workbench/contrib/chat/common/chatService.js
var ChatResponseReferencePartStatusKind2;
(function(ChatResponseReferencePartStatusKind3) {
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Complete"] = 1] = "Complete";
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Partial"] = 2] = "Partial";
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Omitted"] = 3] = "Omitted";
})(ChatResponseReferencePartStatusKind2 || (ChatResponseReferencePartStatusKind2 = {}));
var ChatAgentVoteDirection;
(function(ChatAgentVoteDirection2) {
  ChatAgentVoteDirection2[ChatAgentVoteDirection2["Down"] = 0] = "Down";
  ChatAgentVoteDirection2[ChatAgentVoteDirection2["Up"] = 1] = "Up";
})(ChatAgentVoteDirection || (ChatAgentVoteDirection = {}));
var ChatAgentVoteDownReason;
(function(ChatAgentVoteDownReason2) {
  ChatAgentVoteDownReason2["IncorrectCode"] = "incorrectCode";
  ChatAgentVoteDownReason2["DidNotFollowInstructions"] = "didNotFollowInstructions";
  ChatAgentVoteDownReason2["IncompleteCode"] = "incompleteCode";
  ChatAgentVoteDownReason2["MissingContext"] = "missingContext";
  ChatAgentVoteDownReason2["PoorlyWrittenOrFormatted"] = "poorlyWrittenOrFormatted";
  ChatAgentVoteDownReason2["RefusedAValidRequest"] = "refusedAValidRequest";
  ChatAgentVoteDownReason2["OffensiveOrUnsafe"] = "offensiveOrUnsafe";
  ChatAgentVoteDownReason2["Other"] = "other";
  ChatAgentVoteDownReason2["WillReportIssue"] = "willReportIssue";
})(ChatAgentVoteDownReason || (ChatAgentVoteDownReason = {}));
var ChatCopyKind2;
(function(ChatCopyKind3) {
  ChatCopyKind3[ChatCopyKind3["Action"] = 1] = "Action";
  ChatCopyKind3[ChatCopyKind3["Toolbar"] = 2] = "Toolbar";
})(ChatCopyKind2 || (ChatCopyKind2 = {}));
var $qO = $Qk("IChatService");

// out-build/vs/workbench/contrib/chat/common/chatActions.js
function $lzb(obj) {
  return !!obj && typeof obj.sessionId === "string" && obj.$mid === 19;
}

// out-build/vs/workbench/api/common/extHostChatAgents2.js
var ChatAgentResponseStream = class {
  constructor(j, k, l, m, n) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.b = $te.create(false);
    this.c = false;
  }
  close() {
    this.c = true;
  }
  get timings() {
    return {
      firstProgress: this.d,
      totalElapsed: this.b.elapsed()
    };
  }
  get apiObject() {
    if (!this.g) {
      let throwIfDone2 = function(source) {
        if (that.c) {
          const err = new Error("Response stream has been closed");
          Error.captureStackTrace(err, source);
          throw err;
        }
      };
      var throwIfDone = throwIfDone2;
      const that = this;
      this.b.reset();
      const _report = (progress, task) => {
        if (typeof this.d === "undefined" && (progress.kind === "markdownContent" || progress.kind === "markdownVuln")) {
          this.d = this.b.elapsed();
        }
        if (task) {
          const progressReporterPromise = this.l.$handleProgressChunk(this.k.requestId, progress);
          const progressReporter = {
            report: (p) => {
              progressReporterPromise?.then((handle) => {
                if (handle) {
                  if ($4T.isMarkdownString(p.value)) {
                    this.l.$handleProgressChunk(this.k.requestId, ChatResponseWarningPart.from(p), handle);
                  } else {
                    this.l.$handleProgressChunk(this.k.requestId, ChatResponseReferencePart.from(p), handle);
                  }
                }
              });
            }
          };
          Promise.all([progressReporterPromise, task?.(progressReporter)]).then(([handle, res]) => {
            if (handle !== void 0) {
              this.l.$handleProgressChunk(this.k.requestId, ChatTaskResult.from(res), handle);
            }
          });
        } else {
          this.l.$handleProgressChunk(this.k.requestId, progress);
        }
      };
      this.g = Object.freeze({
        markdown(value) {
          throwIfDone2(this.markdown);
          const part = new $DV(value);
          const dto = ChatResponseMarkdownPart.from(part);
          _report(dto);
          return this;
        },
        markdownWithVulnerabilities(value, vulnerabilities) {
          throwIfDone2(this.markdown);
          if (vulnerabilities) {
            $AN(that.j, "chatParticipantAdditions");
          }
          const part = new $EV(value, vulnerabilities);
          const dto = ChatResponseMarkdownWithVulnerabilitiesPart.from(part);
          _report(dto);
          return this;
        },
        codeblockUri(value) {
          throwIfDone2(this.codeblockUri);
          $AN(that.j, "chatParticipantAdditions");
          const part = new $OV(value);
          const dto = ChatResponseCodeblockUriPart.from(part);
          _report(dto);
          return this;
        },
        filetree(value, baseUri) {
          throwIfDone2(this.filetree);
          const part = new $HV(value, baseUri);
          const dto = ChatResponseFilesPart.from(part);
          _report(dto);
          return this;
        },
        anchor(value, title) {
          const part = new $IV(value, title);
          return this.push(part);
        },
        button(value) {
          throwIfDone2(this.anchor);
          const part = new $MV(value);
          const dto = ChatResponseCommandButtonPart.from(part, that.m, that.n);
          _report(dto);
          return this;
        },
        progress(value, task) {
          throwIfDone2(this.progress);
          const part = new $KV(value, task);
          const dto = task ? ChatTask.from(part) : ChatResponseProgressPart.from(part);
          _report(dto, task);
          return this;
        },
        warning(value) {
          throwIfDone2(this.progress);
          $AN(that.j, "chatParticipantAdditions");
          const part = new $LV(value);
          const dto = ChatResponseWarningPart.from(part);
          _report(dto);
          return this;
        },
        reference(value, iconPath) {
          return this.reference2(value, iconPath);
        },
        reference2(value, iconPath, options2) {
          throwIfDone2(this.reference);
          if (typeof value === "object" && "variableName" in value) {
            $AN(that.j, "chatParticipantAdditions");
          }
          if (typeof value === "object" && "variableName" in value && !value.value) {
            const matchingVarData = that.k.variables.variables.find((v) => v.name === value.variableName);
            if (matchingVarData) {
              let references;
              if (matchingVarData.references?.length) {
                references = matchingVarData.references.map((r) => ({
                  kind: "reference",
                  reference: { variableName: value.variableName, value: r.reference }
                }));
              } else {
                const part = new $NV(value, iconPath, options2);
                const dto = ChatResponseReferencePart.from(part);
                references = [dto];
              }
              references.forEach((r) => _report(r));
              return this;
            } else {
            }
          } else {
            const part = new $NV(value, iconPath, options2);
            const dto = ChatResponseReferencePart.from(part);
            _report(dto);
          }
          return this;
        },
        codeCitation(value, license, snippet) {
          throwIfDone2(this.codeCitation);
          $AN(that.j, "chatParticipantAdditions");
          const part = new $PV(value, license, snippet);
          const dto = ChatResponseCodeCitationPart.from(part);
          _report(dto);
        },
        textEdit(target, edits) {
          throwIfDone2(this.textEdit);
          $AN(that.j, "chatParticipantAdditions");
          const part = new $RV(target, Array.isArray(edits) ? edits : []);
          part.isDone = edits === true ? true : void 0;
          const dto = ChatResponseTextEditPart.from(part);
          _report(dto);
          return this;
        },
        detectedParticipant(participant, command) {
          throwIfDone2(this.detectedParticipant);
          $AN(that.j, "chatParticipantAdditions");
          const part = new $FV(participant, command);
          const dto = ChatResponseDetectedParticipantPart.from(part);
          _report(dto);
          return this;
        },
        confirmation(title, message, data, buttons) {
          throwIfDone2(this.confirmation);
          $AN(that.j, "chatParticipantAdditions");
          const part = new $GV(title, message, data, buttons);
          const dto = ChatResponseConfirmationPart.from(part);
          _report(dto);
          return this;
        },
        push(part) {
          throwIfDone2(this.push);
          if (part instanceof $RV || part instanceof $EV || part instanceof $FV || part instanceof $LV || part instanceof $GV || part instanceof $PV || part instanceof $QV || part instanceof $KV) {
            $AN(that.j, "chatParticipantAdditions");
          }
          if (part instanceof $NV) {
            this.reference2(part.value, part.iconPath, part.options);
          } else if (part instanceof $KV) {
            const dto = part.task ? ChatTask.from(part) : ChatResponseProgressPart.from(part);
            _report(dto, part.task);
          } else if (part instanceof $IV) {
            const dto = ChatResponseAnchorPart.from(part);
            if (part.resolve) {
              $AN(that.j, "chatParticipantAdditions");
              dto.resolveId = $ps();
              const cts = new $ad();
              part.resolve(cts.token).then(() => {
                const resolvedDto = ChatResponseAnchorPart.from(part);
                that.l.$handleAnchorResolve(that.k.requestId, dto.resolveId, resolvedDto);
              }).then(() => cts.dispose(), () => cts.dispose());
              that.n.add($1c(() => cts.dispose(true)));
            }
            _report(dto);
          } else {
            const dto = ChatResponsePart.from(part, that.m, that.n);
            _report(dto);
          }
          return this;
        }
      });
    }
    return this.g;
  }
};
var $1wc = class _$1wc extends $3c {
  static {
    this.b = 0;
  }
  static {
    this.j = 0;
  }
  static {
    this.n = 0;
  }
  constructor(mainContext, w, y, z, C) {
    super();
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.c = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    this.s = /* @__PURE__ */ new Map();
    this.t = this.B(new $_c());
    this.u = this.B(new $_c());
    this.g = mainContext.getProxy($xT.MainThreadChatAgents2);
    y.registerArgumentProcessor({
      processArgument: (arg) => {
        if ($lzb(arg)) {
          return null;
        }
        return arg;
      }
    });
  }
  transferActiveChat(newWorkspace) {
    this.g.$transferActiveChatSession(newWorkspace);
  }
  createChatAgent(extension, id2, handler) {
    const handle = _$1wc.b++;
    const agent = new ExtHostChatAgent(extension, id2, this.g, handle, handler);
    this.c.set(handle, agent);
    this.g.$registerAgent(handle, extension.identifier, id2, {}, void 0);
    return agent.apiAgent;
  }
  createDynamicChatAgent(extension, id2, dynamicProps, handler) {
    const handle = _$1wc.b++;
    const agent = new ExtHostChatAgent(extension, id2, this.g, handle, handler);
    this.c.set(handle, agent);
    this.g.$registerAgent(handle, extension.identifier, id2, { isSticky: true }, dynamicProps);
    return agent.apiAgent;
  }
  registerChatParticipantDetectionProvider(extension, provider) {
    const handle = _$1wc.j++;
    this.m.set(handle, new ExtHostParticipantDetector(extension, provider));
    this.g.$registerChatParticipantDetectionProvider(handle);
    return $1c(() => {
      this.m.delete(handle);
      this.g.$unregisterChatParticipantDetectionProvider(handle);
    });
  }
  registerRelatedFilesProvider(extension, provider, metadata) {
    const handle = _$1wc.n++;
    this.s.set(handle, new ExtHostRelatedFilesProvider(extension, provider));
    this.g.$registerRelatedFilesProvider(handle, metadata);
    return $1c(() => {
      this.s.delete(handle);
      this.g.$unregisterRelatedFilesProvider(handle);
    });
  }
  async $provideRelatedFiles(handle, request, token) {
    const provider = this.s.get(handle);
    if (!provider) {
      return Promise.resolve([]);
    }
    const extRequestDraft = ChatRequestDraft.to(request);
    return await provider.provider.provideRelatedFiles(extRequestDraft, token) ?? void 0;
  }
  async $detectChatParticipant(handle, requestDto, context, options2, token) {
    const { request, location: location2, history } = await this.D(requestDto, context);
    const detector = this.m.get(handle);
    if (!detector) {
      return void 0;
    }
    const model = await this.F(request, detector.extension);
    const extRequest = ChatAgentRequest.to(request, location2, model);
    return detector.provider.provideParticipantDetection(extRequest, { history }, { participants: options2.participants, location: ChatLocation2.to(options2.location) }, token);
  }
  async D(requestDto, context) {
    const request = $cu(requestDto);
    const convertedHistory = await this.G(request.agentId, context);
    let location2;
    if (request.locationData?.type === ChatAgentLocation.Editor) {
      const document2 = this.z.getDocument(request.locationData.document);
      location2 = new $UV(document2, Selection.to(request.locationData.selection), Range.to(request.locationData.wholeRange));
    } else if (request.locationData?.type === ChatAgentLocation.Notebook) {
      const cell = this.z.getDocument(request.locationData.sessionInputUri);
      location2 = new $VV(cell);
    } else if (request.locationData?.type === ChatAgentLocation.Terminal) {
    }
    return { request, location: location2, history: convertedHistory };
  }
  async F(request, extension) {
    let model;
    if (request.userSelectedModelId) {
      model = await this.C.getLanguageModelByIdentifier(extension, request.userSelectedModelId);
    }
    if (!model) {
      model = await this.C.getDefaultLanguageModel(extension);
      if (!model) {
        throw new Error("Language model unavailable");
      }
    }
    return model;
  }
  async $invokeAgent(handle, requestDto, context, token) {
    const agent = this.c.get(handle);
    if (!agent) {
      throw new Error(`[CHAT](${handle}) CANNOT invoke agent because the agent is not registered`);
    }
    let stream;
    try {
      const { request, location: location2, history } = await this.D(requestDto, context);
      let sessionDisposables = this.t.get(request.sessionId);
      if (!sessionDisposables) {
        sessionDisposables = new $2c();
        this.t.set(request.sessionId, sessionDisposables);
      }
      stream = new ChatAgentResponseStream(agent.extension, request, this.g, this.y.converter, sessionDisposables);
      const model = await this.F(request, agent.extension);
      const extRequest = ChatAgentRequest.to(request, location2, model);
      const task = agent.invoke(extRequest, { history }, stream.apiObject, token);
      return await $Ih(Promise.resolve(task).then((result) => {
        if (result?.metadata) {
          try {
            JSON.stringify(result.metadata);
          } catch (err) {
            const msg = `result.metadata MUST be JSON.stringify-able. Got error: ${err.message}`;
            this.w.error(`[${agent.extension.identifier.value}] [@${agent.id}] ${msg}`, agent.extension);
            return { errorDetails: { message: msg }, timings: stream?.timings, nextQuestion: result.nextQuestion };
          }
        }
        let errorDetails;
        if (result?.errorDetails) {
          errorDetails = {
            ...result.errorDetails,
            responseIsIncomplete: true
          };
        }
        if (errorDetails?.responseIsRedacted || errorDetails?.isQuotaExceeded) {
          $AN(agent.extension, "chatParticipantPrivate");
        }
        return { errorDetails, timings: stream?.timings, metadata: result?.metadata, nextQuestion: result?.nextQuestion };
      }), token);
    } catch (e) {
      this.w.error(e, agent.extension);
      if (e instanceof $6V && e.cause) {
        e = e.cause;
      }
      const isQuotaExceeded = e instanceof Error && e.name === "ChatQuotaExceeded";
      return { errorDetails: { message: $1m(e), responseIsIncomplete: true, isQuotaExceeded } };
    } finally {
      stream?.close();
    }
  }
  async G(agentId, context) {
    const res = [];
    for (const h of context.history) {
      const ehResult = ChatAgentResult.to(h.result);
      const result = agentId === h.request.agentId ? ehResult : { ...ehResult, metadata: void 0 };
      const varsWithoutTools = h.request.variables.variables.filter((v) => !v.isTool).map(ChatPromptReference.to);
      const toolReferences = h.request.variables.variables.filter((v) => v.isTool).map(ChatLanguageModelToolReference.to);
      const turn = new $SV(h.request.message, h.request.command, varsWithoutTools, h.request.agentId, toolReferences);
      res.push(turn);
      const parts = $Mb(h.response.map((r) => ChatResponsePart.toContent(r, this.y.converter)));
      res.push(new $TV(parts, result, h.request.agentId, h.request.command));
    }
    return res;
  }
  $releaseSession(sessionId) {
    this.t.deleteAndDispose(sessionId);
  }
  async $provideFollowups(requestDto, handle, result, context, token) {
    const agent = this.c.get(handle);
    if (!agent) {
      return Promise.resolve([]);
    }
    const request = $cu(requestDto);
    const convertedHistory = await this.G(agent.id, context);
    const ehResult = ChatAgentResult.to(result);
    return (await agent.provideFollowups(ehResult, { history: convertedHistory }, token)).filter((f) => {
      const isValid = !f.participant || Iterable.some(this.c.values(), (a) => a.id === f.participant && $5z.equals(a.extension.identifier, agent.extension.identifier));
      if (!isValid) {
        this.w.warn(`[@${agent.id}] ChatFollowup refers to an unknown participant: ${f.participant}`);
      }
      return isValid;
    }).map((f) => ChatFollowup.from(f, request));
  }
  $acceptFeedback(handle, result, voteAction) {
    const agent = this.c.get(handle);
    if (!agent) {
      return;
    }
    const ehResult = ChatAgentResult.to(result);
    let kind;
    switch (voteAction.direction) {
      case ChatAgentVoteDirection.Down:
        kind = ChatResultFeedbackKind.Unhelpful;
        break;
      case ChatAgentVoteDirection.Up:
        kind = ChatResultFeedbackKind.Helpful;
        break;
    }
    const feedback = {
      result: ehResult,
      kind,
      unhelpfulReason: $zN(agent.extension, "chatParticipantAdditions") ? voteAction.reason : void 0
    };
    agent.acceptFeedback(Object.freeze(feedback));
  }
  $acceptAction(handle, result, event) {
    const agent = this.c.get(handle);
    if (!agent) {
      return;
    }
    if (event.action.kind === "vote") {
      return;
    }
    const ehAction = ChatAgentUserActionEvent.to(result, event, this.y.converter);
    if (ehAction) {
      agent.acceptAction(Object.freeze(ehAction));
    }
  }
  async $invokeCompletionProvider(handle, query, token) {
    const agent = this.c.get(handle);
    if (!agent) {
      return [];
    }
    let disposables = this.u.get(handle);
    if (disposables) {
      disposables.clear();
    } else {
      disposables = new $2c();
      this.u.set(handle, disposables);
    }
    const items = await agent.invokeCompletionProvider(query, token);
    return items.map((i) => ChatAgentCompletionItem.from(i, this.y.converter, disposables));
  }
  async $provideWelcomeMessage(handle, token) {
    const agent = this.c.get(handle);
    if (!agent) {
      return;
    }
    return await agent.provideWelcomeMessage(token);
  }
  async $provideChatTitle(handle, context, token) {
    const agent = this.c.get(handle);
    if (!agent) {
      return;
    }
    const history = await this.G(agent.id, { history: context });
    return await agent.provideTitle({ history }, token);
  }
  async $provideSampleQuestions(handle, location2, token) {
    const agent = this.c.get(handle);
    if (!agent) {
      return;
    }
    return (await agent.provideSampleQuestions(ChatLocation2.to(location2), token)).map((f) => ChatFollowup.from(f, void 0));
  }
};
var ExtHostParticipantDetector = class {
  constructor(extension, provider) {
    this.extension = extension;
    this.provider = provider;
  }
};
var ExtHostRelatedFilesProvider = class {
  constructor(extension, provider) {
    this.extension = extension;
    this.provider = provider;
  }
};
var ExtHostChatAgent = class {
  constructor(extension, id2, w, x, y) {
    this.extension = extension;
    this.id = id2;
    this.w = w;
    this.x = x;
    this.y = y;
    this.l = new $ze();
    this.m = new $ze();
  }
  acceptFeedback(feedback) {
    this.l.fire(feedback);
  }
  acceptAction(event) {
    this.m.fire(event);
  }
  async invokeCompletionProvider(query, token) {
    if (!this.o) {
      return [];
    }
    return await this.o.provider.provideCompletionItems(query, token) ?? [];
  }
  async provideFollowups(result, context, token) {
    if (!this.b) {
      return [];
    }
    const followups = await this.b.provideFollowups(result, context, token);
    if (!followups) {
      return [];
    }
    return followups.filter((f) => !(f && "commandId" in f)).filter((f) => !(f && "message" in f));
  }
  async provideWelcomeMessage(token) {
    if (!this.q?.provideWelcomeMessage) {
      return void 0;
    }
    const content = await this.q.provideWelcomeMessage(token);
    const icon = content?.icon;
    if (!content || !ThemeIcon.isThemeIcon(icon)) {
      return void 0;
    }
    return {
      ...content,
      icon,
      message: MarkdownString.from(content.message)
    };
  }
  async provideTitle(context, token) {
    if (!this.s) {
      return;
    }
    return await this.s.provideChatTitle(context, token) ?? void 0;
  }
  async provideSampleQuestions(location2, token) {
    if (!this.q || !this.q.provideSampleQuestions) {
      return [];
    }
    const content = await this.q.provideSampleQuestions(location2, token);
    if (!content) {
      return [];
    }
    return content;
  }
  get apiAgent() {
    let disposed = false;
    let updateScheduled = false;
    const updateMetadataSoon = () => {
      if (disposed) {
        return;
      }
      if (updateScheduled) {
        return;
      }
      updateScheduled = true;
      queueMicrotask(() => {
        this.w.$updateAgent(this.x, {
          icon: !this.c ? void 0 : this.c instanceof URI ? this.c : "light" in this.c ? this.c.light : void 0,
          iconDark: !this.c ? void 0 : "dark" in this.c ? this.c.dark : void 0,
          themeIcon: this.c instanceof $AU ? this.c : void 0,
          hasFollowups: this.b !== void 0,
          isSecondary: this.k,
          helpTextPrefix: !this.d || typeof this.d === "string" ? this.d : MarkdownString.from(this.d),
          helpTextVariablesPrefix: !this.g || typeof this.g === "string" ? this.g : MarkdownString.from(this.g),
          helpTextPostfix: !this.j || typeof this.j === "string" ? this.j : MarkdownString.from(this.j),
          supportIssueReporting: this.n,
          requester: this.t,
          supportsSlowVariables: this.u
        });
        updateScheduled = false;
      });
    };
    const that = this;
    return {
      get id() {
        return that.id;
      },
      get iconPath() {
        return that.c;
      },
      set iconPath(v) {
        that.c = v;
        updateMetadataSoon();
      },
      get requestHandler() {
        return that.y;
      },
      set requestHandler(v) {
        $Jg(typeof v === "function", "Invalid request handler");
        that.y = v;
      },
      get followupProvider() {
        return that.b;
      },
      set followupProvider(v) {
        that.b = v;
        updateMetadataSoon();
      },
      get helpTextPrefix() {
        $AN(that.extension, "defaultChatParticipant");
        return that.d;
      },
      set helpTextPrefix(v) {
        $AN(that.extension, "defaultChatParticipant");
        that.d = v;
        updateMetadataSoon();
      },
      get helpTextVariablesPrefix() {
        $AN(that.extension, "defaultChatParticipant");
        return that.g;
      },
      set helpTextVariablesPrefix(v) {
        $AN(that.extension, "defaultChatParticipant");
        that.g = v;
        updateMetadataSoon();
      },
      get helpTextPostfix() {
        $AN(that.extension, "defaultChatParticipant");
        return that.j;
      },
      set helpTextPostfix(v) {
        $AN(that.extension, "defaultChatParticipant");
        that.j = v;
        updateMetadataSoon();
      },
      get isSecondary() {
        $AN(that.extension, "defaultChatParticipant");
        return that.k;
      },
      set isSecondary(v) {
        $AN(that.extension, "defaultChatParticipant");
        that.k = v;
        updateMetadataSoon();
      },
      get supportIssueReporting() {
        $AN(that.extension, "chatParticipantPrivate");
        return that.n;
      },
      set supportIssueReporting(v) {
        $AN(that.extension, "chatParticipantPrivate");
        that.n = v;
        updateMetadataSoon();
      },
      get onDidReceiveFeedback() {
        return that.l.event;
      },
      set participantVariableProvider(v) {
        $AN(that.extension, "chatParticipantAdditions");
        that.o = v;
        if (v) {
          if (!v.triggerCharacters.length) {
            throw new Error("triggerCharacters are required");
          }
          that.w.$registerAgentCompletionsProvider(that.x, that.id, v.triggerCharacters);
        } else {
          that.w.$unregisterAgentCompletionsProvider(that.x, that.id);
        }
      },
      get participantVariableProvider() {
        $AN(that.extension, "chatParticipantAdditions");
        return that.o;
      },
      set welcomeMessageProvider(v) {
        $AN(that.extension, "defaultChatParticipant");
        that.q = v;
        updateMetadataSoon();
      },
      get welcomeMessageProvider() {
        $AN(that.extension, "defaultChatParticipant");
        return that.q;
      },
      set titleProvider(v) {
        $AN(that.extension, "defaultChatParticipant");
        that.s = v;
        updateMetadataSoon();
      },
      get titleProvider() {
        $AN(that.extension, "defaultChatParticipant");
        return that.s;
      },
      onDidPerformAction: !$zN(this.extension, "chatParticipantAdditions") ? void 0 : this.m.event,
      set requester(v) {
        that.t = v;
        updateMetadataSoon();
      },
      get requester() {
        return that.t;
      },
      set supportsSlowReferences(v) {
        $AN(that.extension, "chatParticipantPrivate");
        that.u = v;
        updateMetadataSoon();
      },
      get supportsSlowReferences() {
        $AN(that.extension, "chatParticipantPrivate");
        return that.u;
      },
      dispose() {
        disposed = true;
        that.b = void 0;
        that.l.dispose();
        that.w.$unregisterAgent(that.x);
      }
    };
  }
  invoke(request, context, response, token) {
    return this.y(request, context, response, token);
  }
};

// out-build/vs/workbench/api/common/extHostChatVariables.js
var $2wc = class _$2wc {
  static {
    this.a = 0;
  }
  constructor(mainContext) {
    this.b = /* @__PURE__ */ new Map();
    this.c = mainContext.getProxy($xT.MainThreadChatVariables);
  }
  async $resolveVariable(handle, requestId, messageText, token) {
    const item = this.b.get(handle);
    if (!item) {
      return void 0;
    }
    try {
      if (item.resolver.resolve2) {
        $AN(item.extension, "chatParticipantAdditions");
        const stream = new ChatVariableResolverResponseStream(requestId, this.c);
        const value = await item.resolver.resolve2(item.data.name, { prompt: messageText }, stream.apiObject, token);
        if (value && value[0]) {
          return value[0].value;
        }
      } else {
        const value = await item.resolver.resolve(item.data.name, { prompt: messageText }, token);
        if (value && value[0]) {
          return value[0].value;
        }
      }
    } catch (err) {
      $hb(err);
    }
    return void 0;
  }
  registerVariableResolver(extension, id2, name, userDescription, modelDescription, isSlow, resolver, fullName, themeIconId) {
    const handle = _$2wc.a++;
    const icon = themeIconId ? ThemeIcon.fromId(themeIconId) : void 0;
    this.b.set(handle, { extension, data: { id: id2, name, description: userDescription, modelDescription, icon }, resolver });
    this.c.$registerVariable(handle, { id: id2, name, description: userDescription, modelDescription, isSlow, fullName, icon });
    return $1c(() => {
      this.b.delete(handle);
      this.c.$unregisterVariable(handle);
    });
  }
};
var ChatVariableResolverResponseStream = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.a = false;
  }
  close() {
    this.a = true;
  }
  get apiObject() {
    if (!this.b) {
      let throwIfDone2 = function(source) {
        if (that.a) {
          const err = new Error("Response stream has been closed");
          Error.captureStackTrace(err, source);
          throw err;
        }
      };
      var throwIfDone = throwIfDone2;
      const that = this;
      const _report = (progress) => {
        this.d.$handleProgressChunk(this.c, progress);
      };
      this.b = {
        progress(value) {
          throwIfDone2(this.progress);
          const part = new $JV(value);
          const dto = ChatResponseProgressPart.from(part);
          _report(dto);
          return this;
        },
        reference(value) {
          throwIfDone2(this.reference);
          const part = new $NV(value);
          const dto = ChatResponseReferencePart.from(part);
          _report(dto);
          return this;
        },
        push(part) {
          throwIfDone2(this.push);
          if (part instanceof $NV) {
            _report(ChatResponseReferencePart.from(part));
          } else if (part instanceof $JV) {
            _report(ChatResponseProgressPart.from(part));
          }
          return this;
        }
      };
    }
    return this.b;
  }
};

// out-build/vs/workbench/api/common/extHostClipboard.js
var $3wc = class {
  constructor(mainContext) {
    const proxy = mainContext.getProxy($xT.MainThreadClipboard);
    this.value = Object.freeze({
      readText() {
        return proxy.$readText();
      },
      writeText(value) {
        return proxy.$writeText(value);
      }
    });
  }
};

// out-build/vs/workbench/contrib/webview/common/webview.js
var $EJb = "vscode-cdn.net";
var $FJb = `vscode-resource.${$EJb}`;
var $GJb = `'self' https://*.${$EJb}`;
function $HJb(resource, remoteInfo) {
  if (resource.scheme === Schemas.http || resource.scheme === Schemas.https) {
    return resource;
  }
  if (remoteInfo && remoteInfo.authority && remoteInfo.isRemote && resource.scheme === Schemas.file) {
    resource = URI.from({
      scheme: Schemas.vscodeRemote,
      authority: remoteInfo.authority,
      path: resource.path
    });
  }
  return URI.from({
    scheme: Schemas.https,
    authority: `${resource.scheme}+${encodeAuthority(resource.authority)}.${$FJb}`,
    path: resource.path,
    fragment: resource.fragment,
    query: resource.query
  });
}
function encodeAuthority(authority) {
  return authority.replace(/./g, (char) => {
    const code = char.charCodeAt(0);
    if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
      return char;
    }
    return "-" + code.toString(16).padStart(4, "0");
  });
}

// out-build/vs/workbench/api/common/extHostCodeInsets.js
var $5wc = class {
  constructor(d, e, f) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.a = 0;
    this.b = new $2c();
    this.c = /* @__PURE__ */ new Map();
    this.b.add(e.onDidChangeVisibleTextEditors(() => {
      const visibleEditor = e.getVisibleTextEditors();
      for (const value of this.c.values()) {
        if (visibleEditor.indexOf(value.editor) < 0) {
          value.inset.dispose();
        }
      }
    }));
  }
  dispose() {
    this.c.forEach((value) => value.inset.dispose());
    this.b.dispose();
  }
  createWebviewEditorInset(editor, line, height, options2, extension) {
    let apiEditor;
    for (const candidate of this.e.getVisibleTextEditors(true)) {
      if (candidate.value === editor) {
        apiEditor = candidate;
        break;
      }
    }
    if (!apiEditor) {
      throw new Error("not a visible editor");
    }
    const that = this;
    const handle = this.a++;
    const onDidReceiveMessage = new $ze();
    const onDidDispose = new $ze();
    const webview = new class {
      constructor() {
        this.a = "";
        this.b = /* @__PURE__ */ Object.create(null);
      }
      asWebviewUri(resource) {
        return $HJb(resource, that.f);
      }
      get cspSource() {
        return $GJb;
      }
      set options(value) {
        this.b = value;
        that.d.$setOptions(handle, value);
      }
      get options() {
        return this.b;
      }
      set html(value) {
        this.a = value;
        that.d.$setHtml(handle, value);
      }
      get html() {
        return this.a;
      }
      get onDidReceiveMessage() {
        return onDidReceiveMessage.event;
      }
      postMessage(message) {
        return that.d.$postMessage(handle, message);
      }
    }();
    const inset = new class {
      constructor() {
        this.editor = editor;
        this.line = line;
        this.height = height;
        this.webview = webview;
        this.onDidDispose = onDidDispose.event;
      }
      dispose() {
        if (that.c.has(handle)) {
          that.c.delete(handle);
          that.d.$disposeEditorInset(handle);
          onDidDispose.fire();
          onDidDispose.dispose();
          onDidReceiveMessage.dispose();
        }
      }
    }();
    this.d.$createEditorInset(handle, apiEditor.id, apiEditor.value.document.uri, line + 1, height, options2 || {}, extension.identifier, extension.extensionLocation);
    this.c.set(handle, { editor, inset, onDidReceiveMessage });
    return inset;
  }
  $onDidDispose(handle) {
    const value = this.c.get(handle);
    if (value) {
      value.inset.dispose();
    }
  }
  $onDidReceiveMessage(handle, message) {
    const value = this.c.get(handle);
    value?.onDidReceiveMessage.fire(message);
  }
};

// out-build/vs/workbench/api/common/extHostComments.js
function $6wc(mainContext, commands, documents) {
  const proxy = mainContext.getProxy($xT.MainThreadComments);
  class ExtHostCommentsImpl {
    static {
      this.a = 0;
    }
    constructor() {
      this.b = /* @__PURE__ */ new Map();
      this.c = new $7z();
      commands.registerArgumentProcessor({
        processArgument: (arg) => {
          if (arg && arg.$mid === 6) {
            const commentController = this.b.get(arg.handle);
            if (!commentController) {
              return arg;
            }
            return commentController.value;
          } else if (arg && arg.$mid === 7) {
            const marshalledCommentThread = arg;
            const commentController = this.b.get(marshalledCommentThread.commentControlHandle);
            if (!commentController) {
              return marshalledCommentThread;
            }
            const commentThread = commentController.getCommentThread(marshalledCommentThread.commentThreadHandle);
            if (!commentThread) {
              return marshalledCommentThread;
            }
            return commentThread.value;
          } else if (arg && (arg.$mid === 9 || arg.$mid === 8)) {
            const commentController = this.b.get(arg.thread.commentControlHandle);
            if (!commentController) {
              return arg;
            }
            const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
            if (!commentThread) {
              return arg;
            }
            if (arg.$mid === 8) {
              return commentThread.value;
            }
            return {
              thread: commentThread.value,
              text: arg.text
            };
          } else if (arg && arg.$mid === 10) {
            const commentController = this.b.get(arg.thread.commentControlHandle);
            if (!commentController) {
              return arg;
            }
            const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
            if (!commentThread) {
              return arg;
            }
            const commentUniqueId = arg.commentUniqueId;
            const comment = commentThread.getCommentByUniqueId(commentUniqueId);
            if (!comment) {
              return arg;
            }
            return comment;
          } else if (arg && arg.$mid === 11) {
            const commentController = this.b.get(arg.thread.commentControlHandle);
            if (!commentController) {
              return arg;
            }
            const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
            if (!commentThread) {
              return arg;
            }
            const body = arg.text;
            const commentUniqueId = arg.commentUniqueId;
            const comment = commentThread.getCommentByUniqueId(commentUniqueId);
            if (!comment) {
              return arg;
            }
            if (typeof comment.body === "string") {
              comment.body = body;
            } else {
              comment.body = new $4T(body);
            }
            return comment;
          }
          return arg;
        }
      });
    }
    createCommentController(extension, id2, label) {
      const handle = ExtHostCommentsImpl.a++;
      const commentController = new ExtHostCommentController(extension, handle, id2, label);
      this.b.set(commentController.handle, commentController);
      const commentControllers = this.c.get(extension.identifier) || [];
      commentControllers.push(commentController);
      this.c.set(extension.identifier, commentControllers);
      return commentController.value;
    }
    async $createCommentThreadTemplate(commentControllerHandle, uriComponents, range, editorId) {
      const commentController = this.b.get(commentControllerHandle);
      if (!commentController) {
        return;
      }
      commentController.$createCommentThreadTemplate(uriComponents, range, editorId);
    }
    async $setActiveComment(controllerHandle, commentInfo) {
      const commentController = this.b.get(controllerHandle);
      if (!commentController) {
        return;
      }
      commentController.$setActiveComment(commentInfo ?? void 0);
    }
    async $updateCommentThreadTemplate(commentControllerHandle, threadHandle, range) {
      const commentController = this.b.get(commentControllerHandle);
      if (!commentController) {
        return;
      }
      commentController.$updateCommentThreadTemplate(threadHandle, range);
    }
    $deleteCommentThread(commentControllerHandle, commentThreadHandle) {
      const commentController = this.b.get(commentControllerHandle);
      commentController?.$deleteCommentThread(commentThreadHandle);
    }
    async $updateCommentThread(commentControllerHandle, commentThreadHandle, changes) {
      const commentController = this.b.get(commentControllerHandle);
      commentController?.$updateCommentThread(commentThreadHandle, changes);
    }
    async $provideCommentingRanges(commentControllerHandle, uriComponents, token) {
      const commentController = this.b.get(commentControllerHandle);
      if (!commentController || !commentController.commentingRangeProvider) {
        return Promise.resolve(void 0);
      }
      const document2 = await documents.ensureDocumentData(URI.revive(uriComponents));
      return $Nh(async () => {
        const rangesResult = await commentController.commentingRangeProvider.provideCommentingRanges(document2.document, token);
        let ranges;
        if (Array.isArray(rangesResult)) {
          ranges = {
            ranges: rangesResult,
            fileComments: false
          };
        } else if (rangesResult) {
          ranges = {
            ranges: rangesResult.ranges || [],
            fileComments: rangesResult.enableFileComments || false
          };
        } else {
          ranges = rangesResult ?? void 0;
        }
        return ranges;
      }).then((ranges) => {
        let convertedResult = void 0;
        if (ranges) {
          convertedResult = {
            ranges: ranges.ranges.map((x) => Range.from(x)),
            fileComments: ranges.fileComments
          };
        }
        return convertedResult;
      });
    }
    $toggleReaction(commentControllerHandle, threadHandle, uri, comment, reaction) {
      const commentController = this.b.get(commentControllerHandle);
      if (!commentController || !commentController.reactionHandler) {
        return Promise.resolve(void 0);
      }
      return $Nh(() => {
        const commentThread = commentController.getCommentThread(threadHandle);
        if (commentThread) {
          const vscodeComment = commentThread.getCommentByUniqueId(comment.uniqueIdInThread);
          if (commentController !== void 0 && vscodeComment) {
            if (commentController.reactionHandler) {
              return commentController.reactionHandler(vscodeComment, convertFromReaction(reaction));
            }
          }
        }
        return Promise.resolve(void 0);
      });
    }
  }
  class ExtHostCommentThread {
    static {
      this.a = 0;
    }
    set threadId(id2) {
      this.n = id2;
    }
    get threadId() {
      return this.n;
    }
    get id() {
      return this.n;
    }
    get resource() {
      return this.o;
    }
    get uri() {
      return this.o;
    }
    set range(range) {
      if (range === void 0 !== (this.p === void 0) || (!range || !this.p || !range.isEqual(this.p))) {
        this.p = range;
        this.b.range = range;
        this.c.fire();
      }
    }
    get range() {
      return this.p;
    }
    set canReply(state) {
      if (this.d !== state) {
        this.d = state;
        this.b.canReply = state;
        this.c.fire();
      }
    }
    get canReply() {
      return this.d;
    }
    get label() {
      return this.e;
    }
    set label(label) {
      this.e = label;
      this.b.label = label;
      this.c.fire();
    }
    get contextValue() {
      return this.f;
    }
    set contextValue(context) {
      this.f = context;
      this.b.contextValue = context;
      this.c.fire();
    }
    get comments() {
      return this.q;
    }
    set comments(newComments) {
      this.q = newComments;
      this.b.comments = newComments;
      this.c.fire();
    }
    get collapsibleState() {
      return this.g;
    }
    set collapsibleState(newState) {
      if (this.g === newState) {
        return;
      }
      this.g = newState;
      this.b.collapsibleState = newState;
      this.c.fire();
    }
    get state() {
      return this.h;
    }
    set state(newState) {
      this.h = newState;
      if (typeof newState === "object") {
        $AN(this.extensionDescription, "commentThreadApplicability");
        this.b.state = newState.resolved;
        this.b.applicability = newState.applicability;
      } else {
        this.b.state = newState;
      }
      this.c.fire();
    }
    get isDisposed() {
      return this.j;
    }
    constructor(commentControllerId, m, n, o, p, q, extensionDescription, r, editorId) {
      this.m = m;
      this.n = n;
      this.o = o;
      this.p = p;
      this.q = q;
      this.extensionDescription = extensionDescription;
      this.r = r;
      this.handle = ExtHostCommentThread.a++;
      this.commentHandle = 0;
      this.b = /* @__PURE__ */ Object.create(null);
      this.c = new $ze();
      this.onDidUpdateCommentThread = this.c.event;
      this.d = true;
      this.k = /* @__PURE__ */ new Map();
      this.l = new $4c();
      this.l.value = new $2c();
      if (this.n === void 0) {
        this.n = `${commentControllerId}.${this.handle}`;
      }
      proxy.$createCommentThread(m, this.handle, this.n, this.o, Range.from(this.p), this.q.map((cmt) => convertToDTOComment(this, cmt, this.k, this.extensionDescription)), extensionDescription.identifier, this.r, editorId);
      this.i = [];
      this.j = false;
      this.i.push(this.onDidUpdateCommentThread(() => {
        this.eventuallyUpdateCommentThread();
      }));
      this.i.push({
        dispose: () => {
          proxy.$deleteCommentThread(m, this.handle);
        }
      });
      const that = this;
      this.value = {
        get uri() {
          return that.uri;
        },
        get range() {
          return that.range;
        },
        set range(value) {
          that.range = value;
        },
        get comments() {
          return that.comments;
        },
        set comments(value) {
          that.comments = value;
        },
        get collapsibleState() {
          return that.collapsibleState;
        },
        set collapsibleState(value) {
          that.collapsibleState = value;
        },
        get canReply() {
          return that.canReply;
        },
        set canReply(state) {
          that.canReply = state;
        },
        get contextValue() {
          return that.contextValue;
        },
        set contextValue(value) {
          that.contextValue = value;
        },
        get label() {
          return that.label;
        },
        set label(value) {
          that.label = value;
        },
        get state() {
          return that.state;
        },
        set state(value) {
          that.state = value;
        },
        reveal: (comment, options2) => that.reveal(comment, options2),
        hide: () => that.hide(),
        dispose: () => {
          that.dispose();
        }
      };
    }
    s() {
      if (this.r) {
        this.r = false;
        this.b.isTemplate = false;
      }
    }
    eventuallyUpdateCommentThread() {
      if (this.j) {
        return;
      }
      this.s();
      if (!this.l.value) {
        this.l.value = new $2c();
      }
      const modified = (value) => Object.prototype.hasOwnProperty.call(this.b, value);
      const formattedModifications = {};
      if (modified("range")) {
        formattedModifications.range = Range.from(this.p);
      }
      if (modified("label")) {
        formattedModifications.label = this.label;
      }
      if (modified("contextValue")) {
        formattedModifications.contextValue = this.contextValue ?? null;
      }
      if (modified("comments")) {
        formattedModifications.comments = this.q.map((cmt) => convertToDTOComment(this, cmt, this.k, this.extensionDescription));
      }
      if (modified("collapsibleState")) {
        formattedModifications.collapseState = convertToCollapsibleState(this.g);
      }
      if (modified("canReply")) {
        formattedModifications.canReply = this.canReply;
      }
      if (modified("state")) {
        formattedModifications.state = convertToState(this.h);
      }
      if (modified("applicability")) {
        formattedModifications.applicability = convertToRelevance(this.h);
      }
      if (modified("isTemplate")) {
        formattedModifications.isTemplate = this.r;
      }
      this.b = {};
      proxy.$updateCommentThread(this.m, this.handle, this.n, this.o, formattedModifications);
    }
    getCommentByUniqueId(uniqueId) {
      for (const key of this.k) {
        const comment = key[0];
        const id2 = key[1];
        if (uniqueId === id2) {
          return comment;
        }
      }
      return;
    }
    async reveal(commentOrOptions, options2) {
      $AN(this.extensionDescription, "commentReveal");
      let comment;
      if (commentOrOptions && commentOrOptions.body !== void 0) {
        comment = commentOrOptions;
      } else {
        options2 = options2 ?? commentOrOptions;
      }
      let commentToReveal = comment ? this.k.get(comment) : void 0;
      commentToReveal ??= this.k.get(this.q[0]);
      let preserveFocus = true;
      let focusReply = false;
      if (options2?.focus === CommentThreadFocus.Reply) {
        focusReply = true;
        preserveFocus = false;
      } else if (options2?.focus === CommentThreadFocus.Comment) {
        preserveFocus = false;
      }
      return proxy.$revealCommentThread(this.m, this.handle, commentToReveal, { preserveFocus, focusReply });
    }
    async hide() {
      return proxy.$hideCommentThread(this.m, this.handle);
    }
    dispose() {
      this.j = true;
      this.l.dispose();
      this.i.forEach((disposable) => disposable.dispose());
    }
  }
  __decorate([
    $$t(100)
  ], ExtHostCommentThread.prototype, "eventuallyUpdateCommentThread", null);
  class ExtHostCommentController {
    get id() {
      return this.j;
    }
    get label() {
      return this.k;
    }
    get handle() {
      return this.i;
    }
    get commentingRangeProvider() {
      return this.b;
    }
    set commentingRangeProvider(provider) {
      this.b = provider;
      if (provider?.resourceHints) {
        $AN(this.h, "commentingRangeHint");
      }
      proxy.$updateCommentingRanges(this.handle, provider?.resourceHints);
    }
    get reactionHandler() {
      return this.c;
    }
    set reactionHandler(handler) {
      this.c = handler;
      proxy.$updateCommentControllerFeatures(this.handle, { reactionHandler: !!handler });
    }
    get options() {
      return this.d;
    }
    set options(options2) {
      this.d = options2;
      proxy.$updateCommentControllerFeatures(this.handle, { options: this.d });
    }
    get activeComment() {
      $AN(this.h, "activeComment");
      return this.e;
    }
    get activeCommentThread() {
      $AN(this.h, "activeComment");
      return this.f?.value;
    }
    constructor(h, i, j, k) {
      this.h = h;
      this.i = i;
      this.j = j;
      this.k = k;
      this.a = /* @__PURE__ */ new Map();
      proxy.$registerCommentController(this.handle, j, k, this.h.identifier.value);
      const that = this;
      this.value = Object.freeze({
        id: that.id,
        label: that.label,
        get options() {
          return that.options;
        },
        set options(options2) {
          that.options = options2;
        },
        get commentingRangeProvider() {
          return that.commentingRangeProvider;
        },
        set commentingRangeProvider(commentingRangeProvider) {
          that.commentingRangeProvider = commentingRangeProvider;
        },
        get reactionHandler() {
          return that.reactionHandler;
        },
        set reactionHandler(handler) {
          that.reactionHandler = handler;
        },
        // get activeComment(): vscode.Comment | undefined { return that.activeComment; },
        get activeCommentThread() {
          return that.activeCommentThread;
        },
        createCommentThread(uri, range, comments) {
          return that.createCommentThread(uri, range, comments).value;
        },
        dispose: () => {
          that.dispose();
        }
      });
      this.g = [];
      this.g.push({
        dispose: () => {
          proxy.$unregisterCommentController(this.handle);
        }
      });
    }
    createCommentThread(resource, range, comments) {
      if (range === void 0) {
        $AN(this.h, "fileComments");
      }
      const commentThread = new ExtHostCommentThread(this.id, this.handle, void 0, resource, range, comments, this.h, false);
      this.a.set(commentThread.handle, commentThread);
      return commentThread;
    }
    $setActiveComment(commentInfo) {
      if (!commentInfo) {
        this.e = void 0;
        this.f = void 0;
        return;
      }
      const thread = this.a.get(commentInfo.commentThreadHandle);
      if (thread) {
        this.e = commentInfo.uniqueIdInThread ? thread.getCommentByUniqueId(commentInfo.uniqueIdInThread) : void 0;
        this.f = thread;
      }
    }
    $createCommentThreadTemplate(uriComponents, range, editorId) {
      const commentThread = new ExtHostCommentThread(this.id, this.handle, void 0, URI.revive(uriComponents), Range.to(range), [], this.h, true, editorId);
      commentThread.collapsibleState = CommentThreadCollapsibleState.Expanded;
      this.a.set(commentThread.handle, commentThread);
      return commentThread;
    }
    $updateCommentThreadTemplate(threadHandle, range) {
      const thread = this.a.get(threadHandle);
      if (thread) {
        thread.range = Range.to(range);
      }
    }
    $updateCommentThread(threadHandle, changes) {
      const thread = this.a.get(threadHandle);
      if (!thread) {
        return;
      }
      const modified = (value) => Object.prototype.hasOwnProperty.call(changes, value);
      if (modified("collapseState")) {
        thread.collapsibleState = convertToCollapsibleState(changes.collapseState);
      }
    }
    $deleteCommentThread(threadHandle) {
      const thread = this.a.get(threadHandle);
      thread?.dispose();
      this.a.delete(threadHandle);
    }
    getCommentThread(handle) {
      return this.a.get(handle);
    }
    dispose() {
      this.a.forEach((value) => {
        value.dispose();
      });
      this.g.forEach((disposable) => disposable.dispose());
    }
  }
  function convertToDTOComment(thread, vscodeComment, commentsMap, extension) {
    let commentUniqueId = commentsMap.get(vscodeComment);
    if (!commentUniqueId) {
      commentUniqueId = ++thread.commentHandle;
      commentsMap.set(vscodeComment, commentUniqueId);
    }
    if (vscodeComment.state !== void 0) {
      $AN(extension, "commentsDraftState");
    }
    if (vscodeComment.reactions?.some((reaction) => reaction.reactors !== void 0)) {
      $AN(extension, "commentReactor");
    }
    return {
      mode: vscodeComment.mode,
      contextValue: vscodeComment.contextValue,
      uniqueIdInThread: commentUniqueId,
      body: typeof vscodeComment.body === "string" ? vscodeComment.body : MarkdownString.from(vscodeComment.body),
      userName: vscodeComment.author.name,
      userIconPath: vscodeComment.author.iconPath,
      label: vscodeComment.label,
      commentReactions: vscodeComment.reactions ? vscodeComment.reactions.map((reaction) => convertToReaction(reaction)) : void 0,
      state: vscodeComment.state,
      timestamp: vscodeComment.timestamp?.toJSON()
    };
  }
  function convertToReaction(reaction) {
    return {
      label: reaction.label,
      iconPath: reaction.iconPath ? $fW(reaction.iconPath) : void 0,
      count: reaction.count,
      hasReacted: reaction.authorHasReacted,
      reactors: reaction.reactors && reaction.reactors.length > 0 && typeof reaction.reactors[0] !== "string" ? reaction.reactors.map((reactor) => reactor.name) : reaction.reactors
    };
  }
  function convertFromReaction(reaction) {
    return {
      label: reaction.label || "",
      count: reaction.count || 0,
      iconPath: reaction.iconPath ? URI.revive(reaction.iconPath) : "",
      authorHasReacted: reaction.hasReacted || false,
      reactors: reaction.reactors?.map((reactor) => ({ name: reactor }))
    };
  }
  function convertToCollapsibleState(kind) {
    if (kind !== void 0) {
      switch (kind) {
        case CommentThreadCollapsibleState2.Expanded:
          return CommentThreadCollapsibleState.Expanded;
        case CommentThreadCollapsibleState2.Collapsed:
          return CommentThreadCollapsibleState.Collapsed;
      }
    }
    return CommentThreadCollapsibleState.Collapsed;
  }
  function convertToState(kind) {
    let resolvedKind;
    if (typeof kind === "object") {
      resolvedKind = kind.resolved;
    } else {
      resolvedKind = kind;
    }
    if (resolvedKind !== void 0) {
      switch (resolvedKind) {
        case CommentThreadState2.Unresolved:
          return CommentThreadState.Unresolved;
        case CommentThreadState2.Resolved:
          return CommentThreadState.Resolved;
      }
    }
    return CommentThreadState.Unresolved;
  }
  function convertToRelevance(kind) {
    let applicabilityKind = void 0;
    if (typeof kind === "object") {
      applicabilityKind = kind.applicability;
    }
    if (applicabilityKind !== void 0) {
      switch (applicabilityKind) {
        case CommentThreadApplicability2.Current:
          return CommentThreadApplicability.Current;
        case CommentThreadApplicability2.Outdated:
          return CommentThreadApplicability.Outdated;
      }
    }
    return CommentThreadApplicability.Current;
  }
  return new ExtHostCommentsImpl();
}

// out-build/vs/base/common/semver/semver.js
var exports = {};
var module = { exports };
!function(e, r) {
  if ("object" == typeof exports && "object" == typeof module) module.exports = r();
  else if ("function" == typeof define && define.amd) define([], r);
  else {
    var t = r();
    for (var n in t) ("object" == typeof exports ? exports : e)[n] = t[n];
  }
}("undefined" != typeof self ? self : void 0, function() {
  return function(e) {
    var r = {};
    function t(n) {
      if (r[n]) return r[n].exports;
      var o = r[n] = { i: n, l: false, exports: {} };
      return e[n].call(o.exports, o, o.exports, t), o.l = true, o.exports;
    }
    return t.m = e, t.c = r, t.d = function(e2, r2, n) {
      t.o(e2, r2) || Object.defineProperty(e2, r2, { enumerable: true, get: n });
    }, t.r = function(e2) {
      "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e2, "__esModule", { value: true });
    }, t.t = function(e2, r2) {
      if (1 & r2 && (e2 = t(e2)), 8 & r2) return e2;
      if (4 & r2 && "object" == typeof e2 && e2 && e2.__esModule) return e2;
      var n = /* @__PURE__ */ Object.create(null);
      if (t.r(n), Object.defineProperty(n, "default", { enumerable: true, value: e2 }), 2 & r2 && "string" != typeof e2) for (var o in e2) t.d(n, o, function(r3) {
        return e2[r3];
      }.bind(null, o));
      return n;
    }, t.n = function(e2) {
      var r2 = e2 && e2.__esModule ? function() {
        return e2.default;
      } : function() {
        return e2;
      };
      return t.d(r2, "a", r2), r2;
    }, t.o = function(e2, r2) {
      return Object.prototype.hasOwnProperty.call(e2, r2);
    }, t.p = "", t(t.s = 0);
  }([function(e, r, t) {
    (function(t2) {
      var n;
      r = e.exports = H, n = "object" == typeof t2 && t2.env && t2.env.NODE_DEBUG && /\bsemver\b/i.test(t2.env.NODE_DEBUG) ? function() {
        var e2 = Array.prototype.slice.call(arguments, 0);
        e2.unshift("SEMVER"), console.log.apply(console, e2);
      } : function() {
      }, r.SEMVER_SPEC_VERSION = "2.0.0";
      var o = 256, i = Number.MAX_SAFE_INTEGER || 9007199254740991, s = r.re = [], a = r.src = [], u = 0, c = u++;
      a[c] = "0|[1-9]\\d*";
      var p = u++;
      a[p] = "[0-9]+";
      var f = u++;
      a[f] = "\\d*[a-zA-Z-][a-zA-Z0-9-]*";
      var l = u++;
      a[l] = "(" + a[c] + ")\\.(" + a[c] + ")\\.(" + a[c] + ")";
      var h = u++;
      a[h] = "(" + a[p] + ")\\.(" + a[p] + ")\\.(" + a[p] + ")";
      var v = u++;
      a[v] = "(?:" + a[c] + "|" + a[f] + ")";
      var m = u++;
      a[m] = "(?:" + a[p] + "|" + a[f] + ")";
      var w = u++;
      a[w] = "(?:-(" + a[v] + "(?:\\." + a[v] + ")*))";
      var g = u++;
      a[g] = "(?:-?(" + a[m] + "(?:\\." + a[m] + ")*))";
      var y = u++;
      a[y] = "[0-9A-Za-z-]+";
      var d = u++;
      a[d] = "(?:\\+(" + a[y] + "(?:\\." + a[y] + ")*))";
      var b = u++, j = "v?" + a[l] + a[w] + "?" + a[d] + "?";
      a[b] = "^" + j + "$";
      var E = "[v=\\s]*" + a[h] + a[g] + "?" + a[d] + "?", T = u++;
      a[T] = "^" + E + "$";
      var x = u++;
      a[x] = "((?:<|>)?=?)";
      var $ = u++;
      a[$] = a[p] + "|x|X|\\*";
      var k = u++;
      a[k] = a[c] + "|x|X|\\*";
      var S = u++;
      a[S] = "[v=\\s]*(" + a[k] + ")(?:\\.(" + a[k] + ")(?:\\.(" + a[k] + ")(?:" + a[w] + ")?" + a[d] + "?)?)?";
      var R = u++;
      a[R] = "[v=\\s]*(" + a[$] + ")(?:\\.(" + a[$] + ")(?:\\.(" + a[$] + ")(?:" + a[g] + ")?" + a[d] + "?)?)?";
      var I = u++;
      a[I] = "^" + a[x] + "\\s*" + a[S] + "$";
      var _ = u++;
      a[_] = "^" + a[x] + "\\s*" + a[R] + "$";
      var O = u++;
      a[O] = "(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";
      var A = u++;
      a[A] = "(?:~>?)";
      var M = u++;
      a[M] = "(\\s*)" + a[A] + "\\s+", s[M] = new RegExp(a[M], "g");
      var V = u++;
      a[V] = "^" + a[A] + a[S] + "$";
      var P = u++;
      a[P] = "^" + a[A] + a[R] + "$";
      var C = u++;
      a[C] = "(?:\\^)";
      var L = u++;
      a[L] = "(\\s*)" + a[C] + "\\s+", s[L] = new RegExp(a[L], "g");
      var N = u++;
      a[N] = "^" + a[C] + a[S] + "$";
      var q = u++;
      a[q] = "^" + a[C] + a[R] + "$";
      var D = u++;
      a[D] = "^" + a[x] + "\\s*(" + E + ")$|^$";
      var X = u++;
      a[X] = "^" + a[x] + "\\s*(" + j + ")$|^$";
      var z = u++;
      a[z] = "(\\s*)" + a[x] + "\\s*(" + E + "|" + a[S] + ")", s[z] = new RegExp(a[z], "g");
      var G = u++;
      a[G] = "^\\s*(" + a[S] + ")\\s+-\\s+(" + a[S] + ")\\s*$";
      var Z = u++;
      a[Z] = "^\\s*(" + a[R] + ")\\s+-\\s+(" + a[R] + ")\\s*$";
      var B = u++;
      a[B] = "(<|>)?=?\\s*\\*";
      for (var U = 0; U < 35; U++) n(U, a[U]), s[U] || (s[U] = new RegExp(a[U]));
      function F(e2, r2) {
        if (e2 instanceof H) return e2;
        if ("string" != typeof e2) return null;
        if (e2.length > o) return null;
        if (!(r2 ? s[T] : s[b]).test(e2)) return null;
        try {
          return new H(e2, r2);
        } catch (e3) {
          return null;
        }
      }
      function H(e2, r2) {
        if (e2 instanceof H) {
          if (e2.loose === r2) return e2;
          e2 = e2.version;
        } else if ("string" != typeof e2) throw new TypeError("Invalid Version: " + e2);
        if (e2.length > o) throw new TypeError("version is longer than " + o + " characters");
        if (!(this instanceof H)) return new H(e2, r2);
        n("SemVer", e2, r2), this.loose = r2;
        var t3 = e2.trim().match(r2 ? s[T] : s[b]);
        if (!t3) throw new TypeError("Invalid Version: " + e2);
        if (this.raw = e2, this.major = +t3[1], this.minor = +t3[2], this.patch = +t3[3], this.major > i || this.major < 0) throw new TypeError("Invalid major version");
        if (this.minor > i || this.minor < 0) throw new TypeError("Invalid minor version");
        if (this.patch > i || this.patch < 0) throw new TypeError("Invalid patch version");
        t3[4] ? this.prerelease = t3[4].split(".").map(function(e3) {
          if (/^[0-9]+$/.test(e3)) {
            var r3 = +e3;
            if (r3 >= 0 && r3 < i) return r3;
          }
          return e3;
        }) : this.prerelease = [], this.build = t3[5] ? t3[5].split(".") : [], this.format();
      }
      r.parse = F, r.valid = function(e2, r2) {
        var t3 = F(e2, r2);
        return t3 ? t3.version : null;
      }, r.clean = function(e2, r2) {
        var t3 = F(e2.trim().replace(/^[=v]+/, ""), r2);
        return t3 ? t3.version : null;
      }, r.SemVer = H, H.prototype.format = function() {
        return this.version = this.major + "." + this.minor + "." + this.patch, this.prerelease.length && (this.version += "-" + this.prerelease.join(".")), this.version;
      }, H.prototype.toString = function() {
        return this.version;
      }, H.prototype.compare = function(e2) {
        return n("SemVer.compare", this.version, this.loose, e2), e2 instanceof H || (e2 = new H(e2, this.loose)), this.compareMain(e2) || this.comparePre(e2);
      }, H.prototype.compareMain = function(e2) {
        return e2 instanceof H || (e2 = new H(e2, this.loose)), K(this.major, e2.major) || K(this.minor, e2.minor) || K(this.patch, e2.patch);
      }, H.prototype.comparePre = function(e2) {
        if (e2 instanceof H || (e2 = new H(e2, this.loose)), this.prerelease.length && !e2.prerelease.length) return -1;
        if (!this.prerelease.length && e2.prerelease.length) return 1;
        if (!this.prerelease.length && !e2.prerelease.length) return 0;
        var r2 = 0;
        do {
          var t3 = this.prerelease[r2], o2 = e2.prerelease[r2];
          if (n("prerelease compare", r2, t3, o2), void 0 === t3 && void 0 === o2) return 0;
          if (void 0 === o2) return 1;
          if (void 0 === t3) return -1;
          if (t3 !== o2) return K(t3, o2);
        } while (++r2);
      }, H.prototype.inc = function(e2, r2) {
        switch (e2) {
          case "premajor":
            this.prerelease.length = 0, this.patch = 0, this.minor = 0, this.major++, this.inc("pre", r2);
            break;
          case "preminor":
            this.prerelease.length = 0, this.patch = 0, this.minor++, this.inc("pre", r2);
            break;
          case "prepatch":
            this.prerelease.length = 0, this.inc("patch", r2), this.inc("pre", r2);
            break;
          case "prerelease":
            0 === this.prerelease.length && this.inc("patch", r2), this.inc("pre", r2);
            break;
          case "major":
            0 === this.minor && 0 === this.patch && 0 !== this.prerelease.length || this.major++, this.minor = 0, this.patch = 0, this.prerelease = [];
            break;
          case "minor":
            0 === this.patch && 0 !== this.prerelease.length || this.minor++, this.patch = 0, this.prerelease = [];
            break;
          case "patch":
            0 === this.prerelease.length && this.patch++, this.prerelease = [];
            break;
          case "pre":
            if (0 === this.prerelease.length) this.prerelease = [0];
            else {
              for (var t3 = this.prerelease.length; --t3 >= 0; ) "number" == typeof this.prerelease[t3] && (this.prerelease[t3]++, t3 = -2);
              -1 === t3 && this.prerelease.push(0);
            }
            r2 && (this.prerelease[0] === r2 ? isNaN(this.prerelease[1]) && (this.prerelease = [r2, 0]) : this.prerelease = [r2, 0]);
            break;
          default:
            throw new Error("invalid increment argument: " + e2);
        }
        return this.format(), this.raw = this.version, this;
      }, r.inc = function(e2, r2, t3, n2) {
        "string" == typeof t3 && (n2 = t3, t3 = void 0);
        try {
          return new H(e2, t3).inc(r2, n2).version;
        } catch (e3) {
          return null;
        }
      }, r.diff = function(e2, r2) {
        if (ee(e2, r2)) return null;
        var t3 = F(e2), n2 = F(r2);
        if (t3.prerelease.length || n2.prerelease.length) {
          for (var o2 in t3) if (("major" === o2 || "minor" === o2 || "patch" === o2) && t3[o2] !== n2[o2]) return "pre" + o2;
          return "prerelease";
        }
        for (var o2 in t3) if (("major" === o2 || "minor" === o2 || "patch" === o2) && t3[o2] !== n2[o2]) return o2;
      }, r.compareIdentifiers = K;
      var J = /^[0-9]+$/;
      function K(e2, r2) {
        var t3 = J.test(e2), n2 = J.test(r2);
        return t3 && n2 && (e2 = +e2, r2 = +r2), t3 && !n2 ? -1 : n2 && !t3 ? 1 : e2 < r2 ? -1 : e2 > r2 ? 1 : 0;
      }
      function Q(e2, r2, t3) {
        return new H(e2, t3).compare(new H(r2, t3));
      }
      function W(e2, r2, t3) {
        return Q(e2, r2, t3) > 0;
      }
      function Y(e2, r2, t3) {
        return Q(e2, r2, t3) < 0;
      }
      function ee(e2, r2, t3) {
        return 0 === Q(e2, r2, t3);
      }
      function re(e2, r2, t3) {
        return 0 !== Q(e2, r2, t3);
      }
      function te(e2, r2, t3) {
        return Q(e2, r2, t3) >= 0;
      }
      function ne(e2, r2, t3) {
        return Q(e2, r2, t3) <= 0;
      }
      function oe(e2, r2, t3, n2) {
        var o2;
        switch (r2) {
          case "===":
            "object" == typeof e2 && (e2 = e2.version), "object" == typeof t3 && (t3 = t3.version), o2 = e2 === t3;
            break;
          case "!==":
            "object" == typeof e2 && (e2 = e2.version), "object" == typeof t3 && (t3 = t3.version), o2 = e2 !== t3;
            break;
          case "":
          case "=":
          case "==":
            o2 = ee(e2, t3, n2);
            break;
          case "!=":
            o2 = re(e2, t3, n2);
            break;
          case ">":
            o2 = W(e2, t3, n2);
            break;
          case ">=":
            o2 = te(e2, t3, n2);
            break;
          case "<":
            o2 = Y(e2, t3, n2);
            break;
          case "<=":
            o2 = ne(e2, t3, n2);
            break;
          default:
            throw new TypeError("Invalid operator: " + r2);
        }
        return o2;
      }
      function ie(e2, r2) {
        if (e2 instanceof ie) {
          if (e2.loose === r2) return e2;
          e2 = e2.value;
        }
        if (!(this instanceof ie)) return new ie(e2, r2);
        n("comparator", e2, r2), this.loose = r2, this.parse(e2), this.semver === se ? this.value = "" : this.value = this.operator + this.semver.version, n("comp", this);
      }
      r.rcompareIdentifiers = function(e2, r2) {
        return K(r2, e2);
      }, r.major = function(e2, r2) {
        return new H(e2, r2).major;
      }, r.minor = function(e2, r2) {
        return new H(e2, r2).minor;
      }, r.patch = function(e2, r2) {
        return new H(e2, r2).patch;
      }, r.compare = Q, r.compareLoose = function(e2, r2) {
        return Q(e2, r2, true);
      }, r.rcompare = function(e2, r2, t3) {
        return Q(r2, e2, t3);
      }, r.sort = function(e2, t3) {
        return e2.sort(function(e3, n2) {
          return r.compare(e3, n2, t3);
        });
      }, r.rsort = function(e2, t3) {
        return e2.sort(function(e3, n2) {
          return r.rcompare(e3, n2, t3);
        });
      }, r.gt = W, r.lt = Y, r.eq = ee, r.neq = re, r.gte = te, r.lte = ne, r.cmp = oe, r.Comparator = ie;
      var se = {};
      function ae(e2, r2) {
        if (e2 instanceof ae) return e2.loose === r2 ? e2 : new ae(e2.raw, r2);
        if (e2 instanceof ie) return new ae(e2.value, r2);
        if (!(this instanceof ae)) return new ae(e2, r2);
        if (this.loose = r2, this.raw = e2, this.set = e2.split(/\s*\|\|\s*/).map(function(e3) {
          return this.parseRange(e3.trim());
        }, this).filter(function(e3) {
          return e3.length;
        }), !this.set.length) throw new TypeError("Invalid SemVer Range: " + e2);
        this.format();
      }
      function ue(e2) {
        return !e2 || "x" === e2.toLowerCase() || "*" === e2;
      }
      function ce(e2, r2, t3, n2, o2, i2, s2, a2, u2, c2, p2, f2, l2) {
        return ((r2 = ue(t3) ? "" : ue(n2) ? ">=" + t3 + ".0.0" : ue(o2) ? ">=" + t3 + "." + n2 + ".0" : ">=" + r2) + " " + (a2 = ue(u2) ? "" : ue(c2) ? "<" + (+u2 + 1) + ".0.0" : ue(p2) ? "<" + u2 + "." + (+c2 + 1) + ".0" : f2 ? "<=" + u2 + "." + c2 + "." + p2 + "-" + f2 : "<=" + a2)).trim();
      }
      function pe(e2, r2) {
        for (var t3 = 0; t3 < e2.length; t3++) if (!e2[t3].test(r2)) return false;
        if (r2.prerelease.length) {
          for (t3 = 0; t3 < e2.length; t3++) if (n(e2[t3].semver), e2[t3].semver !== se && e2[t3].semver.prerelease.length > 0) {
            var o2 = e2[t3].semver;
            if (o2.major === r2.major && o2.minor === r2.minor && o2.patch === r2.patch) return true;
          }
          return false;
        }
        return true;
      }
      function fe(e2, r2, t3) {
        try {
          r2 = new ae(r2, t3);
        } catch (e3) {
          return false;
        }
        return r2.test(e2);
      }
      function le(e2, r2, t3, n2) {
        var o2, i2, s2, a2, u2;
        switch (e2 = new H(e2, n2), r2 = new ae(r2, n2), t3) {
          case ">":
            o2 = W, i2 = ne, s2 = Y, a2 = ">", u2 = ">=";
            break;
          case "<":
            o2 = Y, i2 = te, s2 = W, a2 = "<", u2 = "<=";
            break;
          default:
            throw new TypeError('Must provide a hilo val of "<" or ">"');
        }
        if (fe(e2, r2, n2)) return false;
        for (var c2 = 0; c2 < r2.set.length; ++c2) {
          var p2 = r2.set[c2], f2 = null, l2 = null;
          if (p2.forEach(function(e3) {
            e3.semver === se && (e3 = new ie(">=0.0.0")), f2 = f2 || e3, l2 = l2 || e3, o2(e3.semver, f2.semver, n2) ? f2 = e3 : s2(e3.semver, l2.semver, n2) && (l2 = e3);
          }), f2.operator === a2 || f2.operator === u2) return false;
          if ((!l2.operator || l2.operator === a2) && i2(e2, l2.semver)) return false;
          if (l2.operator === u2 && s2(e2, l2.semver)) return false;
        }
        return true;
      }
      ie.prototype.parse = function(e2) {
        var r2 = this.loose ? s[D] : s[X], t3 = e2.match(r2);
        if (!t3) throw new TypeError("Invalid comparator: " + e2);
        this.operator = t3[1], "=" === this.operator && (this.operator = ""), t3[2] ? this.semver = new H(t3[2], this.loose) : this.semver = se;
      }, ie.prototype.toString = function() {
        return this.value;
      }, ie.prototype.test = function(e2) {
        return n("Comparator.test", e2, this.loose), this.semver === se || ("string" == typeof e2 && (e2 = new H(e2, this.loose)), oe(e2, this.operator, this.semver, this.loose));
      }, ie.prototype.intersects = function(e2, r2) {
        if (!(e2 instanceof ie)) throw new TypeError("a Comparator is required");
        var t3;
        if ("" === this.operator) return t3 = new ae(e2.value, r2), fe(this.value, t3, r2);
        if ("" === e2.operator) return t3 = new ae(this.value, r2), fe(e2.semver, t3, r2);
        var n2 = !(">=" !== this.operator && ">" !== this.operator || ">=" !== e2.operator && ">" !== e2.operator), o2 = !("<=" !== this.operator && "<" !== this.operator || "<=" !== e2.operator && "<" !== e2.operator), i2 = this.semver.version === e2.semver.version, s2 = !(">=" !== this.operator && "<=" !== this.operator || ">=" !== e2.operator && "<=" !== e2.operator), a2 = oe(this.semver, "<", e2.semver, r2) && (">=" === this.operator || ">" === this.operator) && ("<=" === e2.operator || "<" === e2.operator), u2 = oe(this.semver, ">", e2.semver, r2) && ("<=" === this.operator || "<" === this.operator) && (">=" === e2.operator || ">" === e2.operator);
        return n2 || o2 || i2 && s2 || a2 || u2;
      }, r.Range = ae, ae.prototype.format = function() {
        return this.range = this.set.map(function(e2) {
          return e2.join(" ").trim();
        }).join("||").trim(), this.range;
      }, ae.prototype.toString = function() {
        return this.range;
      }, ae.prototype.parseRange = function(e2) {
        var r2 = this.loose;
        e2 = e2.trim(), n("range", e2, r2);
        var t3 = r2 ? s[Z] : s[G];
        e2 = e2.replace(t3, ce), n("hyphen replace", e2), e2 = e2.replace(s[z], "$1$2$3"), n("comparator trim", e2, s[z]), e2 = (e2 = (e2 = e2.replace(s[M], "$1~")).replace(s[L], "$1^")).split(/\s+/).join(" ");
        var o2 = r2 ? s[D] : s[X], i2 = e2.split(" ").map(function(e3) {
          return function(e4, r3) {
            return n("comp", e4), e4 = function(e5, r4) {
              return e5.trim().split(/\s+/).map(function(e6) {
                return function(e7, r5) {
                  n("caret", e7, r5);
                  var t4 = r5 ? s[q] : s[N];
                  return e7.replace(t4, function(r6, t5, o3, i3, s2) {
                    var a2;
                    return n("caret", e7, r6, t5, o3, i3, s2), ue(t5) ? a2 = "" : ue(o3) ? a2 = ">=" + t5 + ".0.0 <" + (+t5 + 1) + ".0.0" : ue(i3) ? a2 = "0" === t5 ? ">=" + t5 + "." + o3 + ".0 <" + t5 + "." + (+o3 + 1) + ".0" : ">=" + t5 + "." + o3 + ".0 <" + (+t5 + 1) + ".0.0" : s2 ? (n("replaceCaret pr", s2), "-" !== s2.charAt(0) && (s2 = "-" + s2), a2 = "0" === t5 ? "0" === o3 ? ">=" + t5 + "." + o3 + "." + i3 + s2 + " <" + t5 + "." + o3 + "." + (+i3 + 1) : ">=" + t5 + "." + o3 + "." + i3 + s2 + " <" + t5 + "." + (+o3 + 1) + ".0" : ">=" + t5 + "." + o3 + "." + i3 + s2 + " <" + (+t5 + 1) + ".0.0") : (n("no pr"), a2 = "0" === t5 ? "0" === o3 ? ">=" + t5 + "." + o3 + "." + i3 + " <" + t5 + "." + o3 + "." + (+i3 + 1) : ">=" + t5 + "." + o3 + "." + i3 + " <" + t5 + "." + (+o3 + 1) + ".0" : ">=" + t5 + "." + o3 + "." + i3 + " <" + (+t5 + 1) + ".0.0"), n("caret return", a2), a2;
                  });
                }(e6, r4);
              }).join(" ");
            }(e4, r3), n("caret", e4), e4 = function(e5, r4) {
              return e5.trim().split(/\s+/).map(function(e6) {
                return function(e7, r5) {
                  var t4 = r5 ? s[P] : s[V];
                  return e7.replace(t4, function(r6, t5, o3, i3, s2) {
                    var a2;
                    return n("tilde", e7, r6, t5, o3, i3, s2), ue(t5) ? a2 = "" : ue(o3) ? a2 = ">=" + t5 + ".0.0 <" + (+t5 + 1) + ".0.0" : ue(i3) ? a2 = ">=" + t5 + "." + o3 + ".0 <" + t5 + "." + (+o3 + 1) + ".0" : s2 ? (n("replaceTilde pr", s2), "-" !== s2.charAt(0) && (s2 = "-" + s2), a2 = ">=" + t5 + "." + o3 + "." + i3 + s2 + " <" + t5 + "." + (+o3 + 1) + ".0") : a2 = ">=" + t5 + "." + o3 + "." + i3 + " <" + t5 + "." + (+o3 + 1) + ".0", n("tilde return", a2), a2;
                  });
                }(e6, r4);
              }).join(" ");
            }(e4, r3), n("tildes", e4), e4 = function(e5, r4) {
              return n("replaceXRanges", e5, r4), e5.split(/\s+/).map(function(e6) {
                return function(e7, r5) {
                  e7 = e7.trim();
                  var t4 = r5 ? s[_] : s[I];
                  return e7.replace(t4, function(r6, t5, o3, i3, s2, a2) {
                    n("xRange", e7, r6, t5, o3, i3, s2, a2);
                    var u2 = ue(o3), c2 = u2 || ue(i3), p2 = c2 || ue(s2);
                    return "=" === t5 && p2 && (t5 = ""), u2 ? r6 = ">" === t5 || "<" === t5 ? "<0.0.0" : "*" : t5 && p2 ? (c2 && (i3 = 0), p2 && (s2 = 0), ">" === t5 ? (t5 = ">=", c2 ? (o3 = +o3 + 1, i3 = 0, s2 = 0) : p2 && (i3 = +i3 + 1, s2 = 0)) : "<=" === t5 && (t5 = "<", c2 ? o3 = +o3 + 1 : i3 = +i3 + 1), r6 = t5 + o3 + "." + i3 + "." + s2) : c2 ? r6 = ">=" + o3 + ".0.0 <" + (+o3 + 1) + ".0.0" : p2 && (r6 = ">=" + o3 + "." + i3 + ".0 <" + o3 + "." + (+i3 + 1) + ".0"), n("xRange return", r6), r6;
                  });
                }(e6, r4);
              }).join(" ");
            }(e4, r3), n("xrange", e4), e4 = function(e5, r4) {
              return n("replaceStars", e5, r4), e5.trim().replace(s[B], "");
            }(e4, r3), n("stars", e4), e4;
          }(e3, r2);
        }).join(" ").split(/\s+/);
        return this.loose && (i2 = i2.filter(function(e3) {
          return !!e3.match(o2);
        })), i2 = i2.map(function(e3) {
          return new ie(e3, r2);
        });
      }, ae.prototype.intersects = function(e2, r2) {
        if (!(e2 instanceof ae)) throw new TypeError("a Range is required");
        return this.set.some(function(t3) {
          return t3.every(function(t4) {
            return e2.set.some(function(e3) {
              return e3.every(function(e4) {
                return t4.intersects(e4, r2);
              });
            });
          });
        });
      }, r.toComparators = function(e2, r2) {
        return new ae(e2, r2).set.map(function(e3) {
          return e3.map(function(e4) {
            return e4.value;
          }).join(" ").trim().split(" ");
        });
      }, ae.prototype.test = function(e2) {
        if (!e2) return false;
        "string" == typeof e2 && (e2 = new H(e2, this.loose));
        for (var r2 = 0; r2 < this.set.length; r2++) if (pe(this.set[r2], e2)) return true;
        return false;
      }, r.satisfies = fe, r.maxSatisfying = function(e2, r2, t3) {
        var n2 = null, o2 = null;
        try {
          var i2 = new ae(r2, t3);
        } catch (e3) {
          return null;
        }
        return e2.forEach(function(e3) {
          i2.test(e3) && (n2 && -1 !== o2.compare(e3) || (o2 = new H(n2 = e3, t3)));
        }), n2;
      }, r.minSatisfying = function(e2, r2, t3) {
        var n2 = null, o2 = null;
        try {
          var i2 = new ae(r2, t3);
        } catch (e3) {
          return null;
        }
        return e2.forEach(function(e3) {
          i2.test(e3) && (n2 && 1 !== o2.compare(e3) || (o2 = new H(n2 = e3, t3)));
        }), n2;
      }, r.validRange = function(e2, r2) {
        try {
          return new ae(e2, r2).range || "*";
        } catch (e3) {
          return null;
        }
      }, r.ltr = function(e2, r2, t3) {
        return le(e2, r2, "<", t3);
      }, r.gtr = function(e2, r2, t3) {
        return le(e2, r2, ">", t3);
      }, r.outside = le, r.prerelease = function(e2, r2) {
        var t3 = F(e2, r2);
        return t3 && t3.prerelease.length ? t3.prerelease : null;
      }, r.intersects = function(e2, r2, t3) {
        return e2 = new ae(e2, t3), r2 = new ae(r2, t3), e2.intersects(r2);
      }, r.coerce = function(e2) {
        if (e2 instanceof H) return e2;
        if ("string" != typeof e2) return null;
        var r2 = e2.match(s[O]);
        return null == r2 ? null : F((r2[1] || "0") + "." + (r2[2] || "0") + "." + (r2[3] || "0"));
      };
    }).call(this, t(1));
  }, function(e, r) {
    var t, n, o = e.exports = {};
    function i() {
      throw new Error("setTimeout has not been defined");
    }
    function s() {
      throw new Error("clearTimeout has not been defined");
    }
    function a(e2) {
      if (t === setTimeout) return setTimeout(e2, 0);
      if ((t === i || !t) && setTimeout) return t = setTimeout, setTimeout(e2, 0);
      try {
        return t(e2, 0);
      } catch (r2) {
        try {
          return t.call(null, e2, 0);
        } catch (r3) {
          return t.call(this, e2, 0);
        }
      }
    }
    !function() {
      try {
        t = "function" == typeof setTimeout ? setTimeout : i;
      } catch (e2) {
        t = i;
      }
      try {
        n = "function" == typeof clearTimeout ? clearTimeout : s;
      } catch (e2) {
        n = s;
      }
    }();
    var u, c = [], p = false, f = -1;
    function l() {
      p && u && (p = false, u.length ? c = u.concat(c) : f = -1, c.length && h());
    }
    function h() {
      if (!p) {
        var e2 = a(l);
        p = true;
        for (var r2 = c.length; r2; ) {
          for (u = c, c = []; ++f < r2; ) u && u[f].run();
          f = -1, r2 = c.length;
        }
        u = null, p = false, function(e3) {
          if (n === clearTimeout) return clearTimeout(e3);
          if ((n === s || !n) && clearTimeout) return n = clearTimeout, clearTimeout(e3);
          try {
            n(e3);
          } catch (r3) {
            try {
              return n.call(null, e3);
            } catch (r4) {
              return n.call(this, e3);
            }
          }
        }(e2);
      }
    }
    function v(e2, r2) {
      this.fun = e2, this.array = r2;
    }
    function m() {
    }
    o.nextTick = function(e2) {
      var r2 = new Array(arguments.length - 1);
      if (arguments.length > 1) for (var t2 = 1; t2 < arguments.length; t2++) r2[t2 - 1] = arguments[t2];
      c.push(new v(e2, r2)), 1 !== c.length || p || a(h);
    }, v.prototype.run = function() {
      this.fun.apply(null, this.array);
    }, o.title = "browser", o.browser = true, o.env = {}, o.argv = [], o.version = "", o.versions = {}, o.on = m, o.addListener = m, o.once = m, o.off = m, o.removeListener = m, o.removeAllListeners = m, o.emit = m, o.prependListener = m, o.prependOnceListener = m, o.listeners = function(e2) {
      return [];
    }, o.binding = function(e2) {
      throw new Error("process.binding is not supported");
    }, o.cwd = function() {
      return "/";
    }, o.chdir = function(e2) {
      throw new Error("process.chdir is not supported");
    }, o.umask = function() {
      return 0;
    };
  }]);
});
var SEMVER_SPEC_VERSION = module.exports.SEMVER_SPEC_VERSION;
var parse = module.exports.parse;
var valid = module.exports.valid;
var coerce = module.exports.coerce;
var clean2 = module.exports.clean;
var inc = module.exports.inc;
var major = module.exports.major;
var minor = module.exports.minor;
var patch = module.exports.patch;
var prerelease = module.exports.prerelease;
var gt = module.exports.gt;
var gte = module.exports.gte;
var lt = module.exports.lt;
var lte = module.exports.lte;
var eq = module.exports.eq;
var neq = module.exports.neq;
var cmp3 = module.exports.cmp;
var compare2 = module.exports.compare;
var rcompare = module.exports.rcompare;
var compareIdentifiers = module.exports.compareIdentifiers;
var rcompareIdentifiers = module.exports.rcompareIdentifiers;
var compareBuild = module.exports.compareBuild;
var sort = module.exports.sort;
var rsort = module.exports.rsort;
var diff = module.exports.diff;
var validRange = module.exports.validRange;
var satisfies = module.exports.satisfies;
var maxSatisfying = module.exports.maxSatisfying;
var minSatisfying = module.exports.minSatisfying;
var minVersion = module.exports.minVersion;
var gtr = module.exports.gtr;
var ltr = module.exports.ltr;
var outside = module.exports.outside;
var intersects = module.exports.intersects;
var SemVer = module.exports.SemVer;
var Comparator = module.exports.Comparator;
var Range2 = module.exports.Range;

// out-build/vs/platform/extensions/common/extensionValidator.js
var VERSION_REGEXP = /^(\^|>=)?((\d+)|x)\.((\d+)|x)\.((\d+)|x)(\-.*)?$/;
var NOT_BEFORE_REGEXP = /^-(\d{4})(\d{2})(\d{2})$/;
function $UA(version) {
  version = version.trim();
  return version === "*" || VERSION_REGEXP.test(version);
}
function $VA(version) {
  if (!$UA(version)) {
    return null;
  }
  version = version.trim();
  if (version === "*") {
    return {
      hasCaret: false,
      hasGreaterEquals: false,
      majorBase: 0,
      majorMustEqual: false,
      minorBase: 0,
      minorMustEqual: false,
      patchBase: 0,
      patchMustEqual: false,
      preRelease: null
    };
  }
  const m = version.match(VERSION_REGEXP);
  if (!m) {
    return null;
  }
  return {
    hasCaret: m[1] === "^",
    hasGreaterEquals: m[1] === ">=",
    majorBase: m[2] === "x" ? 0 : parseInt(m[2], 10),
    majorMustEqual: m[2] === "x" ? false : true,
    minorBase: m[4] === "x" ? 0 : parseInt(m[4], 10),
    minorMustEqual: m[4] === "x" ? false : true,
    patchBase: m[6] === "x" ? 0 : parseInt(m[6], 10),
    patchMustEqual: m[6] === "x" ? false : true,
    preRelease: m[8] || null
  };
}
function $WA(version) {
  if (!version) {
    return null;
  }
  const majorBase = version.majorBase;
  const majorMustEqual = version.majorMustEqual;
  const minorBase = version.minorBase;
  let minorMustEqual = version.minorMustEqual;
  const patchBase = version.patchBase;
  let patchMustEqual = version.patchMustEqual;
  if (version.hasCaret) {
    if (majorBase === 0) {
      patchMustEqual = false;
    } else {
      minorMustEqual = false;
      patchMustEqual = false;
    }
  }
  let notBefore = 0;
  if (version.preRelease) {
    const match = NOT_BEFORE_REGEXP.exec(version.preRelease);
    if (match) {
      const [, year2, month2, day2] = match;
      notBefore = Date.UTC(Number(year2), Number(month2) - 1, Number(day2));
    }
  }
  return {
    majorBase,
    majorMustEqual,
    minorBase,
    minorMustEqual,
    patchBase,
    patchMustEqual,
    isMinimum: version.hasGreaterEquals,
    notBefore
  };
}

// out-build/vs/workbench/api/common/extHostWebviewMessaging.js
var ArrayBufferSet = class {
  constructor() {
    this.buffers = [];
  }
  add(buffer) {
    let index = this.buffers.indexOf(buffer);
    if (index < 0) {
      index = this.buffers.length;
      this.buffers.push(buffer);
    }
    return index;
  }
};
function $kOb(message, options2) {
  if (options2.serializeBuffersForPostMessage) {
    const arrayBuffers = new ArrayBufferSet();
    const replacer2 = (_key, value) => {
      if (value instanceof ArrayBuffer) {
        const index = arrayBuffers.add(value);
        return {
          $$vscode_array_buffer_reference$$: true,
          index
        };
      } else if (ArrayBuffer.isView(value)) {
        const type = getTypedArrayType(value);
        if (type) {
          const index = arrayBuffers.add(value.buffer);
          return {
            $$vscode_array_buffer_reference$$: true,
            index,
            view: {
              type,
              byteLength: value.byteLength,
              byteOffset: value.byteOffset
            }
          };
        }
      }
      return value;
    };
    const serializedMessage = JSON.stringify(message, replacer2);
    const buffers = arrayBuffers.buffers.map((arrayBuffer) => {
      const bytes = new Uint8Array(arrayBuffer);
      return $Ci.wrap(bytes);
    });
    return { message: serializedMessage, buffers };
  } else {
    return { message: JSON.stringify(message), buffers: [] };
  }
}
function getTypedArrayType(value) {
  switch (value.constructor.name) {
    case "Int8Array":
      return 1;
    case "Uint8Array":
      return 2;
    case "Uint8ClampedArray":
      return 3;
    case "Int16Array":
      return 4;
    case "Uint16Array":
      return 5;
    case "Int32Array":
      return 6;
    case "Uint32Array":
      return 7;
    case "Float32Array":
      return 8;
    case "Float64Array":
      return 9;
    case "BigInt64Array":
      return 10;
    case "BigUint64Array":
      return 11;
  }
  return void 0;
}
function $lOb(jsonMessage, buffers) {
  const arrayBuffers = buffers.map((buffer) => {
    const arrayBuffer = new ArrayBuffer(buffer.byteLength);
    const uint8Array = new Uint8Array(arrayBuffer);
    uint8Array.set(buffer.buffer);
    return arrayBuffer;
  });
  const reviver = !buffers.length ? void 0 : (_key, value) => {
    if (value && typeof value === "object" && value.$$vscode_array_buffer_reference$$) {
      const ref = value;
      const { index } = ref;
      const arrayBuffer = arrayBuffers[index];
      if (ref.view) {
        switch (ref.view.type) {
          case 1:
            return new Int8Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Int8Array.BYTES_PER_ELEMENT);
          case 2:
            return new Uint8Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Uint8Array.BYTES_PER_ELEMENT);
          case 3:
            return new Uint8ClampedArray(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Uint8ClampedArray.BYTES_PER_ELEMENT);
          case 4:
            return new Int16Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Int16Array.BYTES_PER_ELEMENT);
          case 5:
            return new Uint16Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Uint16Array.BYTES_PER_ELEMENT);
          case 6:
            return new Int32Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Int32Array.BYTES_PER_ELEMENT);
          case 7:
            return new Uint32Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Uint32Array.BYTES_PER_ELEMENT);
          case 8:
            return new Float32Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Float32Array.BYTES_PER_ELEMENT);
          case 9:
            return new Float64Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Float64Array.BYTES_PER_ELEMENT);
          case 10:
            return new BigInt64Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / BigInt64Array.BYTES_PER_ELEMENT);
          case 11:
            return new BigUint64Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / BigUint64Array.BYTES_PER_ELEMENT);
          default:
            throw new Error("Unknown array buffer view type");
        }
      }
      return arrayBuffer;
    }
    return value;
  };
  const message = JSON.parse(jsonMessage, reviver);
  return { message, arrayBuffers };
}

// out-build/vs/workbench/api/common/extHostWebview.js
var $fxc = class {
  #handle;
  #proxy;
  #deprecationService;
  #remoteInfo;
  #workspace;
  #extension;
  #html;
  #options;
  #isDisposed;
  #hasCalledAsWebviewUri;
  #serializeBuffersForPostMessage;
  #shouldRewriteOldResourceUris;
  constructor(handle, proxy, options2, remoteInfo, workspace, extension, deprecationService) {
    this.#html = "";
    this.#isDisposed = false;
    this.#hasCalledAsWebviewUri = false;
    this._onMessageEmitter = new $ze();
    this.onDidReceiveMessage = this._onMessageEmitter.event;
    this.#onDidDisposeEmitter = new $ze();
    this._onDidDispose = this.#onDidDisposeEmitter.event;
    this.#handle = handle;
    this.#proxy = proxy;
    this.#options = options2;
    this.#remoteInfo = remoteInfo;
    this.#workspace = workspace;
    this.#extension = extension;
    this.#serializeBuffersForPostMessage = $gxc(extension);
    this.#shouldRewriteOldResourceUris = shouldTryRewritingOldResourceUris(extension);
    this.#deprecationService = deprecationService;
  }
  #onDidDisposeEmitter;
  dispose() {
    this.#isDisposed = true;
    this.#onDidDisposeEmitter.fire();
    this.#onDidDisposeEmitter.dispose();
    this._onMessageEmitter.dispose();
  }
  asWebviewUri(resource) {
    this.#hasCalledAsWebviewUri = true;
    return $HJb(resource, this.#remoteInfo);
  }
  get cspSource() {
    const extensionLocation = this.#extension.extensionLocation;
    if (extensionLocation.scheme === Schemas.https || extensionLocation.scheme === Schemas.http) {
      let extensionCspRule = extensionLocation.toString();
      if (!extensionCspRule.endsWith("/")) {
        extensionCspRule += "/";
      }
      return extensionCspRule + " " + $GJb;
    }
    return $GJb;
  }
  get html() {
    this.a();
    return this.#html;
  }
  set html(value) {
    this.a();
    if (this.#html !== value) {
      this.#html = value;
      if (this.#shouldRewriteOldResourceUris && !this.#hasCalledAsWebviewUri && /(["'])vscode-resource:([^\s'"]+?)(["'])/i.test(value)) {
        this.#hasCalledAsWebviewUri = true;
        this.#deprecationService.report("Webview vscode-resource: uris", this.#extension, `Please migrate to use the 'webview.asWebviewUri' api instead: https://aka.ms/vscode-webview-use-aswebviewuri`);
      }
      this.#proxy.$setHtml(this.#handle, this.b(value));
    }
  }
  get options() {
    this.a();
    return this.#options;
  }
  set options(newOptions) {
    this.a();
    if (!$Pv(this.#options, newOptions)) {
      this.#proxy.$setOptions(this.#handle, $jxc(this.#extension, this.#workspace, newOptions));
    }
    this.#options = newOptions;
  }
  async postMessage(message) {
    if (this.#isDisposed) {
      return false;
    }
    const serialized = $kOb(message, { serializeBuffersForPostMessage: this.#serializeBuffersForPostMessage });
    return this.#proxy.$postMessage(this.#handle, serialized.message, ...serialized.buffers);
  }
  a() {
    if (this.#isDisposed) {
      throw new Error("Webview is disposed");
    }
  }
  b(value) {
    if (!this.#shouldRewriteOldResourceUris) {
      return value;
    }
    const isRemote = this.#extension.extensionLocation?.scheme === Schemas.vscodeRemote;
    const remoteAuthority = this.#extension.extensionLocation.scheme === Schemas.vscodeRemote ? this.#extension.extensionLocation.authority : void 0;
    return value.replace(/(["'])(?:vscode-resource):(\/\/([^\s\/'"]+?)(?=\/))?([^\s'"]+?)(["'])/gi, (_match, startQuote, _1, scheme, path, endQuote) => {
      const uri = URI.from({
        scheme: scheme || "file",
        path: decodeURIComponent(path)
      });
      const webviewUri = $HJb(uri, { isRemote, authority: remoteAuthority }).toString();
      return `${startQuote}${webviewUri}${endQuote}`;
    }).replace(/(["'])(?:vscode-webview-resource):(\/\/[^\s\/'"]+\/([^\s\/'"]+?)(?=\/))?([^\s'"]+?)(["'])/gi, (_match, startQuote, _1, scheme, path, endQuote) => {
      const uri = URI.from({
        scheme: scheme || "file",
        path: decodeURIComponent(path)
      });
      const webviewUri = $HJb(uri, { isRemote, authority: remoteAuthority }).toString();
      return `${startQuote}${webviewUri}${endQuote}`;
    });
  }
};
function $gxc(extension) {
  try {
    const version = $WA($VA(extension.engines.vscode));
    return !!version && version.majorBase >= 1 && version.minorBase >= 57;
  } catch {
    return false;
  }
}
function shouldTryRewritingOldResourceUris(extension) {
  try {
    const version = $WA($VA(extension.engines.vscode));
    if (!version) {
      return false;
    }
    return version.majorBase < 1 || version.majorBase === 1 && version.minorBase < 60;
  } catch {
    return false;
  }
}
var $hxc = class extends $3c {
  constructor(mainContext, c, f, g, h) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h;
    this.b = /* @__PURE__ */ new Map();
    this.a = mainContext.getProxy($xT.MainThreadWebviews);
  }
  dispose() {
    super.dispose();
    for (const webview of this.b.values()) {
      webview.dispose();
    }
    this.b.clear();
  }
  $onMessage(handle, jsonMessage, buffers) {
    const webview = this.j(handle);
    if (webview) {
      const { message } = $lOb(jsonMessage, buffers.value);
      webview._onMessageEmitter.fire(message);
    }
  }
  $onMissingCsp(_handle, extensionId) {
    this.g.warn(`${extensionId} created a webview without a content security policy: https://aka.ms/vscode-webview-missing-csp`);
  }
  createNewWebview(handle, options2, extension) {
    const webview = new $fxc(handle, this.a, reviveOptions(options2), this.c, this.f, extension, this.h);
    this.b.set(handle, webview);
    const sub = webview._onDidDispose(() => {
      sub.dispose();
      this.deleteWebview(handle);
    });
    return webview;
  }
  deleteWebview(handle) {
    this.b.delete(handle);
  }
  j(handle) {
    return this.b.get(handle);
  }
};
function $ixc(extension) {
  return { id: extension.identifier, location: extension.extensionLocation };
}
function $jxc(extension, workspace, options2) {
  return {
    enableCommandUris: options2.enableCommandUris,
    enableScripts: options2.enableScripts,
    enableForms: options2.enableForms,
    portMapping: options2.portMapping,
    localResourceRoots: options2.localResourceRoots || getDefaultLocalResourceRoots(extension, workspace)
  };
}
function reviveOptions(options2) {
  return {
    enableCommandUris: options2.enableCommandUris,
    enableScripts: options2.enableScripts,
    enableForms: options2.enableForms,
    portMapping: options2.portMapping,
    localResourceRoots: options2.localResourceRoots?.map((components) => URI.from(components))
  };
}
function getDefaultLocalResourceRoots(extension, workspace) {
  return [
    ...(workspace?.getWorkspaceFolders() || []).map((x) => x.uri),
    extension.extensionLocation
  ];
}

// out-build/vs/workbench/api/common/cache.js
var $Jwc = class _$Jwc {
  static {
    this.a = false;
  }
  constructor(d) {
    this.d = d;
    this.b = /* @__PURE__ */ new Map();
    this.c = 1;
  }
  add(item) {
    const id2 = this.c++;
    this.b.set(id2, item);
    this.e();
    return id2;
  }
  get(pid, id2) {
    return this.b.has(pid) ? this.b.get(pid)[id2] : void 0;
  }
  delete(id2) {
    this.b.delete(id2);
    this.e();
  }
  e() {
    if (!_$Jwc.a) {
      return;
    }
    console.log(`${this.d} cache size - ${this.b.size}`);
  }
};

// out-build/vs/workbench/api/common/extHostCustomEditors.js
var CustomDocumentStoreEntry = class {
  constructor(document2, b) {
    this.document = document2;
    this.b = b;
    this.a = 1;
    this.c = new $Jwc("custom documents");
  }
  addEdit(item) {
    return this.c.add([item]);
  }
  async undo(editId, isDirty) {
    await this.f(editId).undo();
    if (!isDirty) {
      this.disposeBackup();
    }
  }
  async redo(editId, isDirty) {
    await this.f(editId).redo();
    if (!isDirty) {
      this.disposeBackup();
    }
  }
  disposeEdits(editIds) {
    for (const id2 of editIds) {
      this.c.delete(id2);
    }
  }
  getNewBackupUri() {
    if (!this.b) {
      throw new Error("Backup requires a valid storage path");
    }
    const fileName = hashPath(this.document.uri) + this.a++;
    return $vh(this.b, fileName);
  }
  updateBackup(backup) {
    this.d?.delete();
    this.d = backup;
  }
  disposeBackup() {
    this.d?.delete();
    this.d = void 0;
  }
  f(editId) {
    const edit2 = this.c.get(editId, 0);
    if (!edit2) {
      throw new Error("No edit found");
    }
    return edit2;
  }
};
var CustomDocumentStore = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  get(viewType, resource) {
    return this.a.get(this.b(viewType, resource));
  }
  add(viewType, document2, storagePath) {
    const key = this.b(viewType, document2.uri);
    if (this.a.has(key)) {
      throw new Error(`Document already exists for viewType:${viewType} resource:${document2.uri}`);
    }
    const entry = new CustomDocumentStoreEntry(document2, storagePath);
    this.a.set(key, entry);
    return entry;
  }
  delete(viewType, document2) {
    const key = this.b(viewType, document2.uri);
    this.a.delete(key);
  }
  b(viewType, resource) {
    return `${viewType}@@@${resource}`;
  }
};
var CustomEditorType;
(function(CustomEditorType2) {
  CustomEditorType2[CustomEditorType2["Text"] = 0] = "Text";
  CustomEditorType2[CustomEditorType2["Custom"] = 1] = "Custom";
})(CustomEditorType || (CustomEditorType = {}));
var EditorProviderStore = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  addTextProvider(viewType, extension, provider) {
    return this.b(viewType, { type: 0, extension, provider });
  }
  addCustomProvider(viewType, extension, provider) {
    return this.b(viewType, { type: 1, extension, provider });
  }
  get(viewType) {
    return this.a.get(viewType);
  }
  b(viewType, entry) {
    if (this.a.has(viewType)) {
      throw new Error(`Provider for viewType:${viewType} already registered`);
    }
    this.a.set(viewType, entry);
    return new $zT(() => this.a.delete(viewType));
  }
};
var $lxc = class {
  constructor(mainContext, d, f, g, h) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h;
    this.b = new EditorProviderStore();
    this.c = new CustomDocumentStore();
    this.a = mainContext.getProxy($xT.MainThreadCustomEditors);
  }
  registerCustomEditorProvider(extension, viewType, provider, options2) {
    const disposables = new $2c();
    if (isCustomTextEditorProvider(provider)) {
      disposables.add(this.b.addTextProvider(viewType, extension, provider));
      this.a.$registerTextEditorProvider($ixc(extension), viewType, options2.webviewOptions || {}, {
        supportsMove: !!provider.moveCustomTextEditor
      }, $gxc(extension));
    } else {
      disposables.add(this.b.addCustomProvider(viewType, extension, provider));
      if (isCustomEditorProviderWithEditingCapability(provider)) {
        disposables.add(provider.onDidChangeCustomDocument((e) => {
          const entry = this.i(viewType, e.document.uri);
          if (isEditEvent(e)) {
            const editId = entry.addEdit(e);
            this.a.$onDidEdit(e.document.uri, viewType, editId, e.label);
          } else {
            this.a.$onContentChange(e.document.uri, viewType);
          }
        }));
      }
      this.a.$registerCustomEditorProvider($ixc(extension), viewType, options2.webviewOptions || {}, !!options2.supportsMultipleEditorsPerDocument, $gxc(extension));
    }
    return $zT.from(disposables, new $zT(() => {
      this.a.$unregisterEditorProvider(viewType);
    }));
  }
  async $createCustomDocument(resource, viewType, backupId, untitledDocumentData, cancellation) {
    const entry = this.b.get(viewType);
    if (!entry) {
      throw new Error(`No provider found for '${viewType}'`);
    }
    if (entry.type !== 1) {
      throw new Error(`Invalid provide type for '${viewType}'`);
    }
    const revivedResource = URI.revive(resource);
    const document2 = await entry.provider.openCustomDocument(revivedResource, { backupId, untitledDocumentData: untitledDocumentData?.buffer }, cancellation);
    let storageRoot;
    if (isCustomEditorProviderWithEditingCapability(entry.provider) && this.f) {
      storageRoot = this.f.workspaceValue(entry.extension) ?? this.f.globalValue(entry.extension);
    }
    this.c.add(viewType, document2, storageRoot);
    return { editable: isCustomEditorProviderWithEditingCapability(entry.provider) };
  }
  async $disposeCustomDocument(resource, viewType) {
    const entry = this.b.get(viewType);
    if (!entry) {
      throw new Error(`No provider found for '${viewType}'`);
    }
    if (entry.type !== 1) {
      throw new Error(`Invalid provider type for '${viewType}'`);
    }
    const revivedResource = URI.revive(resource);
    const { document: document2 } = this.i(viewType, revivedResource);
    this.c.delete(viewType, document2);
    document2.dispose();
  }
  async $resolveCustomEditor(resource, handle, viewType, initData, position, cancellation) {
    const entry = this.b.get(viewType);
    if (!entry) {
      throw new Error(`No provider found for '${viewType}'`);
    }
    const viewColumn = ViewColumn2.to(position);
    const webview = this.g.createNewWebview(handle, initData.contentOptions, entry.extension);
    const panel = this.h.createNewWebviewPanel(handle, viewType, initData.title, viewColumn, initData.options, webview, initData.active);
    const revivedResource = URI.revive(resource);
    switch (entry.type) {
      case 1: {
        const { document: document2 } = this.i(viewType, revivedResource);
        return entry.provider.resolveCustomEditor(document2, panel, cancellation);
      }
      case 0: {
        const document2 = this.d.getDocument(revivedResource);
        return entry.provider.resolveCustomTextEditor(document2, panel, cancellation);
      }
      default: {
        throw new Error("Unknown webview provider type");
      }
    }
  }
  $disposeEdits(resourceComponents, viewType, editIds) {
    const document2 = this.i(viewType, resourceComponents);
    document2.disposeEdits(editIds);
  }
  async $onMoveCustomEditor(handle, newResourceComponents, viewType) {
    const entry = this.b.get(viewType);
    if (!entry) {
      throw new Error(`No provider found for '${viewType}'`);
    }
    if (!entry.provider.moveCustomTextEditor) {
      throw new Error(`Provider does not implement move '${viewType}'`);
    }
    const webview = this.h.getWebviewPanel(handle);
    if (!webview) {
      throw new Error(`No webview found`);
    }
    const resource = URI.revive(newResourceComponents);
    const document2 = this.d.getDocument(resource);
    await entry.provider.moveCustomTextEditor(document2, webview, CancellationToken.None);
  }
  async $undo(resourceComponents, viewType, editId, isDirty) {
    const entry = this.i(viewType, resourceComponents);
    return entry.undo(editId, isDirty);
  }
  async $redo(resourceComponents, viewType, editId, isDirty) {
    const entry = this.i(viewType, resourceComponents);
    return entry.redo(editId, isDirty);
  }
  async $revert(resourceComponents, viewType, cancellation) {
    const entry = this.i(viewType, resourceComponents);
    const provider = this.j(viewType);
    await provider.revertCustomDocument(entry.document, cancellation);
    entry.disposeBackup();
  }
  async $onSave(resourceComponents, viewType, cancellation) {
    const entry = this.i(viewType, resourceComponents);
    const provider = this.j(viewType);
    await provider.saveCustomDocument(entry.document, cancellation);
    entry.disposeBackup();
  }
  async $onSaveAs(resourceComponents, viewType, targetResource, cancellation) {
    const entry = this.i(viewType, resourceComponents);
    const provider = this.j(viewType);
    return provider.saveCustomDocumentAs(entry.document, URI.revive(targetResource), cancellation);
  }
  async $backup(resourceComponents, viewType, cancellation) {
    const entry = this.i(viewType, resourceComponents);
    const provider = this.j(viewType);
    const backup = await provider.backupCustomDocument(entry.document, {
      destination: entry.getNewBackupUri()
    }, cancellation);
    entry.updateBackup(backup);
    return backup.id;
  }
  i(viewType, resource) {
    const entry = this.c.get(viewType, URI.revive(resource));
    if (!entry) {
      throw new Error("No custom document found");
    }
    return entry;
  }
  j(viewType) {
    const entry = this.b.get(viewType);
    const provider = entry?.provider;
    if (!provider || !isCustomEditorProviderWithEditingCapability(provider)) {
      throw new Error("Custom document is not editable");
    }
    return provider;
  }
};
function isCustomEditorProviderWithEditingCapability(provider) {
  return !!provider.onDidChangeCustomDocument;
}
function isCustomTextEditorProvider(provider) {
  return typeof provider.resolveCustomTextEditor === "function";
}
function isEditEvent(e) {
  return typeof e.undo === "function" && typeof e.redo === "function";
}
function hashPath(resource) {
  const str = resource.scheme === Schemas.file || resource.scheme === Schemas.untitled ? resource.fsPath : resource.toString();
  return $Xi(str) + "";
}

// out-build/vs/workbench/api/common/extHostDiagnostics.js
var $Rwc_1;
var $Qwc = class _$Qwc {
  #proxy;
  #onDidChangeDiagnostics;
  #data;
  constructor(d, e, f, g, h, extUri, proxy, onDidChangeDiagnostics) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h;
    this.c = false;
    this.f = Math.max(g, f);
    this.#data = new $Ec((uri) => extUri.getComparisonKey(uri));
    this.#proxy = proxy;
    this.#onDidChangeDiagnostics = onDidChangeDiagnostics;
  }
  dispose() {
    if (!this.c) {
      this.#onDidChangeDiagnostics.fire([...this.#data.keys()]);
      this.#proxy?.$clear(this.e);
      this.#data.clear();
      this.c = true;
    }
  }
  get name() {
    this.j();
    return this.d;
  }
  set(first, diagnostics) {
    if (!first) {
      this.clear();
      return;
    }
    this.j();
    let toSync = [];
    if (URI.isUri(first)) {
      if (!diagnostics) {
        this.delete(first);
        return;
      }
      this.#data.set(first, diagnostics.slice());
      toSync = [first];
    } else if (Array.isArray(first)) {
      toSync = [];
      let lastUri;
      first = [...first].sort(_$Qwc.k);
      for (const tuple of first) {
        const [uri, diagnostics2] = tuple;
        if (!lastUri || uri.toString() !== lastUri.toString()) {
          if (lastUri && this.#data.get(lastUri).length === 0) {
            this.#data.delete(lastUri);
          }
          lastUri = uri;
          toSync.push(uri);
          this.#data.set(uri, []);
        }
        if (!diagnostics2) {
          const currentDiagnostics = this.#data.get(uri);
          if (currentDiagnostics) {
            currentDiagnostics.length = 0;
          }
        } else {
          const currentDiagnostics = this.#data.get(uri);
          currentDiagnostics?.push(...diagnostics2);
        }
      }
    }
    this.#onDidChangeDiagnostics.fire(toSync);
    if (!this.#proxy) {
      return;
    }
    const entries = [];
    let totalMarkerCount = 0;
    for (const uri of toSync) {
      let marker = [];
      const diagnostics2 = this.#data.get(uri);
      if (diagnostics2) {
        if (diagnostics2.length > this.g) {
          marker = [];
          const order = [DiagnosticSeverity.Error, DiagnosticSeverity.Warning, DiagnosticSeverity.Information, DiagnosticSeverity.Hint];
          orderLoop: for (let i = 0; i < 4; i++) {
            for (const diagnostic of diagnostics2) {
              if (diagnostic.severity === order[i]) {
                const len = marker.push({ ...Diagnostic.from(diagnostic), modelVersionId: this.h(uri) });
                if (len === this.g) {
                  break orderLoop;
                }
              }
            }
          }
          marker.push({
            severity: MarkerSeverity.Info,
            message: localize(2754, null, diagnostics2.length - this.g),
            startLineNumber: marker[marker.length - 1].startLineNumber,
            startColumn: marker[marker.length - 1].startColumn,
            endLineNumber: marker[marker.length - 1].endLineNumber,
            endColumn: marker[marker.length - 1].endColumn
          });
        } else {
          marker = diagnostics2.map((diag) => ({ ...Diagnostic.from(diag), modelVersionId: this.h(uri) }));
        }
      }
      entries.push([uri, marker]);
      totalMarkerCount += marker.length;
      if (totalMarkerCount > this.f) {
        break;
      }
    }
    this.#proxy.$changeMany(this.e, entries);
  }
  delete(uri) {
    this.j();
    this.#onDidChangeDiagnostics.fire([uri]);
    this.#data.delete(uri);
    this.#proxy?.$changeMany(this.e, [[uri, void 0]]);
  }
  clear() {
    this.j();
    this.#onDidChangeDiagnostics.fire([...this.#data.keys()]);
    this.#data.clear();
    this.#proxy?.$clear(this.e);
  }
  forEach(callback, thisArg) {
    this.j();
    for (const [uri, values] of this) {
      callback.call(thisArg, uri, values, this);
    }
  }
  *[Symbol.iterator]() {
    this.j();
    for (const uri of this.#data.keys()) {
      yield [uri, this.get(uri)];
    }
  }
  get(uri) {
    this.j();
    const result = this.#data.get(uri);
    if (Array.isArray(result)) {
      return Object.freeze(result.slice(0));
    }
    return [];
  }
  has(uri) {
    this.j();
    return Array.isArray(this.#data.get(uri));
  }
  j() {
    if (this.c) {
      throw new Error("illegal state - object is disposed");
    }
  }
  static k(a, b) {
    if (a[0].toString() < b[0].toString()) {
      return -1;
    } else if (a[0].toString() > b[0].toString()) {
      return 1;
    } else {
      return 0;
    }
  }
};
var $Rwc = class $Rwc2 {
  static {
    $Rwc_1 = this;
  }
  static {
    this.c = 0;
  }
  static {
    this.d = 1e3;
  }
  static {
    this.e = 1.1 * this.d;
  }
  static _mapper(last) {
    const map = new $Ec();
    for (const uri of last) {
      map.set(uri, uri);
    }
    return { uris: Object.freeze(Array.from(map.values())) };
  }
  constructor(mainContext, j, k, l) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.g = /* @__PURE__ */ new Map();
    this.h = new $De({ merge: (all) => all.flat(), delay: 50 });
    this.onDidChangeDiagnostics = Event.map(this.h.event, $Rwc_1._mapper);
    this.f = mainContext.getProxy($xT.MainThreadDiagnostics);
  }
  createDiagnosticCollection(extensionId, name) {
    const { g: _collections, f: _proxy, h: _onDidChangeDiagnostics, j: _logService, k: _fileSystemInfoService, l: _extHostDocumentsAndEditors } = this;
    const loggingProxy = new class {
      $changeMany(owner2, entries) {
        _proxy.$changeMany(owner2, entries);
        _logService.trace("[DiagnosticCollection] change many (extension, owner, uris)", extensionId.value, owner2, entries.length === 0 ? "CLEARING" : entries);
      }
      $clear(owner2) {
        _proxy.$clear(owner2);
        _logService.trace("[DiagnosticCollection] remove all (extension, owner)", extensionId.value, owner2);
      }
      dispose() {
        _proxy.dispose();
      }
    }();
    let owner;
    if (!name) {
      name = "_generated_diagnostic_collection_name_#" + $Rwc_1.c++;
      owner = name;
    } else if (!_collections.has(name)) {
      owner = name;
    } else {
      this.j.warn(`DiagnosticCollection with name '${name}' does already exist.`);
      do {
        owner = name + $Rwc_1.c++;
      } while (_collections.has(owner));
    }
    const result = new class extends $Qwc {
      constructor() {
        super(name, owner, $Rwc_1.e, $Rwc_1.d, (uri) => _extHostDocumentsAndEditors.getDocument(uri)?.version, _fileSystemInfoService.extUri, loggingProxy, _onDidChangeDiagnostics);
        _collections.set(owner, this);
      }
      dispose() {
        super.dispose();
        _collections.delete(owner);
      }
    }();
    return result;
  }
  getDiagnostics(resource) {
    if (resource) {
      return this.m(resource);
    } else {
      const index = /* @__PURE__ */ new Map();
      const res = [];
      for (const collection of this.g.values()) {
        collection.forEach((uri, diagnostics) => {
          let idx = index.get(uri.toString());
          if (typeof idx === "undefined") {
            idx = res.length;
            index.set(uri.toString(), idx);
            res.push([uri, []]);
          }
          res[idx][1] = res[idx][1].concat(...diagnostics);
        });
      }
      return res;
    }
  }
  m(resource) {
    let res = [];
    for (const collection of this.g.values()) {
      if (collection.has(resource)) {
        res = res.concat(collection.get(resource));
      }
    }
    return res;
  }
  $acceptMarkersChange(data) {
    if (!this.n) {
      const name = "_generated_mirror";
      const collection = new $Qwc(
        name,
        name,
        Number.MAX_SAFE_INTEGER,
        Number.MAX_SAFE_INTEGER,
        // no limits because this collection is just a mirror of "sanitized" data
        // no limits because this collection is just a mirror of "sanitized" data
        (_uri) => void 0,
        this.k.extUri,
        void 0,
        this.h
      );
      this.g.set(name, collection);
      this.n = collection;
    }
    for (const [uri, markers] of data) {
      this.n.set(URI.revive(uri), markers.map(Diagnostic.to));
    }
  }
};
$Rwc = $Rwc_1 = __decorate([
  __param(1, $wn),
  __param(2, $Pwc)
], $Rwc);

// out-build/vs/workbench/api/common/extHostDialogs.js
var $3xc = class {
  constructor(mainContext) {
    this.a = mainContext.getProxy($xT.MainThreadDialogs);
  }
  showOpenDialog(extension, options2) {
    if (options2?.allowUIResources) {
      $AN(extension, "showLocal");
    }
    return this.a.$showOpenDialog(options2).then((filepaths) => {
      return filepaths ? filepaths.map((p) => URI.revive(p)) : void 0;
    });
  }
  showSaveDialog(options2) {
    return this.a.$showSaveDialog(options2).then((filepath) => {
      return filepath ? URI.revive(filepath) : void 0;
    });
  }
};

// out-build/vs/workbench/api/common/extHostDocumentContentProviders.js
var $4xc = class _$4xc {
  static {
    this.a = 0;
  }
  constructor(mainContext, d, e) {
    this.d = d;
    this.e = e;
    this.b = /* @__PURE__ */ new Map();
    this.c = mainContext.getProxy($xT.MainThreadDocumentContentProviders);
  }
  registerTextDocumentContentProvider(scheme, provider) {
    if (Object.keys(Schemas).indexOf(scheme) >= 0) {
      throw new Error(`scheme '${scheme}' already registered`);
    }
    const handle = _$4xc.a++;
    this.b.set(handle, provider);
    this.c.$registerTextContentProvider(handle, scheme);
    let subscription;
    if (typeof provider.onDidChange === "function") {
      let lastEvent;
      subscription = provider.onDidChange(async (uri) => {
        if (uri.scheme !== scheme) {
          this.e.warn(`Provider for scheme '${scheme}' is firing event for schema '${uri.scheme}' which will be IGNORED`);
          return;
        }
        if (!this.d.getDocument(uri)) {
          return;
        }
        if (lastEvent) {
          await lastEvent;
        }
        const thisEvent = this.$provideTextDocumentContent(handle, uri).then(async (value) => {
          if (!value && typeof value !== "string") {
            return;
          }
          const document2 = this.d.getDocument(uri);
          if (!document2) {
            return;
          }
          const lines = $Mf(value);
          if (!document2.equalLines(lines)) {
            return this.c.$onVirtualDocumentChange(uri, value);
          }
        }).catch($gb).finally(() => {
          if (lastEvent === thisEvent) {
            lastEvent = void 0;
          }
        });
        lastEvent = thisEvent;
      });
    }
    return new $zT(() => {
      if (this.b.delete(handle)) {
        this.c.$unregisterTextContentProvider(handle);
      }
      if (subscription) {
        subscription.dispose();
        subscription = void 0;
      }
    });
  }
  $provideTextDocumentContent(handle, uri) {
    const provider = this.b.get(handle);
    if (!provider) {
      return Promise.reject(new Error(`unsupported uri-scheme: ${uri.scheme}`));
    }
    return Promise.resolve(provider.provideTextDocumentContent(URI.revive(uri), CancellationToken.None));
  }
};

// out-build/vs/workbench/api/common/extHostDocumentSaveParticipant.js
var $5xc = class {
  constructor(c, d, f, g = { timeout: 1500, errors: 3 }) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.a = new $cd();
    this.b = /* @__PURE__ */ new WeakMap();
  }
  dispose() {
    this.a.clear();
  }
  getOnWillSaveTextDocumentEvent(extension) {
    return (listener, thisArg, disposables) => {
      const remove = this.a.push([listener, thisArg, extension]);
      const result = { dispose: remove };
      if (Array.isArray(disposables)) {
        disposables.push(result);
      }
      return result;
    };
  }
  async $participateInSave(data, reason) {
    const resource = URI.revive(data);
    let didTimeout = false;
    const didTimeoutHandle = setTimeout(() => didTimeout = true, this.g.timeout);
    const results = [];
    try {
      for (const listener of [...this.a]) {
        if (didTimeout) {
          break;
        }
        const document2 = this.d.getDocument(resource);
        const success = await this.h(listener, { document: document2, reason: TextDocumentSaveReason2.to(reason) });
        results.push(success);
      }
    } finally {
      clearTimeout(didTimeoutHandle);
    }
    return results;
  }
  h([listener, thisArg, extension], stubEvent) {
    const errors = this.b.get(listener);
    if (typeof errors === "number" && errors > this.g.errors) {
      return Promise.resolve(false);
    }
    return this.i(extension, listener, thisArg, stubEvent).then(() => {
      return true;
    }, (err) => {
      this.c.error(`onWillSaveTextDocument-listener from extension '${extension.identifier.value}' threw ERROR`);
      this.c.error(err);
      if (!(err instanceof Error) || err.message !== "concurrent_edits") {
        const errors2 = this.b.get(listener);
        this.b.set(listener, !errors2 ? 1 : errors2 + 1);
        if (typeof errors2 === "number" && errors2 > this.g.errors) {
          this.c.info(`onWillSaveTextDocument-listener from extension '${extension.identifier.value}' will now be IGNORED because of timeouts and/or errors`);
        }
      }
      return false;
    });
  }
  i(extension, listener, thisArg, stubEvent) {
    const promises8 = [];
    const t1 = Date.now();
    const { document: document2, reason } = stubEvent;
    const { version } = document2;
    const event = Object.freeze({
      document: document2,
      reason,
      waitUntil(p) {
        if (Object.isFrozen(promises8)) {
          throw $ob("waitUntil can not be called async");
        }
        promises8.push(Promise.resolve(p));
      }
    });
    try {
      listener.apply(thisArg, [event]);
    } catch (err) {
      return Promise.reject(err);
    }
    Object.freeze(promises8);
    return new Promise((resolve, reject) => {
      const handle = setTimeout(() => reject(new Error("timeout")), this.g.timeout);
      return Promise.all(promises8).then((edits) => {
        this.c.debug(`onWillSaveTextDocument-listener from extension '${extension.identifier.value}' finished after ${Date.now() - t1}ms`);
        clearTimeout(handle);
        resolve(edits);
      }).catch((err) => {
        clearTimeout(handle);
        reject(err);
      });
    }).then((values) => {
      const dto = { edits: [] };
      for (const value of values) {
        if (Array.isArray(value) && value.every((e) => e instanceof $IT)) {
          for (const { newText, newEol, range } of value) {
            dto.edits.push({
              resource: document2.uri,
              versionId: void 0,
              textEdit: {
                range: range && Range.from(range),
                text: newText,
                eol: newEol && EndOfLine2.from(newEol)
              }
            });
          }
        }
      }
      if (dto.edits.length === 0) {
        return void 0;
      }
      if (version === document2.version) {
        return this.f.$tryApplyWorkspaceEdit(new $ES(dto));
      }
      return Promise.reject(new Error("concurrent_edits"));
    });
  }
};

// out-build/vs/workbench/api/common/extHostDocuments.js
var $Swc = class {
  constructor(mainContext, documentsAndEditors) {
    this.a = new $ze();
    this.b = new $ze();
    this.c = new $ze();
    this.d = new $ze();
    this.onDidAddDocument = this.a.event;
    this.onDidRemoveDocument = this.b.event;
    this.onDidChangeDocument = this.c.event;
    this.onDidSaveDocument = this.d.event;
    this.e = new $2c();
    this.h = /* @__PURE__ */ new Map();
    this.f = mainContext.getProxy($xT.MainThreadDocuments);
    this.g = documentsAndEditors;
    this.g.onDidRemoveDocuments((documents) => {
      for (const data of documents) {
        this.b.fire(data.document);
      }
    }, void 0, this.e);
    this.g.onDidAddDocuments((documents) => {
      for (const data of documents) {
        this.a.fire(data.document);
      }
    }, void 0, this.e);
  }
  dispose() {
    this.e.dispose();
  }
  getAllDocumentData() {
    return [...this.g.allDocuments()];
  }
  getDocumentData(resource) {
    if (!resource) {
      return void 0;
    }
    const data = this.g.getDocument(resource);
    if (data) {
      return data;
    }
    return void 0;
  }
  getDocument(resource) {
    const data = this.getDocumentData(resource);
    if (!data?.document) {
      throw new Error(`Unable to retrieve document from URI '${resource}'`);
    }
    return data.document;
  }
  ensureDocumentData(uri) {
    const cached = this.g.getDocument(uri);
    if (cached) {
      return Promise.resolve(cached);
    }
    let promise = this.h.get(uri.toString());
    if (!promise) {
      promise = this.f.$tryOpenDocument(uri).then((uriData) => {
        this.h.delete(uri.toString());
        const canonicalUri = URI.revive(uriData);
        return $Kg(this.g.getDocument(canonicalUri));
      }, (err) => {
        this.h.delete(uri.toString());
        return Promise.reject(err);
      });
      this.h.set(uri.toString(), promise);
    }
    return promise;
  }
  createDocumentData(options2) {
    return this.f.$tryCreateDocument(options2).then((data) => URI.revive(data));
  }
  $acceptModelLanguageChanged(uriComponents, newLanguageId) {
    const uri = URI.revive(uriComponents);
    const data = this.g.getDocument(uri);
    if (!data) {
      throw new Error("unknown document");
    }
    this.b.fire(data.document);
    data._acceptLanguageId(newLanguageId);
    this.a.fire(data.document);
  }
  $acceptModelSaved(uriComponents) {
    const uri = URI.revive(uriComponents);
    const data = this.g.getDocument(uri);
    if (!data) {
      throw new Error("unknown document");
    }
    this.$acceptDirtyStateChanged(uriComponents, false);
    this.d.fire(data.document);
  }
  $acceptDirtyStateChanged(uriComponents, isDirty) {
    const uri = URI.revive(uriComponents);
    const data = this.g.getDocument(uri);
    if (!data) {
      throw new Error("unknown document");
    }
    data._acceptIsDirty(isDirty);
    this.c.fire({
      document: data.document,
      contentChanges: [],
      reason: void 0
    });
  }
  $acceptModelChanged(uriComponents, events, isDirty) {
    const uri = URI.revive(uriComponents);
    const data = this.g.getDocument(uri);
    if (!data) {
      throw new Error("unknown document");
    }
    data._acceptIsDirty(isDirty);
    data.onEvents(events);
    let reason = void 0;
    if (events.isUndoing) {
      reason = TextDocumentChangeReason.Undo;
    } else if (events.isRedoing) {
      reason = TextDocumentChangeReason.Redo;
    }
    this.c.fire($Mv({
      document: data.document,
      contentChanges: events.changes.map((change) => {
        return {
          range: Range.to(change.range),
          rangeOffset: change.rangeOffset,
          rangeLength: change.rangeLength,
          text: change.text
        };
      }),
      reason
    }));
  }
  setWordDefinitionFor(languageId, wordDefinition) {
    $iW(languageId, wordDefinition);
  }
};

// out-build/vs/workbench/api/common/extHostEmbedding.js
var $6xc = class {
  constructor(mainContext) {
    this.b = /* @__PURE__ */ new Map();
    this.c = new $ze();
    this.onDidChange = this.c.event;
    this.d = /* @__PURE__ */ new Set();
    this.e = 0;
    this.a = mainContext.getProxy($xT.MainThreadEmbeddings);
  }
  registerEmbeddingsProvider(_extension, embeddingsModel, provider) {
    if (this.d.has(embeddingsModel)) {
      throw new Error("An embeddings provider for this model is already registered");
    }
    const handle = this.e++;
    this.a.$registerEmbeddingProvider(handle, embeddingsModel);
    this.b.set(handle, { id: embeddingsModel, provider });
    return $1c(() => {
      this.d.delete(embeddingsModel);
      this.a.$unregisterEmbeddingProvider(handle);
      this.b.delete(handle);
    });
  }
  async computeEmbeddings(embeddingsModel, input, token) {
    token ??= CancellationToken.None;
    let returnSingle = false;
    if (typeof input === "string") {
      input = [input];
      returnSingle = true;
    }
    const result = await this.a.$computeEmbeddings(embeddingsModel, input, token);
    if (result.length !== input.length) {
      throw new Error();
    }
    if (returnSingle) {
      if (result.length !== 1) {
        throw new Error();
      }
      return result[0];
    }
    return result;
  }
  async $provideEmbeddings(handle, input, token) {
    const data = this.b.get(handle);
    if (!data) {
      return [];
    }
    const result = await data.provider.provideEmbeddings(input, token);
    if (!result) {
      return [];
    }
    return result;
  }
  get embeddingsModels() {
    return Array.from(this.d);
  }
  $acceptEmbeddingModels(models) {
    this.d = new Set(models);
    this.c.fire();
  }
};

// out-build/vs/workbench/api/common/extHostEmbeddingVector.js
var $7xc = class {
  constructor(mainContext) {
    this.a = /* @__PURE__ */ new Map();
    this.b = 0;
    this.c = mainContext.getProxy($xT.MainThreadAiEmbeddingVector);
  }
  async $provideAiEmbeddingVector(handle, strings, token) {
    if (this.a.size === 0) {
      throw new Error("No embedding vector providers registered");
    }
    const provider = this.a.get(handle);
    if (!provider) {
      throw new Error("Embedding vector provider not found");
    }
    const result = await provider.provideEmbeddingVector(strings, token);
    if (!result) {
      throw new Error("Embedding vector provider returned undefined");
    }
    return result;
  }
  registerEmbeddingVectorProvider(extension, model, provider) {
    const handle = this.b;
    this.b++;
    this.a.set(handle, provider);
    this.c.$registerAiEmbeddingVectorProvider(model, handle);
    return new $zT(() => {
      this.c.$unregisterAiEmbeddingVectorProvider(handle);
      this.a.delete(handle);
    });
  }
};

// out-build/vs/editor/common/languages/linkComputer.js
var State2;
(function(State4) {
  State4[State4["Invalid"] = 0] = "Invalid";
  State4[State4["Start"] = 1] = "Start";
  State4[State4["H"] = 2] = "H";
  State4[State4["HT"] = 3] = "HT";
  State4[State4["HTT"] = 4] = "HTT";
  State4[State4["HTTP"] = 5] = "HTTP";
  State4[State4["F"] = 6] = "F";
  State4[State4["FI"] = 7] = "FI";
  State4[State4["FIL"] = 8] = "FIL";
  State4[State4["BeforeColon"] = 9] = "BeforeColon";
  State4[State4["AfterColon"] = 10] = "AfterColon";
  State4[State4["AlmostThere"] = 11] = "AlmostThere";
  State4[State4["End"] = 12] = "End";
  State4[State4["Accept"] = 13] = "Accept";
  State4[State4["LastKnownState"] = 14] = "LastKnownState";
})(State2 || (State2 = {}));
var Uint8Matrix = class {
  constructor(rows, cols, defaultValue) {
    const data = new Uint8Array(rows * cols);
    for (let i = 0, len = rows * cols; i < len; i++) {
      data[i] = defaultValue;
    }
    this.a = data;
    this.rows = rows;
    this.cols = cols;
  }
  get(row, col) {
    return this.a[row * this.cols + col];
  }
  set(row, col, value) {
    this.a[row * this.cols + col] = value;
  }
};
var $09 = class {
  constructor(edges) {
    let maxCharCode = 0;
    let maxState = 0;
    for (let i = 0, len = edges.length; i < len; i++) {
      const [from, chCode, to] = edges[i];
      if (chCode > maxCharCode) {
        maxCharCode = chCode;
      }
      if (from > maxState) {
        maxState = from;
      }
      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 [from, chCode, to] = edges[i];
      states.set(from, chCode, to);
    }
    this.a = states;
    this.b = maxCharCode;
  }
  nextState(currentState, chCode) {
    if (chCode < 0 || chCode >= this.b) {
      return 0;
    }
    return this.a.get(currentState, chCode);
  }
};
var _stateMachine = null;
function getStateMachine() {
  if (_stateMachine === null) {
    _stateMachine = new $09([
      [
        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;
}
var CharacterClass;
(function(CharacterClass2) {
  CharacterClass2[CharacterClass2["None"] = 0] = "None";
  CharacterClass2[CharacterClass2["ForceTermination"] = 1] = "ForceTermination";
  CharacterClass2[CharacterClass2["CannotEndIn"] = 2] = "CannotEndIn";
})(CharacterClass || (CharacterClass = {}));
var _classifier = null;
function getClassifier() {
  if (_classifier === null) {
    _classifier = new $fE(
      0
      /* CharacterClass.None */
    );
    const FORCE_TERMINATION_CHARACTERS = ` 	<>'"\u3001\u3002\uFF61\uFF64\uFF0C\uFF0E\uFF1A\uFF1B\u2018\u3008\u300C\u300E\u3014\uFF08\uFF3B\uFF5B\uFF62\uFF63\uFF5D\uFF3D\uFF09\u3015\u300F\u300D\u3009\u2019\uFF40\uFF5E\u2026`;
    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;
}
var $$9 = class _$$9 {
  static a(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 result = [];
    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) {
            result.push(_$$9.a(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) {
        result.push(_$$9.a(classifier, line, i, linkBeginIndex, len));
      }
    }
    return result;
  }
};

// out-build/vs/workbench/api/common/extHostFileSystem.js
var FsLinkProvider = class {
  constructor() {
    this.a = [];
  }
  add(scheme) {
    this.b = void 0;
    this.a.push(scheme);
  }
  delete(scheme) {
    const idx = this.a.indexOf(scheme);
    if (idx >= 0) {
      this.a.splice(idx, 1);
      this.b = void 0;
    }
  }
  c() {
    if (!this.b) {
      const schemes = this.a.sort();
      const edges = [];
      let prevScheme;
      let prevState;
      let lastState = 14;
      let nextState = 14;
      for (const scheme of schemes) {
        let pos = !prevScheme ? 0 : $3f(prevScheme, scheme);
        if (pos === 0) {
          prevState = 1;
        } else {
          prevState = nextState;
        }
        for (; pos < scheme.length; pos++) {
          if (pos + 1 === scheme.length) {
            lastState = nextState;
            nextState = 9;
          } else {
            nextState += 1;
          }
          edges.push([prevState, scheme.toUpperCase().charCodeAt(pos), nextState]);
          edges.push([prevState, scheme.toLowerCase().charCodeAt(pos), nextState]);
          prevState = nextState;
        }
        prevScheme = scheme;
        nextState = lastState;
      }
      edges.push([
        9,
        58,
        10
        /* State.AfterColon */
      ]);
      edges.push([
        10,
        47,
        12
        /* State.End */
      ]);
      this.b = new $09(edges);
    }
  }
  provideDocumentLinks(document2) {
    this.c();
    const result = [];
    const links = $$9.computeLinks({
      getLineContent(lineNumber) {
        return document2.lineAt(lineNumber - 1).text;
      },
      getLineCount() {
        return document2.lineCount;
      }
    }, this.b);
    for (const link2 of links) {
      const docLink = DocumentLink.to(link2);
      if (docLink.target) {
        result.push(docLink);
      }
    }
    return result;
  }
};
var $8xc = class _$8xc {
  constructor(mainContext, i) {
    this.i = i;
    this.b = new FsLinkProvider();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Set();
    this.f = /* @__PURE__ */ new Map();
    this.h = 0;
    this.a = mainContext.getProxy($xT.MainThreadFileSystem);
  }
  dispose() {
    this.g?.dispose();
  }
  registerFileSystemProvider(extension, scheme, provider, options2 = {}) {
    _$8xc.j(provider);
    if (this.d.has(scheme)) {
      throw new Error(`a provider for the scheme '${scheme}' is already registered`);
    }
    if (!this.g) {
      this.g = this.i.registerDocumentLinkProvider(extension, "*", this.b);
    }
    const handle = this.h++;
    this.b.add(scheme);
    this.d.add(scheme);
    this.c.set(handle, provider);
    let capabilities = 2;
    if (options2.isCaseSensitive) {
      capabilities += 1024;
    }
    if (options2.isReadonly) {
      capabilities += 2048;
    }
    if (typeof provider.copy === "function") {
      capabilities += 8;
    }
    if (typeof provider.open === "function" && typeof provider.close === "function" && typeof provider.read === "function" && typeof provider.write === "function") {
      $AN(extension, "fsChunks");
      capabilities += 4;
    }
    let readOnlyMessage;
    if (options2.isReadonly && $dm(options2.isReadonly) && options2.isReadonly.value !== "") {
      readOnlyMessage = {
        value: options2.isReadonly.value,
        isTrusted: options2.isReadonly.isTrusted,
        supportThemeIcons: options2.isReadonly.supportThemeIcons,
        supportHtml: options2.isReadonly.supportHtml,
        baseUri: options2.isReadonly.baseUri,
        uris: options2.isReadonly.uris
      };
    }
    this.a.$registerFileSystemProvider(handle, scheme, capabilities, readOnlyMessage).catch((err) => {
      console.error(`FAILED to register filesystem provider of ${extension.identifier.value}-extension for the scheme ${scheme}`);
      console.error(err);
    });
    const subscription = provider.onDidChangeFile((event) => {
      const mapped = [];
      for (const e of event) {
        const { uri: resource, type } = e;
        if (resource.scheme !== scheme) {
          continue;
        }
        let newType;
        switch (type) {
          case FileChangeType2.Changed:
            newType = 0;
            break;
          case FileChangeType2.Created:
            newType = 1;
            break;
          case FileChangeType2.Deleted:
            newType = 2;
            break;
          default:
            throw new Error("Unknown FileChangeType");
        }
        mapped.push({ resource, type: newType });
      }
      this.a.$onFileSystemChange(handle, mapped);
    });
    return $1c(() => {
      subscription.dispose();
      this.b.delete(scheme);
      this.d.delete(scheme);
      this.c.delete(handle);
      this.a.$unregisterProvider(handle);
    });
  }
  static j(provider) {
    if (!provider) {
      throw new Error("MISSING provider");
    }
    if (typeof provider.watch !== "function") {
      throw new Error("Provider does NOT implement watch");
    }
    if (typeof provider.stat !== "function") {
      throw new Error("Provider does NOT implement stat");
    }
    if (typeof provider.readDirectory !== "function") {
      throw new Error("Provider does NOT implement readDirectory");
    }
    if (typeof provider.createDirectory !== "function") {
      throw new Error("Provider does NOT implement createDirectory");
    }
    if (typeof provider.readFile !== "function") {
      throw new Error("Provider does NOT implement readFile");
    }
    if (typeof provider.writeFile !== "function") {
      throw new Error("Provider does NOT implement writeFile");
    }
    if (typeof provider.delete !== "function") {
      throw new Error("Provider does NOT implement delete");
    }
    if (typeof provider.rename !== "function") {
      throw new Error("Provider does NOT implement rename");
    }
  }
  static k(stat2) {
    const { type, ctime, mtime, size, permissions } = stat2;
    return { type, ctime, mtime, size, permissions };
  }
  $stat(handle, resource) {
    return Promise.resolve(this.l(handle).stat(URI.revive(resource))).then((stat2) => _$8xc.k(stat2));
  }
  $readdir(handle, resource) {
    return Promise.resolve(this.l(handle).readDirectory(URI.revive(resource)));
  }
  $readFile(handle, resource) {
    return Promise.resolve(this.l(handle).readFile(URI.revive(resource))).then((data) => $Ci.wrap(data));
  }
  $writeFile(handle, resource, content, opts) {
    return Promise.resolve(this.l(handle).writeFile(URI.revive(resource), content.buffer, opts));
  }
  $delete(handle, resource, opts) {
    return Promise.resolve(this.l(handle).delete(URI.revive(resource), opts));
  }
  $rename(handle, oldUri, newUri, opts) {
    return Promise.resolve(this.l(handle).rename(URI.revive(oldUri), URI.revive(newUri), opts));
  }
  $copy(handle, oldUri, newUri, opts) {
    const provider = this.l(handle);
    if (!provider.copy) {
      throw new Error('FileSystemProvider does not implement "copy"');
    }
    return Promise.resolve(provider.copy(URI.revive(oldUri), URI.revive(newUri), opts));
  }
  $mkdir(handle, resource) {
    return Promise.resolve(this.l(handle).createDirectory(URI.revive(resource)));
  }
  $watch(handle, session, resource, opts) {
    const subscription = this.l(handle).watch(URI.revive(resource), opts);
    this.f.set(session, subscription);
  }
  $unwatch(_handle, session) {
    const subscription = this.f.get(session);
    if (subscription) {
      subscription.dispose();
      this.f.delete(session);
    }
  }
  $open(handle, resource, opts) {
    const provider = this.l(handle);
    if (!provider.open) {
      throw new Error('FileSystemProvider does not implement "open"');
    }
    return Promise.resolve(provider.open(URI.revive(resource), opts));
  }
  $close(handle, fd) {
    const provider = this.l(handle);
    if (!provider.close) {
      throw new Error('FileSystemProvider does not implement "close"');
    }
    return Promise.resolve(provider.close(fd));
  }
  $read(handle, fd, pos, length) {
    const provider = this.l(handle);
    if (!provider.read) {
      throw new Error('FileSystemProvider does not implement "read"');
    }
    const data = $Ci.alloc(length);
    return Promise.resolve(provider.read(fd, pos, data.buffer, 0, length)).then((read2) => {
      return data.slice(0, read2);
    });
  }
  $write(handle, fd, pos, data) {
    const provider = this.l(handle);
    if (!provider.write) {
      throw new Error('FileSystemProvider does not implement "write"');
    }
    return Promise.resolve(provider.write(fd, pos, data.buffer, 0, data.byteLength));
  }
  l(handle) {
    const provider = this.c.get(handle);
    if (!provider) {
      const err = new Error();
      err.name = "ENOPRO";
      err.message = `no provider`;
      throw err;
    }
    return provider;
  }
};

// out-build/vs/platform/files/common/watcher.js
function $7s(request) {
  return typeof request.correlationId === "number";
}
function $8s(request) {
  return request.recursive === true;
}
var $9s = class _$9s extends $3c {
  static {
    this.a = 5;
  }
  constructor(h, j, m, n) {
    super();
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.c = this.B(new $4c());
    this.f = void 0;
    this.g = 0;
  }
  s() {
    const disposables = new $2c();
    this.c.value = disposables;
    this.b = this.r(disposables);
    this.b.setVerboseLogging(this.m);
    disposables.add(this.b.onDidChangeFile((changes) => this.h(changes)));
    disposables.add(this.b.onDidLogMessage((msg) => this.j(msg)));
    disposables.add(this.b.onDidError((e) => this.t(e.error, e.request)));
  }
  t(error, failedRequest) {
    if (this.u(error, failedRequest)) {
      if (this.g < _$9s.a && this.f) {
        this.y(`restarting watcher after unexpected error: ${error}`);
        this.w(this.f);
      } else {
        this.y(`gave up attempting to restart watcher after unexpected error: ${error}`);
      }
    } else {
      this.y(error);
    }
  }
  u(error, failedRequest) {
    if (!this.n.restartOnError) {
      return false;
    }
    if (failedRequest) {
      return false;
    }
    if (error.indexOf("No space left on device") !== -1 || error.indexOf("EMFILE") !== -1) {
      return false;
    }
    return true;
  }
  w(requests) {
    this.g++;
    this.s();
    this.watch(requests);
  }
  async watch(requests) {
    this.f = requests;
    await this.b?.watch(requests);
  }
  async setVerboseLogging(verboseLogging) {
    this.m = verboseLogging;
    await this.b?.setVerboseLogging(verboseLogging);
  }
  y(message) {
    this.j({ type: "error", message: `[File Watcher (${this.n.type})] ${message}` });
  }
  z(message) {
    this.j({ type: "trace", message: `[File Watcher (${this.n.type})] ${message}` });
  }
  dispose() {
    this.b = void 0;
    return super.dispose();
  }
};
var $0s = class extends $9s {
  constructor(onFileChanges, onLogMessage, verboseLogging) {
    super(onFileChanges, onLogMessage, verboseLogging, { type: "node.js", restartOnError: false });
  }
};
var $$s = class extends $9s {
  constructor(onFileChanges, onLogMessage, verboseLogging) {
    super(onFileChanges, onLogMessage, verboseLogging, { type: "universal", restartOnError: true });
  }
};
function $_s(changes) {
  return changes.map((change) => ({
    type: change.type,
    resource: URI.revive(change.resource),
    cId: change.cId
  }));
}
function $at(changes) {
  const coalescer = new EventCoalescer();
  for (const event of changes) {
    coalescer.processEvent(event);
  }
  return coalescer.coalesce();
}
function $bt(path, pattern) {
  if (typeof pattern === "string" && !pattern.startsWith($zl) && !$mc(pattern)) {
    return { base: path, pattern };
  }
  return pattern;
}
function $ct(path, patterns) {
  const parsedPatterns = [];
  for (const pattern of patterns) {
    parsedPatterns.push($Dl($bt(path, pattern)));
  }
  return parsedPatterns;
}
var EventCoalescer = class {
  constructor() {
    this.a = /* @__PURE__ */ new Set();
    this.b = /* @__PURE__ */ new Map();
  }
  c(event) {
    if ($n) {
      return event.resource.fsPath;
    }
    return event.resource.fsPath.toLowerCase();
  }
  processEvent(event) {
    const existingEvent = this.b.get(this.c(event));
    let keepEvent = false;
    if (existingEvent) {
      const currentChangeType = existingEvent.type;
      const newChangeType = event.type;
      if (existingEvent.resource.fsPath !== event.resource.fsPath && (event.type === 2 || event.type === 1)) {
        keepEvent = true;
      } else if (currentChangeType === 1 && newChangeType === 2) {
        this.b.delete(this.c(event));
        this.a.delete(existingEvent);
      } else if (currentChangeType === 2 && newChangeType === 1) {
        existingEvent.type = 0;
      } else if (currentChangeType === 1 && newChangeType === 0) {
      } else {
        existingEvent.type = newChangeType;
      }
    } else {
      keepEvent = true;
    }
    if (keepEvent) {
      this.a.add(event);
      this.b.set(this.c(event), event);
    }
  }
  coalesce() {
    const addOrChangeEvents = [];
    const deletedPaths = [];
    return Array.from(this.a).filter((e) => {
      if (e.type !== 2) {
        addOrChangeEvents.push(e);
        return false;
      }
      return true;
    }).sort((e1, e2) => {
      return e1.resource.fsPath.length - e2.resource.fsPath.length;
    }).filter((e) => {
      if (deletedPaths.some((deletedPath) => $Em(
        e.resource.fsPath,
        deletedPath,
        !$n
        /* ignorecase */
      ))) {
        return false;
      }
      deletedPaths.push(e.resource.fsPath);
      return true;
    }).concat(addOrChangeEvents);
  }
};
function $dt(event, filter) {
  if (typeof filter === "number") {
    switch (event.type) {
      case 1:
        return (filter & 4) === 0;
      case 2:
        return (filter & 8) === 0;
      case 0:
        return (filter & 2) === 0;
    }
  }
  return false;
}
function $et(filter) {
  if (typeof filter === "number") {
    const filters = [];
    if (filter & 4) {
      filters.push("Added");
    }
    if (filter & 8) {
      filters.push("Deleted");
    }
    if (filter & 2) {
      filters.push("Updated");
    }
    if (filters.length === 0) {
      return "<all>";
    }
    return `[${filters.join(", ")}]`;
  }
  return "<none>";
}

// out-build/vs/workbench/api/common/extHostFileSystemEventService.js
var FileSystemWatcher = class {
  get ignoreCreateEvents() {
    return Boolean(this.h & 1);
  }
  get ignoreChangeEvents() {
    return Boolean(this.h & 2);
  }
  get ignoreDeleteEvents() {
    return Boolean(this.h & 4);
  }
  constructor(mainContext, configuration, workspace, extension, dispatcher, globPattern, options2) {
    this.a = Math.random();
    this.b = new $ze();
    this.c = new $ze();
    this.d = new $ze();
    this.h = 0;
    if (options2.ignoreCreateEvents) {
      this.h += 1;
    }
    if (options2.ignoreChangeEvents) {
      this.h += 2;
    }
    if (options2.ignoreDeleteEvents) {
      this.h += 4;
    }
    const parsedPattern = $Dl(globPattern);
    const excludeOutOfWorkspaceEvents = typeof globPattern === "string";
    const excludeUncorrelatedEvents = options2.correlate;
    const subscription = dispatcher((events) => {
      if (typeof events.session === "number" && events.session !== this.a) {
        return;
      }
      if (excludeUncorrelatedEvents && typeof events.session === "undefined") {
        return;
      }
      if (!options2.ignoreCreateEvents) {
        for (const created of events.created) {
          const uri = URI.revive(created);
          if (parsedPattern(uri.fsPath) && (!excludeOutOfWorkspaceEvents || workspace.getWorkspaceFolder(uri))) {
            this.b.fire(uri);
          }
        }
      }
      if (!options2.ignoreChangeEvents) {
        for (const changed of events.changed) {
          const uri = URI.revive(changed);
          if (parsedPattern(uri.fsPath) && (!excludeOutOfWorkspaceEvents || workspace.getWorkspaceFolder(uri))) {
            this.c.fire(uri);
          }
        }
      }
      if (!options2.ignoreDeleteEvents) {
        for (const deleted of events.deleted) {
          const uri = URI.revive(deleted);
          if (parsedPattern(uri.fsPath) && (!excludeOutOfWorkspaceEvents || workspace.getWorkspaceFolder(uri))) {
            this.d.fire(uri);
          }
        }
      }
    });
    this.g = $zT.from(this.i(mainContext, workspace, configuration, extension, globPattern, options2, options2.correlate), this.b, this.c, this.d, subscription);
  }
  i(mainContext, workspace, configuration, extension, globPattern, options2, correlate) {
    const disposable = $zT.from();
    if (typeof globPattern === "string") {
      return disposable;
    }
    if (options2.ignoreChangeEvents && options2.ignoreCreateEvents && options2.ignoreDeleteEvents) {
      return disposable;
    }
    const proxy = mainContext.getProxy($xT.MainThreadFileSystemEventService);
    let recursive = false;
    if (globPattern.pattern.includes($zl) || globPattern.pattern.includes($Al)) {
      recursive = true;
    }
    const excludes = options2.excludes ?? [];
    let includes = void 0;
    let filter;
    if (correlate) {
      if (options2.ignoreChangeEvents || options2.ignoreCreateEvents || options2.ignoreDeleteEvents) {
        filter = 2 | 4 | 8;
        if (options2.ignoreChangeEvents) {
          filter &= ~2;
        }
        if (options2.ignoreCreateEvents) {
          filter &= ~4;
        }
        if (options2.ignoreDeleteEvents) {
          filter &= ~8;
        }
      }
    } else {
      if (recursive && excludes.length === 0) {
        const workspaceFolder = workspace.getWorkspaceFolder(URI.revive(globPattern.baseUri));
        const watcherExcludes = configuration.getConfiguration("files", workspaceFolder).get("watcherExclude");
        if (watcherExcludes) {
          for (const key in watcherExcludes) {
            if (key && watcherExcludes[key] === true) {
              excludes.push(key);
            }
          }
        }
      } else if (!recursive) {
        const workspaceFolder = workspace.getWorkspaceFolder(URI.revive(globPattern.baseUri));
        if (workspaceFolder) {
          const watcherExcludes = configuration.getConfiguration("files", workspaceFolder).get("watcherExclude");
          if (watcherExcludes) {
            for (const key in watcherExcludes) {
              if (key && watcherExcludes[key] === true) {
                const includePattern = `${$Gf(key, "/")}/${$zl}`;
                if (!includes) {
                  includes = [];
                }
                includes.push($bt(workspaceFolder.uri.fsPath, includePattern));
              }
            }
          }
          if (!includes || includes.length === 0) {
            return disposable;
          }
        }
      }
    }
    proxy.$watch(extension.identifier.value, this.a, globPattern.baseUri, { recursive, excludes, includes, filter }, Boolean(correlate));
    return $zT.from({ dispose: () => proxy.$unwatch(this.a) });
  }
  dispose() {
    this.g.dispose();
  }
  get onDidCreate() {
    return this.b.event;
  }
  get onDidChange() {
    return this.c.event;
  }
  get onDidDelete() {
    return this.d.event;
  }
};
var LazyRevivedFileSystemEvents = class {
  constructor(a) {
    this.a = a;
    this.session = this.a.session;
    this.b = new $sf(() => this.a.created.map(URI.revive));
    this.c = new $sf(() => this.a.changed.map(URI.revive));
    this.d = new $sf(() => this.a.deleted.map(URI.revive));
  }
  get created() {
    return this.b.value;
  }
  get changed() {
    return this.c.value;
  }
  get deleted() {
    return this.d.value;
  }
};
var $9xc = class {
  constructor(j, k, l) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.a = new $ze();
    this.b = new $ze();
    this.c = new $ze();
    this.d = new $ze();
    this.g = new $Be();
    this.h = new $Be();
    this.i = new $Be();
    this.onDidRenameFile = this.b.event;
    this.onDidCreateFile = this.c.event;
    this.onDidDeleteFile = this.d.event;
  }
  //--- file events
  createFileSystemWatcher(workspace, configProvider, extension, globPattern, options2) {
    return new FileSystemWatcher(this.j, configProvider, workspace, extension, this.a.event, GlobPattern.from(globPattern), options2);
  }
  $onFileEvent(events) {
    this.a.fire(new LazyRevivedFileSystemEvents(events));
  }
  //--- file operations
  $onDidRunFileOperation(operation, files) {
    switch (operation) {
      case 2:
        this.b.fire(Object.freeze({ files: files.map((f) => ({ oldUri: URI.revive(f.source), newUri: URI.revive(f.target) })) }));
        break;
      case 1:
        this.d.fire(Object.freeze({ files: files.map((f) => URI.revive(f.target)) }));
        break;
      case 0:
      case 3:
        this.c.fire(Object.freeze({ files: files.map((f) => URI.revive(f.target)) }));
        break;
      default:
    }
  }
  getOnWillRenameFileEvent(extension) {
    return this.m(extension, this.g);
  }
  getOnWillCreateFileEvent(extension) {
    return this.m(extension, this.h);
  }
  getOnWillDeleteFileEvent(extension) {
    return this.m(extension, this.i);
  }
  m(extension, emitter) {
    return (listener, thisArg, disposables) => {
      const wrappedListener = function wrapped(e) {
        listener.call(thisArg, e);
      };
      wrappedListener.extension = extension;
      return emitter.event(wrappedListener, void 0, disposables);
    };
  }
  async $onWillRunFileOperation(operation, files, timeout, token) {
    switch (operation) {
      case 2:
        return await this.n(this.g, { files: files.map((f) => ({ oldUri: URI.revive(f.source), newUri: URI.revive(f.target) })) }, timeout, token);
      case 1:
        return await this.n(this.i, { files: files.map((f) => URI.revive(f.target)) }, timeout, token);
      case 0:
      case 3:
        return await this.n(this.h, { files: files.map((f) => URI.revive(f.target)) }, timeout, token);
    }
    return void 0;
  }
  async n(emitter, data, timeout, token) {
    const extensionNames = /* @__PURE__ */ new Set();
    const edits = [];
    await emitter.fireAsync(data, token, async (thenable, listener) => {
      const now = Date.now();
      const result = await Promise.resolve(thenable);
      if (result instanceof $LT) {
        edits.push([listener.extension, result]);
        extensionNames.add(listener.extension.displayName ?? listener.extension.identifier.value);
      }
      if (Date.now() - now > timeout) {
        this.k.warn("SLOW file-participant", listener.extension.identifier);
      }
    });
    if (token.isCancellationRequested) {
      return void 0;
    }
    if (edits.length === 0) {
      return void 0;
    }
    const dto = { edits: [] };
    for (const [, edit2] of edits) {
      const { edits: edits2 } = WorkspaceEdit.from(edit2, {
        getTextDocumentVersion: (uri) => this.l.getDocument(uri)?.version,
        getNotebookDocumentVersion: () => void 0
      });
      dto.edits = dto.edits.concat(edits2);
    }
    return { edit: dto, extensionNames: Array.from(extensionNames) };
  }
};

// out-build/vs/workbench/api/common/extHostInteractive.js
var $oyc = class {
  constructor(mainContext, a, b, c, _logService) {
    this.a = a;
    this.b = b;
    this.c = c;
    const openApiCommand = new $GW("interactive.open", "_interactive.open", "Open interactive window and return notebook editor and input URI", [
      new $EW("showOptions", "Show Options", (v) => true, (v) => v),
      new $EW("resource", "Interactive resource Uri", (v) => true, (v) => v),
      new $EW("controllerId", "Notebook controller Id", (v) => true, (v) => v),
      new $EW("title", "Interactive editor title", (v) => true, (v) => v)
    ], new $FW("Notebook and input URI", (v) => {
      _logService.debug("[ExtHostInteractive] open iw with notebook editor id", v.notebookEditorId);
      if (v.notebookEditorId !== void 0) {
        const editor = this.a.getEditorById(v.notebookEditorId);
        _logService.debug("[ExtHostInteractive] notebook editor found", editor.id);
        return { notebookUri: URI.revive(v.notebookUri), inputUri: URI.revive(v.inputUri), notebookEditor: editor.apiEditor };
      }
      _logService.debug("[ExtHostInteractive] notebook editor not found, uris for the interactive document", v.notebookUri, v.inputUri);
      return { notebookUri: URI.revive(v.notebookUri), inputUri: URI.revive(v.inputUri) };
    }));
    this.c.registerApiCommand(openApiCommand);
  }
  $willAddInteractiveDocument(uri, eol, languageId, notebookUri) {
    this.b.acceptDocumentsAndEditorsDelta({
      addedDocuments: [{
        EOL: eol,
        lines: [""],
        languageId,
        uri,
        isDirty: false,
        versionId: 1
      }]
    });
  }
  $willRemoveInteractiveDocument(uri, notebookUri) {
    this.b.acceptDocumentsAndEditorsDelta({
      removedDocuments: [uri]
    });
  }
};

// out-build/vs/workbench/api/common/extHostLabelService.js
var $pyc = class {
  constructor(mainContext) {
    this.b = 0;
    this.a = mainContext.getProxy($xT.MainThreadLabelService);
  }
  $registerResourceLabelFormatter(formatter) {
    const handle = this.b++;
    this.a.$registerResourceLabelFormatter(handle, formatter);
    return $1c(() => {
      this.a.$unregisterResourceLabelFormatter(handle);
    });
  }
};

// out-build/vs/editor/common/core/selection.js
var SelectionDirection;
(function(SelectionDirection2) {
  SelectionDirection2[SelectionDirection2["LTR"] = 0] = "LTR";
  SelectionDirection2[SelectionDirection2["RTL"] = 1] = "RTL";
})(SelectionDirection || (SelectionDirection = {}));
var $_D = class _$_D extends $9C {
  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 _$_D.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 _$_D(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
    }
    return new _$_D(endLineNumber, endColumn, this.startLineNumber, this.startColumn);
  }
  /**
   * Get the position at `positionLineNumber` and `positionColumn`.
   */
  getPosition() {
    return new $8C(this.positionLineNumber, this.positionColumn);
  }
  /**
   * Get the position at the start of the selection.
  */
  getSelectionStart() {
    return new $8C(this.selectionStartLineNumber, this.selectionStartColumn);
  }
  /**
   * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`.
   */
  setStartPosition(startLineNumber, startColumn) {
    if (this.getDirection() === 0) {
      return new _$_D(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
    }
    return new _$_D(this.endLineNumber, this.endColumn, startLineNumber, startColumn);
  }
  // ----
  /**
   * Create a `Selection` from one or two positions
   */
  static fromPositions(start, end = start) {
    return new _$_D(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  /**
   * Creates a `Selection` from a range, given a direction.
   */
  static fromRange(range, direction) {
    if (direction === 0) {
      return new _$_D(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
    } else {
      return new _$_D(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
    }
  }
  /**
   * Create a `Selection` from an `ISelection`.
   */
  static liftSelection(sel) {
    return new _$_D(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 _$_D(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    return new _$_D(endLineNumber, endColumn, startLineNumber, startColumn);
  }
};

// out-build/vs/workbench/api/common/extHostLanguageFeatures.js
var DocumentSymbolAdapter = class _DocumentSymbolAdapter {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideDocumentSymbols(resource, token) {
    const doc = this.d.getDocument(resource);
    const value = await this.e.provideDocumentSymbols(doc, token);
    if ($Pb(value)) {
      return void 0;
    } else if (value[0] instanceof $VT) {
      return value.map(DocumentSymbol.from);
    } else {
      return _DocumentSymbolAdapter.f(value);
    }
  }
  static f(infos) {
    infos = infos.slice(0).sort((a, b) => {
      let res2 = a.location.range.start.compareTo(b.location.range.start);
      if (res2 === 0) {
        res2 = b.location.range.end.compareTo(a.location.range.end);
      }
      return res2;
    });
    const res = [];
    const parentStack = [];
    for (const info of infos) {
      const element = {
        name: info.name || "!!MISSING: name!!",
        kind: SymbolKind3.from(info.kind),
        tags: info.tags?.map(SymbolTag3.from) || [],
        detail: "",
        containerName: info.containerName,
        range: Range.from(info.location.range),
        selectionRange: Range.from(info.location.range),
        children: []
      };
      while (true) {
        if (parentStack.length === 0) {
          parentStack.push(element);
          res.push(element);
          break;
        }
        const parent = parentStack[parentStack.length - 1];
        if ($9C.containsRange(parent.range, element.range) && !$9C.equalsRange(parent.range, element.range)) {
          parent.children?.push(element);
          parentStack.push(element);
          break;
        }
        parentStack.pop();
      }
    }
    return res;
  }
};
var CodeLensAdapter = class {
  constructor(f, g, h, j, k, l) {
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.k = k;
    this.l = l;
    this.d = new $Jwc("CodeLens");
    this.e = /* @__PURE__ */ new Map();
  }
  async provideCodeLenses(resource, token) {
    const doc = this.f.getDocument(resource);
    const lenses = await this.h.provideCodeLenses(doc, token);
    if (!lenses || token.isCancellationRequested) {
      return void 0;
    }
    const cacheId = this.d.add(lenses);
    const disposables = new $2c();
    this.e.set(cacheId, disposables);
    const result = {
      cacheId,
      lenses: []
    };
    for (let i = 0; i < lenses.length; i++) {
      result.lenses.push({
        cacheId: [cacheId, i],
        range: Range.from(lenses[i].range),
        command: this.g.toInternal(lenses[i].command, disposables)
      });
    }
    return result;
  }
  async resolveCodeLens(symbol, token) {
    const lens = symbol.cacheId && this.d.get(...symbol.cacheId);
    if (!lens) {
      return void 0;
    }
    let resolvedLens;
    if (typeof this.h.resolveCodeLens !== "function" || lens.isResolved) {
      resolvedLens = lens;
    } else {
      resolvedLens = await this.h.resolveCodeLens(lens, token);
    }
    if (!resolvedLens) {
      resolvedLens = lens;
    }
    if (token.isCancellationRequested) {
      return void 0;
    }
    const disposables = symbol.cacheId && this.e.get(symbol.cacheId[0]);
    if (!disposables) {
      return void 0;
    }
    if (!resolvedLens.command) {
      const error = new Error("INVALID code lens resolved, lacks command: " + this.j.identifier.value);
      this.k.onExtensionError(this.j.identifier, error);
      this.l.error(error);
      return void 0;
    }
    symbol.command = this.g.toInternal(resolvedLens.command, disposables);
    return symbol;
  }
  releaseCodeLenses(cachedId) {
    this.e.get(cachedId)?.dispose();
    this.e.delete(cachedId);
    this.d.delete(cachedId);
  }
};
function convertToLocationLinks(value) {
  if (Array.isArray(value)) {
    return value.map(DefinitionLink.from);
  } else if (value) {
    return [DefinitionLink.from(value)];
  }
  return [];
}
var DefinitionAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideDefinition(resource, position, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideDefinition(doc, pos, token);
    return convertToLocationLinks(value);
  }
};
var DeclarationAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideDeclaration(resource, position, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideDeclaration(doc, pos, token);
    return convertToLocationLinks(value);
  }
};
var ImplementationAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideImplementation(resource, position, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideImplementation(doc, pos, token);
    return convertToLocationLinks(value);
  }
};
var TypeDefinitionAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideTypeDefinition(resource, position, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideTypeDefinition(doc, pos, token);
    return convertToLocationLinks(value);
  }
};
var HoverAdapter = class _HoverAdapter {
  static {
    this.f = 10;
  }
  constructor(g, h) {
    this.g = g;
    this.h = h;
    this.d = 0;
    this.e = /* @__PURE__ */ new Map();
  }
  async provideHover(resource, position, context, token) {
    const doc = this.g.getDocument(resource);
    const pos = Position.to(position);
    let value;
    if (context && context.verbosityRequest) {
      const previousHoverId = context.verbosityRequest.previousHover.id;
      const previousHover = this.e.get(previousHoverId);
      if (!previousHover) {
        throw new Error(`Hover with id ${previousHoverId} not found`);
      }
      const hoverContext = { verbosityDelta: context.verbosityRequest.verbosityDelta, previousHover };
      value = await this.h.provideHover(doc, pos, token, hoverContext);
    } else {
      value = await this.h.provideHover(doc, pos, token);
    }
    if (!value || $Pb(value.contents)) {
      return void 0;
    }
    if (!value.range) {
      value.range = doc.getWordRangeAtPosition(pos);
    }
    if (!value.range) {
      value.range = new $BT(pos, pos);
    }
    const convertedHover = Hover.from(value);
    const id2 = this.d;
    if (this.e.size === _HoverAdapter.f) {
      const minimumId = Math.min(...this.e.keys());
      this.e.delete(minimumId);
    }
    this.e.set(id2, value);
    this.d += 1;
    const hover = {
      ...convertedHover,
      id: id2
    };
    return hover;
  }
  releaseHover(id2) {
    this.e.delete(id2);
  }
};
var EvaluatableExpressionAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideEvaluatableExpression(resource, position, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideEvaluatableExpression(doc, pos, token);
    if (value) {
      return EvaluatableExpression.from(value);
    }
    return void 0;
  }
};
var InlineValuesAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideInlineValues(resource, viewPort, context, token) {
    const doc = this.d.getDocument(resource);
    const value = await this.e.provideInlineValues(doc, Range.to(viewPort), InlineValueContext.to(context), token);
    if (Array.isArray(value)) {
      return value.map((iv) => InlineValue.from(iv));
    }
    return void 0;
  }
};
var DocumentHighlightAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideDocumentHighlights(resource, position, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideDocumentHighlights(doc, pos, token);
    if (Array.isArray(value)) {
      return value.map(DocumentHighlight.from);
    }
    return void 0;
  }
};
var MultiDocumentHighlightAdapter = class {
  constructor(d, e, f) {
    this.d = d;
    this.e = e;
    this.f = f;
  }
  async provideMultiDocumentHighlights(resource, position, otherResources, token) {
    const doc = this.d.getDocument(resource);
    const otherDocuments = otherResources.map((r) => {
      try {
        return this.d.getDocument(r);
      } catch (err) {
        this.f.error("Error: Unable to retrieve document from URI: " + r + ". Error message: " + err);
        return void 0;
      }
    }).filter((doc2) => doc2 !== void 0);
    const pos = Position.to(position);
    const value = await this.e.provideMultiDocumentHighlights(doc, pos, otherDocuments, token);
    if (Array.isArray(value)) {
      return value.map(MultiDocumentHighlight.from);
    }
    return void 0;
  }
};
var LinkedEditingRangeAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideLinkedEditingRanges(resource, position, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideLinkedEditingRanges(doc, pos, token);
    if (value && Array.isArray(value.ranges)) {
      return {
        ranges: $Mb(value.ranges.map(Range.from)),
        wordPattern: value.wordPattern
      };
    }
    return void 0;
  }
};
var ReferenceAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideReferences(resource, position, context, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideReferences(doc, pos, context, token);
    if (Array.isArray(value)) {
      return value.map(location.from);
    }
    return void 0;
  }
};
var CodeActionAdapter = class _CodeActionAdapter {
  static {
    this.d = 1e3;
  }
  constructor(g, h, j, k, l, m, n) {
    this.g = g;
    this.h = h;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.e = new $Jwc("CodeAction");
    this.f = /* @__PURE__ */ new Map();
  }
  async provideCodeActions(resource, rangeOrSelection, context, token) {
    const doc = this.g.getDocument(resource);
    const ran = $_D.isISelection(rangeOrSelection) ? Selection.to(rangeOrSelection) : Range.to(rangeOrSelection);
    const allDiagnostics = [];
    for (const diagnostic of this.j.getDiagnostics(resource)) {
      if (ran.intersection(diagnostic.range)) {
        const newLen = allDiagnostics.push(diagnostic);
        if (newLen > _CodeActionAdapter.d) {
          break;
        }
      }
    }
    const codeActionContext = {
      diagnostics: allDiagnostics,
      only: context.only ? new $XT(context.only) : void 0,
      triggerKind: CodeActionTriggerKind2.to(context.trigger)
    };
    const commandsOrActions = await this.k.provideCodeActions(doc, ran, codeActionContext, token);
    if (!$Qb(commandsOrActions) || token.isCancellationRequested) {
      return void 0;
    }
    const cacheId = this.e.add(commandsOrActions);
    const disposables = new $2c();
    this.f.set(cacheId, disposables);
    const actions = [];
    for (let i = 0; i < commandsOrActions.length; i++) {
      const candidate = commandsOrActions[i];
      if (!candidate) {
        continue;
      }
      if (_CodeActionAdapter.o(candidate)) {
        this.n.report("CodeActionProvider.provideCodeActions - return commands", this.m, `Return 'CodeAction' instances instead.`);
        actions.push({
          _isSynthetic: true,
          title: candidate.title,
          command: this.h.toInternal(candidate, disposables)
        });
      } else {
        if (codeActionContext.only) {
          if (!candidate.kind) {
            this.l.warn(`${this.m.identifier.value} - Code actions of kind '${codeActionContext.only.value}' requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`);
          } else if (!codeActionContext.only.contains(candidate.kind)) {
            this.l.warn(`${this.m.identifier.value} - Code actions of kind '${codeActionContext.only.value}' requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`);
          }
        }
        const range = candidate.ranges ?? [];
        actions.push({
          cacheId: [cacheId, i],
          title: candidate.title,
          command: candidate.command && this.h.toInternal(candidate.command, disposables),
          diagnostics: candidate.diagnostics && candidate.diagnostics.map(Diagnostic.from),
          edit: candidate.edit && WorkspaceEdit.from(candidate.edit, void 0),
          kind: candidate.kind && candidate.kind.value,
          isPreferred: candidate.isPreferred,
          isAI: $zN(this.m, "codeActionAI") ? candidate.isAI : false,
          ranges: $zN(this.m, "codeActionRanges") ? $Mb(range.map(Range.from)) : void 0,
          disabled: candidate.disabled?.reason
        });
      }
    }
    return { cacheId, actions };
  }
  async resolveCodeAction(id2, token) {
    const [sessionId, itemId] = id2;
    const item = this.e.get(sessionId, itemId);
    if (!item || _CodeActionAdapter.o(item)) {
      return {};
    }
    if (!this.k.resolveCodeAction) {
      return {};
    }
    const resolvedItem = await this.k.resolveCodeAction(item, token) ?? item;
    let resolvedEdit;
    if (resolvedItem.edit) {
      resolvedEdit = WorkspaceEdit.from(resolvedItem.edit, void 0);
    }
    let resolvedCommand;
    if (resolvedItem.command) {
      const disposables = this.f.get(sessionId);
      if (disposables) {
        resolvedCommand = this.h.toInternal(resolvedItem.command, disposables);
      }
    }
    return { edit: resolvedEdit, command: resolvedCommand };
  }
  releaseCodeActions(cachedId) {
    this.f.get(cachedId)?.dispose();
    this.f.delete(cachedId);
    this.e.delete(cachedId);
  }
  static o(thing) {
    return typeof thing.command === "string" && typeof thing.title === "string";
  }
};
var DocumentPasteEditProvider = class {
  constructor(e, f, g, h, j) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.d = new $Jwc("DocumentPasteEdit");
  }
  async prepareDocumentPaste(resource, ranges, dataTransferDto, token) {
    if (!this.g.prepareDocumentPaste) {
      return;
    }
    const doc = this.f.getDocument(resource);
    const vscodeRanges = ranges.map((range) => Range.to(range));
    const dataTransfer = DataTransfer.toDataTransfer(dataTransferDto, () => {
      throw new $rb();
    });
    await this.g.prepareDocumentPaste(doc, vscodeRanges, dataTransfer, token);
    if (token.isCancellationRequested) {
      return;
    }
    const entries = Array.from(dataTransfer).filter(([, value]) => !(value instanceof $tU));
    return DataTransfer.from(entries);
  }
  async providePasteEdits(requestId, resource, ranges, dataTransferDto, context, token) {
    if (!this.g.provideDocumentPasteEdits) {
      return [];
    }
    const doc = this.f.getDocument(resource);
    const vscodeRanges = ranges.map((range) => Range.to(range));
    const dataTransfer = DataTransfer.toDataTransfer(dataTransferDto, async (id2) => {
      return (await this.e.$resolvePasteFileData(this.h, requestId, id2)).buffer;
    });
    const edits = await this.g.provideDocumentPasteEdits(doc, vscodeRanges, dataTransfer, {
      only: context.only ? new $yU(context.only) : void 0,
      triggerKind: context.triggerKind
    }, token);
    if (!edits || token.isCancellationRequested) {
      return [];
    }
    const cacheId = this.d.add(edits);
    return edits.map((edit2, i) => ({
      _cacheId: [cacheId, i],
      title: edit2.title ?? localize(2757, null, this.j.displayName || this.j.name),
      kind: edit2.kind,
      yieldTo: edit2.yieldTo?.map((x) => x.value),
      insertText: typeof edit2.insertText === "string" ? edit2.insertText : { snippet: edit2.insertText.value },
      additionalEdit: edit2.additionalEdit ? WorkspaceEdit.from(edit2.additionalEdit, void 0) : void 0
    }));
  }
  async resolvePasteEdit(id2, token) {
    const [sessionId, itemId] = id2;
    const item = this.d.get(sessionId, itemId);
    if (!item || !this.g.resolveDocumentPasteEdit) {
      return {};
    }
    const resolvedItem = await this.g.resolveDocumentPasteEdit(item, token) ?? item;
    const additionalEdit = resolvedItem.additionalEdit ? WorkspaceEdit.from(resolvedItem.additionalEdit, void 0) : void 0;
    return { additionalEdit };
  }
  releasePasteEdits(id2) {
    this.d.delete(id2);
  }
};
var DocumentFormattingAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideDocumentFormattingEdits(resource, options2, token) {
    const document2 = this.d.getDocument(resource);
    const value = await this.e.provideDocumentFormattingEdits(document2, options2, token);
    if (Array.isArray(value)) {
      return value.map(TextEdit.from);
    }
    return void 0;
  }
};
var RangeFormattingAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideDocumentRangeFormattingEdits(resource, range, options2, token) {
    const document2 = this.d.getDocument(resource);
    const ran = Range.to(range);
    const value = await this.e.provideDocumentRangeFormattingEdits(document2, ran, options2, token);
    if (Array.isArray(value)) {
      return value.map(TextEdit.from);
    }
    return void 0;
  }
  async provideDocumentRangesFormattingEdits(resource, ranges, options2, token) {
    $Jg(typeof this.e.provideDocumentRangesFormattingEdits === "function", "INVALID invocation of `provideDocumentRangesFormattingEdits`");
    const document2 = this.d.getDocument(resource);
    const _ranges = ranges.map(Range.to);
    const value = await this.e.provideDocumentRangesFormattingEdits(document2, _ranges, options2, token);
    if (Array.isArray(value)) {
      return value.map(TextEdit.from);
    }
    return void 0;
  }
};
var OnTypeFormattingAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
    this.autoFormatTriggerCharacters = [];
  }
  async provideOnTypeFormattingEdits(resource, position, ch, options2, token) {
    const document2 = this.d.getDocument(resource);
    const pos = Position.to(position);
    const value = await this.e.provideOnTypeFormattingEdits(document2, pos, ch, options2, token);
    if (Array.isArray(value)) {
      return value.map(TextEdit.from);
    }
    return void 0;
  }
};
var NavigateTypeAdapter = class {
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.d = new $Jwc("WorkspaceSymbols");
  }
  async provideWorkspaceSymbols(search, token) {
    const value = await this.e.provideWorkspaceSymbols(search, token);
    if (!$Qb(value)) {
      return { symbols: [] };
    }
    const sid = this.d.add(value);
    const result = {
      cacheId: sid,
      symbols: []
    };
    for (let i = 0; i < value.length; i++) {
      const item = value[i];
      if (!item || !item.name) {
        this.f.warn("INVALID SymbolInformation", item);
        continue;
      }
      result.symbols.push({
        ...WorkspaceSymbol.from(item),
        cacheId: [sid, i]
      });
    }
    return result;
  }
  async resolveWorkspaceSymbol(symbol, token) {
    if (typeof this.e.resolveWorkspaceSymbol !== "function") {
      return symbol;
    }
    if (!symbol.cacheId) {
      return symbol;
    }
    const item = this.d.get(...symbol.cacheId);
    if (item) {
      const value = await this.e.resolveWorkspaceSymbol(item, token);
      return value && $Ov(symbol, WorkspaceSymbol.from(value), true);
    }
    return void 0;
  }
  releaseWorkspaceSymbols(id2) {
    this.d.delete(id2);
  }
};
var RenameAdapter = class _RenameAdapter {
  static supportsResolving(provider) {
    return typeof provider.prepareRename === "function";
  }
  constructor(d, e, f) {
    this.d = d;
    this.e = e;
    this.f = f;
  }
  async provideRenameEdits(resource, position, newName, token) {
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    try {
      const value = await this.e.provideRenameEdits(doc, pos, newName, token);
      if (!value) {
        return void 0;
      }
      return WorkspaceEdit.from(value);
    } catch (err) {
      const rejectReason = _RenameAdapter.g(err);
      if (rejectReason) {
        return { rejectReason, edits: void 0 };
      } else {
        return Promise.reject(err);
      }
    }
  }
  async resolveRenameLocation(resource, position, token) {
    if (typeof this.e.prepareRename !== "function") {
      return Promise.resolve(void 0);
    }
    const doc = this.d.getDocument(resource);
    const pos = Position.to(position);
    try {
      const rangeOrLocation = await this.e.prepareRename(doc, pos, token);
      let range;
      let text;
      if ($BT.isRange(rangeOrLocation)) {
        range = rangeOrLocation;
        text = doc.getText(rangeOrLocation);
      } else if ($Bg(rangeOrLocation)) {
        range = rangeOrLocation.range;
        text = rangeOrLocation.placeholder;
      }
      if (!range || !text) {
        return void 0;
      }
      if (range.start.line > pos.line || range.end.line < pos.line) {
        this.f.warn("INVALID rename location: position line must be within range start/end lines");
        return void 0;
      }
      return { range: Range.from(range), text };
    } catch (err) {
      const rejectReason = _RenameAdapter.g(err);
      if (rejectReason) {
        return { rejectReason, range: void 0, text: void 0 };
      } else {
        return Promise.reject(err);
      }
    }
  }
  static g(err) {
    if (typeof err === "string") {
      return err;
    } else if (err instanceof Error && typeof err.message === "string") {
      return err.message;
    } else {
      return void 0;
    }
  }
};
var NewSymbolNamesAdapter = class _NewSymbolNamesAdapter {
  static {
    this.d = {
      [NewSymbolNameTriggerKind.Invoke]: NewSymbolNameTriggerKind2.Invoke,
      [NewSymbolNameTriggerKind.Automatic]: NewSymbolNameTriggerKind2.Automatic
    };
  }
  constructor(e, f, g) {
    this.e = e;
    this.f = f;
    this.g = g;
  }
  async supportsAutomaticNewSymbolNamesTriggerKind() {
    return this.f.supportsAutomaticTriggerKind;
  }
  async provideNewSymbolNames(resource, range, triggerKind, token) {
    const doc = this.e.getDocument(resource);
    const pos = Range.to(range);
    try {
      const kind = _NewSymbolNamesAdapter.d[triggerKind];
      const value = await this.f.provideNewSymbolNames(doc, pos, kind, token);
      if (!value) {
        return void 0;
      }
      return value.map((v) => typeof v === "string" ? { newSymbolName: v } : { newSymbolName: v.newSymbolName, tags: v.tags });
    } catch (err) {
      this.g.error(
        _NewSymbolNamesAdapter.h(err) ?? JSON.stringify(err, null, "	")
        /* @ulugbekna: assuming `err` doesn't have circular references that could result in an exception when converting to JSON */
      );
      return void 0;
    }
  }
  // @ulugbekna: this method is also defined in RenameAdapter but seems OK to be duplicated
  static h(err) {
    if (typeof err === "string") {
      return err;
    } else if (err instanceof Error && typeof err.message === "string") {
      return err.message;
    } else {
      return void 0;
    }
  }
};
var SemanticTokensPreviousResult = class {
  constructor(resultId, tokens) {
    this.resultId = resultId;
    this.tokens = tokens;
  }
};
var DocumentSemanticTokensAdapter = class _DocumentSemanticTokensAdapter {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.e = 1;
    this.d = /* @__PURE__ */ new Map();
  }
  async provideDocumentSemanticTokens(resource, previousResultId, token) {
    const doc = this.f.getDocument(resource);
    const previousResult = previousResultId !== 0 ? this.d.get(previousResultId) : null;
    let value = typeof previousResult?.resultId === "string" && typeof this.g.provideDocumentSemanticTokensEdits === "function" ? await this.g.provideDocumentSemanticTokensEdits(doc, previousResult.resultId, token) : await this.g.provideDocumentSemanticTokens(doc, token);
    if (previousResult) {
      this.d.delete(previousResultId);
    }
    if (!value) {
      return null;
    }
    value = _DocumentSemanticTokensAdapter.h(value);
    return this.o(_DocumentSemanticTokensAdapter.n(previousResult, value), value);
  }
  async releaseDocumentSemanticColoring(semanticColoringResultId) {
    this.d.delete(semanticColoringResultId);
  }
  static h(v) {
    if (_DocumentSemanticTokensAdapter.j(v)) {
      if (_DocumentSemanticTokensAdapter.k(v)) {
        return v;
      }
      return new $YU(new Uint32Array(v.data), v.resultId);
    } else if (_DocumentSemanticTokensAdapter.l(v)) {
      if (_DocumentSemanticTokensAdapter.m(v)) {
        return v;
      }
      return new $1U(v.edits.map((edit2) => new $ZU(edit2.start, edit2.deleteCount, edit2.data ? new Uint32Array(edit2.data) : edit2.data)), v.resultId);
    }
    return v;
  }
  static j(v) {
    return v && !!v.data;
  }
  static k(v) {
    return v.data instanceof Uint32Array;
  }
  static l(v) {
    return v && Array.isArray(v.edits);
  }
  static m(v) {
    for (const edit2 of v.edits) {
      if (!(edit2.data instanceof Uint32Array)) {
        return false;
      }
    }
    return true;
  }
  static n(previousResult, newResult) {
    if (!_DocumentSemanticTokensAdapter.j(newResult)) {
      return newResult;
    }
    if (!previousResult || !previousResult.tokens) {
      return newResult;
    }
    const oldData = previousResult.tokens;
    const oldLength = oldData.length;
    const newData = newResult.data;
    const newLength = newData.length;
    let commonPrefixLength = 0;
    const maxCommonPrefixLength = Math.min(oldLength, newLength);
    while (commonPrefixLength < maxCommonPrefixLength && oldData[commonPrefixLength] === newData[commonPrefixLength]) {
      commonPrefixLength++;
    }
    if (commonPrefixLength === oldLength && commonPrefixLength === newLength) {
      return new $1U([], newResult.resultId);
    }
    let commonSuffixLength = 0;
    const maxCommonSuffixLength = maxCommonPrefixLength - commonPrefixLength;
    while (commonSuffixLength < maxCommonSuffixLength && oldData[oldLength - commonSuffixLength - 1] === newData[newLength - commonSuffixLength - 1]) {
      commonSuffixLength++;
    }
    return new $1U([{
      start: commonPrefixLength,
      deleteCount: oldLength - commonPrefixLength - commonSuffixLength,
      data: newData.subarray(commonPrefixLength, newLength - commonSuffixLength)
    }], newResult.resultId);
  }
  o(value, original) {
    if (_DocumentSemanticTokensAdapter.j(value)) {
      const myId = this.e++;
      this.d.set(myId, new SemanticTokensPreviousResult(value.resultId, value.data));
      return $$jb({
        id: myId,
        type: "full",
        data: value.data
      });
    }
    if (_DocumentSemanticTokensAdapter.l(value)) {
      const myId = this.e++;
      if (_DocumentSemanticTokensAdapter.j(original)) {
        this.d.set(myId, new SemanticTokensPreviousResult(original.resultId, original.data));
      } else {
        this.d.set(myId, new SemanticTokensPreviousResult(value.resultId));
      }
      return $$jb({
        id: myId,
        type: "delta",
        deltas: (value.edits || []).map((edit2) => ({ start: edit2.start, deleteCount: edit2.deleteCount, data: edit2.data }))
      });
    }
    return null;
  }
};
var DocumentRangeSemanticTokensAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideDocumentRangeSemanticTokens(resource, range, token) {
    const doc = this.d.getDocument(resource);
    const value = await this.e.provideDocumentRangeSemanticTokens(doc, Range.to(range), token);
    if (!value) {
      return null;
    }
    return this.f(value);
  }
  f(value) {
    return $$jb({
      id: 0,
      type: "full",
      data: value.data
    });
  }
};
var CompletionsAdapter = class _CompletionsAdapter {
  static supportsResolving(provider) {
    return typeof provider.resolveCompletionItem === "function";
  }
  constructor(f, g, h, j, k) {
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.k = k;
    this.d = new $Jwc("CompletionItem");
    this.e = /* @__PURE__ */ new Map();
  }
  async provideCompletionItems(resource, position, context, token) {
    const doc = this.f.getDocument(resource);
    const pos = Position.to(position);
    const replaceRange = doc.getWordRangeAtPosition(pos) || new $BT(pos, pos);
    const insertRange = replaceRange.with({ end: pos });
    const sw = new $te();
    const itemsOrList = await this.h.provideCompletionItems(doc, pos, token, CompletionContext.to(context));
    if (!itemsOrList) {
      return void 0;
    }
    if (token.isCancellationRequested) {
      return void 0;
    }
    const list2 = Array.isArray(itemsOrList) ? new $$T(itemsOrList) : itemsOrList;
    const pid = _CompletionsAdapter.supportsResolving(this.h) ? this.d.add(list2.items) : this.d.add([]);
    const disposables = new $2c();
    this.e.set(pid, disposables);
    const completions = [];
    const result = {
      x: pid,
      [
        "b"
        /* extHostProtocol.ISuggestResultDtoField.completions */
      ]: completions,
      [
        "a"
        /* extHostProtocol.ISuggestResultDtoField.defaultRanges */
      ]: { replace: Range.from(replaceRange), insert: Range.from(insertRange) },
      [
        "c"
        /* extHostProtocol.ISuggestResultDtoField.isIncomplete */
      ]: list2.isIncomplete || void 0,
      [
        "d"
        /* extHostProtocol.ISuggestResultDtoField.duration */
      ]: sw.elapsed()
    };
    for (let i = 0; i < list2.items.length; i++) {
      const item = list2.items[i];
      const dto = this.l(item, [pid, i], insertRange, replaceRange);
      completions.push(dto);
    }
    return result;
  }
  async resolveCompletionItem(id2, token) {
    if (typeof this.h.resolveCompletionItem !== "function") {
      return void 0;
    }
    const item = this.d.get(...id2);
    if (!item) {
      return void 0;
    }
    const dto1 = this.l(item, id2);
    const resolvedItem = await this.h.resolveCompletionItem(item, token);
    if (!resolvedItem) {
      return void 0;
    }
    const dto2 = this.l(resolvedItem, id2);
    if (dto1[
      "h"
      /* extHostProtocol.ISuggestDataDtoField.insertText */
    ] !== dto2[
      "h"
      /* extHostProtocol.ISuggestDataDtoField.insertText */
    ] || dto1[
      "i"
      /* extHostProtocol.ISuggestDataDtoField.insertTextRules */
    ] !== dto2[
      "i"
      /* extHostProtocol.ISuggestDataDtoField.insertTextRules */
    ]) {
      this.j.report("CompletionItem.insertText", this.k, "extension MAY NOT change 'insertText' of a CompletionItem during resolve");
    }
    if (dto1[
      "n"
      /* extHostProtocol.ISuggestDataDtoField.commandIdent */
    ] !== dto2[
      "n"
      /* extHostProtocol.ISuggestDataDtoField.commandIdent */
    ] || dto1[
      "o"
      /* extHostProtocol.ISuggestDataDtoField.commandId */
    ] !== dto2[
      "o"
      /* extHostProtocol.ISuggestDataDtoField.commandId */
    ] || !$Pv(dto1[
      "p"
      /* extHostProtocol.ISuggestDataDtoField.commandArguments */
    ], dto2[
      "p"
      /* extHostProtocol.ISuggestDataDtoField.commandArguments */
    ])) {
      this.j.report("CompletionItem.command", this.k, "extension MAY NOT change 'command' of a CompletionItem during resolve");
    }
    return {
      ...dto1,
      [
        "d"
        /* extHostProtocol.ISuggestDataDtoField.documentation */
      ]: dto2[
        "d"
        /* extHostProtocol.ISuggestDataDtoField.documentation */
      ],
      [
        "c"
        /* extHostProtocol.ISuggestDataDtoField.detail */
      ]: dto2[
        "c"
        /* extHostProtocol.ISuggestDataDtoField.detail */
      ],
      [
        "l"
        /* extHostProtocol.ISuggestDataDtoField.additionalTextEdits */
      ]: dto2[
        "l"
        /* extHostProtocol.ISuggestDataDtoField.additionalTextEdits */
      ],
      // (fishy) async insertText
      [
        "h"
        /* extHostProtocol.ISuggestDataDtoField.insertText */
      ]: dto2[
        "h"
        /* extHostProtocol.ISuggestDataDtoField.insertText */
      ],
      [
        "i"
        /* extHostProtocol.ISuggestDataDtoField.insertTextRules */
      ]: dto2[
        "i"
        /* extHostProtocol.ISuggestDataDtoField.insertTextRules */
      ],
      // (fishy) async command
      [
        "n"
        /* extHostProtocol.ISuggestDataDtoField.commandIdent */
      ]: dto2[
        "n"
        /* extHostProtocol.ISuggestDataDtoField.commandIdent */
      ],
      [
        "o"
        /* extHostProtocol.ISuggestDataDtoField.commandId */
      ]: dto2[
        "o"
        /* extHostProtocol.ISuggestDataDtoField.commandId */
      ],
      [
        "p"
        /* extHostProtocol.ISuggestDataDtoField.commandArguments */
      ]: dto2[
        "p"
        /* extHostProtocol.ISuggestDataDtoField.commandArguments */
      ]
    };
  }
  releaseCompletionItems(id2) {
    this.e.get(id2)?.dispose();
    this.e.delete(id2);
    this.d.delete(id2);
  }
  l(item, id2, defaultInsertRange, defaultReplaceRange) {
    const disposables = this.e.get(id2[0]);
    if (!disposables) {
      throw Error("DisposableStore is missing...");
    }
    const command = this.g.toInternal(item.command, disposables);
    const result = {
      //
      x: id2,
      //
      [
        "a"
        /* extHostProtocol.ISuggestDataDtoField.label */
      ]: item.label,
      [
        "b"
        /* extHostProtocol.ISuggestDataDtoField.kind */
      ]: item.kind !== void 0 ? CompletionItemKind3.from(item.kind) : void 0,
      [
        "m"
        /* extHostProtocol.ISuggestDataDtoField.kindModifier */
      ]: item.tags && item.tags.map(CompletionItemTag3.from),
      [
        "c"
        /* extHostProtocol.ISuggestDataDtoField.detail */
      ]: item.detail,
      [
        "d"
        /* extHostProtocol.ISuggestDataDtoField.documentation */
      ]: typeof item.documentation === "undefined" ? void 0 : MarkdownString.fromStrict(item.documentation),
      [
        "e"
        /* extHostProtocol.ISuggestDataDtoField.sortText */
      ]: item.sortText !== item.label ? item.sortText : void 0,
      [
        "f"
        /* extHostProtocol.ISuggestDataDtoField.filterText */
      ]: item.filterText !== item.label ? item.filterText : void 0,
      [
        "g"
        /* extHostProtocol.ISuggestDataDtoField.preselect */
      ]: item.preselect || void 0,
      [
        "i"
        /* extHostProtocol.ISuggestDataDtoField.insertTextRules */
      ]: item.keepWhitespace ? 1 : 0,
      [
        "k"
        /* extHostProtocol.ISuggestDataDtoField.commitCharacters */
      ]: item.commitCharacters?.join(""),
      [
        "l"
        /* extHostProtocol.ISuggestDataDtoField.additionalTextEdits */
      ]: item.additionalTextEdits && item.additionalTextEdits.map(TextEdit.from),
      [
        "n"
        /* extHostProtocol.ISuggestDataDtoField.commandIdent */
      ]: command?.$ident,
      [
        "o"
        /* extHostProtocol.ISuggestDataDtoField.commandId */
      ]: command?.id,
      [
        "p"
        /* extHostProtocol.ISuggestDataDtoField.commandArguments */
      ]: command?.$ident ? void 0 : command?.arguments
      // filled in on main side from $ident
    };
    if (item.textEdit) {
      this.j.report("CompletionItem.textEdit", this.k, `Use 'CompletionItem.insertText' and 'CompletionItem.range' instead.`);
      result[
        "h"
        /* extHostProtocol.ISuggestDataDtoField.insertText */
      ] = item.textEdit.newText;
    } else if (typeof item.insertText === "string") {
      result[
        "h"
        /* extHostProtocol.ISuggestDataDtoField.insertText */
      ] = item.insertText;
    } else if (item.insertText instanceof $MT) {
      result[
        "h"
        /* extHostProtocol.ISuggestDataDtoField.insertText */
      ] = item.insertText.value;
      result[
        "i"
        /* extHostProtocol.ISuggestDataDtoField.insertTextRules */
      ] |= 4;
    }
    let range;
    if (item.textEdit) {
      range = item.textEdit.range;
    } else if (item.range) {
      range = item.range;
    }
    if ($BT.isRange(range)) {
      result[
        "j"
        /* extHostProtocol.ISuggestDataDtoField.range */
      ] = Range.from(range);
    } else if (range && (!defaultInsertRange?.isEqual(range.inserting) || !defaultReplaceRange?.isEqual(range.replacing))) {
      result[
        "j"
        /* extHostProtocol.ISuggestDataDtoField.range */
      ] = {
        insert: Range.from(range.inserting),
        replace: Range.from(range.replacing)
      };
    }
    return result;
  }
};
var InlineCompletionAdapterBase = class {
  async provideInlineCompletions(resource, position, context, token) {
    return void 0;
  }
  async provideInlineEditsForRange(resource, range, context, token) {
    return void 0;
  }
  disposeCompletions(pid) {
  }
  handleDidShowCompletionItem(pid, idx, updatedInsertText) {
  }
  handlePartialAccept(pid, idx, acceptedCharacters, info) {
  }
};
var InlineCompletionAdapter = class extends InlineCompletionAdapterBase {
  constructor(f, g, h, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.d = new ReferenceMap();
    this.e = $zN(this.f, "inlineCompletionsAdditions");
    this.k = {
      [InlineCompletionTriggerKind.Automatic]: InlineCompletionTriggerKind2.Automatic,
      [InlineCompletionTriggerKind.Explicit]: InlineCompletionTriggerKind2.Invoke
    };
  }
  get supportsHandleEvents() {
    return $zN(this.f, "inlineCompletionsAdditions") && (typeof this.h.handleDidShowCompletionItem === "function" || typeof this.h.handleDidPartiallyAcceptCompletionItem === "function");
  }
  async provideInlineCompletions(resource, position, context, token) {
    const doc = this.g.getDocument(resource);
    const pos = Position.to(position);
    const result = await this.h.provideInlineCompletionItems(doc, pos, {
      selectedCompletionInfo: context.selectedSuggestionInfo ? {
        range: Range.to(context.selectedSuggestionInfo.range),
        text: context.selectedSuggestionInfo.text
      } : void 0,
      triggerKind: this.k[context.triggerKind]
    }, token);
    if (!result) {
      return void 0;
    }
    if (token.isCancellationRequested) {
      return void 0;
    }
    const normalizedResult = Array.isArray(result) ? result : result.items;
    const commands = this.e ? Array.isArray(result) ? [] : result.commands || [] : [];
    const enableForwardStability = this.e && !Array.isArray(result) ? result.enableForwardStability : void 0;
    let disposableStore = void 0;
    const pid = this.d.createReferenceId({
      dispose() {
        disposableStore?.dispose();
      },
      items: normalizedResult
    });
    return {
      pid,
      items: normalizedResult.map((item, idx) => {
        let command = void 0;
        if (item.command) {
          if (!disposableStore) {
            disposableStore = new $2c();
          }
          command = this.j.toInternal(item.command, disposableStore);
        }
        const insertText = item.insertText;
        return {
          insertText: typeof insertText === "string" ? insertText : { snippet: insertText.value },
          filterText: item.filterText,
          range: item.range ? Range.from(item.range) : void 0,
          command,
          idx,
          completeBracketPairs: this.e ? item.completeBracketPairs : false
        };
      }),
      commands: commands.map((c) => {
        if (!disposableStore) {
          disposableStore = new $2c();
        }
        return this.j.toInternal(c, disposableStore);
      }),
      suppressSuggestions: false,
      enableForwardStability
    };
  }
  async provideInlineEditsForRange(resource, range, context, token) {
    if (!this.h.provideInlineEditsForRange) {
      return void 0;
    }
    $AN(this.f, "inlineCompletionsAdditions");
    const doc = this.g.getDocument(resource);
    const r = Range.to(range);
    const result = await this.h.provideInlineEditsForRange(doc, r, {
      selectedCompletionInfo: context.selectedSuggestionInfo ? {
        range: Range.to(context.selectedSuggestionInfo.range),
        text: context.selectedSuggestionInfo.text
      } : void 0,
      triggerKind: this.k[context.triggerKind],
      userPrompt: context.userPrompt
    }, token);
    if (!result) {
      return void 0;
    }
    if (token.isCancellationRequested) {
      return void 0;
    }
    const normalizedResult = Array.isArray(result) ? result : result.items;
    const commands = this.e ? Array.isArray(result) ? [] : result.commands || [] : [];
    const enableForwardStability = this.e && !Array.isArray(result) ? result.enableForwardStability : void 0;
    let disposableStore = void 0;
    const pid = this.d.createReferenceId({
      dispose() {
        disposableStore?.dispose();
      },
      items: normalizedResult
    });
    return {
      pid,
      items: normalizedResult.map((item, idx) => {
        let command = void 0;
        if (item.command) {
          if (!disposableStore) {
            disposableStore = new $2c();
          }
          command = this.j.toInternal(item.command, disposableStore);
        }
        const insertText = item.insertText;
        return {
          insertText: typeof insertText === "string" ? insertText : { snippet: insertText.value },
          filterText: item.filterText,
          range: item.range ? Range.from(item.range) : void 0,
          command,
          idx,
          completeBracketPairs: this.e ? item.completeBracketPairs : false
        };
      }),
      commands: commands.map((c) => {
        if (!disposableStore) {
          disposableStore = new $2c();
        }
        return this.j.toInternal(c, disposableStore);
      }),
      suppressSuggestions: false,
      enableForwardStability
    };
  }
  disposeCompletions(pid) {
    const data = this.d.disposeReferenceId(pid);
    data?.dispose();
  }
  handleDidShowCompletionItem(pid, idx, updatedInsertText) {
    const completionItem = this.d.get(pid)?.items[idx];
    if (completionItem) {
      if (this.h.handleDidShowCompletionItem && this.e) {
        this.h.handleDidShowCompletionItem(completionItem, updatedInsertText);
      }
    }
  }
  handlePartialAccept(pid, idx, acceptedCharacters, info) {
    const completionItem = this.d.get(pid)?.items[idx];
    if (completionItem) {
      if (this.h.handleDidPartiallyAcceptCompletionItem && this.e) {
        this.h.handleDidPartiallyAcceptCompletionItem(completionItem, acceptedCharacters);
        this.h.handleDidPartiallyAcceptCompletionItem(completionItem, PartialAcceptInfo.to(info));
      }
    }
  }
};
var InlineEditAdapter = class {
  async provideInlineEdits(uri, context, token) {
    const doc = this.f.getDocument(uri);
    const result = await this.g.provideInlineEdit(doc, {
      triggerKind: this.e[context.triggerKind]
    }, token);
    if (!result) {
      return void 0;
    }
    if (token.isCancellationRequested) {
      return void 0;
    }
    let disposableStore = void 0;
    const pid = this.d.createReferenceId({
      dispose() {
        disposableStore?.dispose();
      },
      item: result
    });
    let acceptCommand = void 0;
    if (result.accepted) {
      if (!disposableStore) {
        disposableStore = new $2c();
      }
      acceptCommand = this.h.toInternal(result.accepted, disposableStore);
    }
    let rejectCommand = void 0;
    if (result.rejected) {
      if (!disposableStore) {
        disposableStore = new $2c();
      }
      rejectCommand = this.h.toInternal(result.rejected, disposableStore);
    }
    let shownCommand = void 0;
    if (result.shown) {
      if (!disposableStore) {
        disposableStore = new $2c();
      }
      shownCommand = this.h.toInternal(result.shown, disposableStore);
    }
    if (!disposableStore) {
      disposableStore = new $2c();
    }
    const langResult = {
      pid,
      text: result.text,
      range: Range.from(result.range),
      accepted: acceptCommand,
      rejected: rejectCommand,
      shown: shownCommand,
      commands: result.commands?.map((c) => this.h.toInternal(c, disposableStore))
    };
    return langResult;
  }
  disposeEdit(pid) {
    const data = this.d.disposeReferenceId(pid);
    data?.dispose();
  }
  constructor(_extension, f, g, h) {
    this.f = f;
    this.g = g;
    this.h = h;
    this.d = new ReferenceMap();
    this.e = {
      [InlineEditTriggerKind.Automatic]: InlineEditTriggerKind2.Automatic,
      [InlineEditTriggerKind.Invoke]: InlineEditTriggerKind2.Invoke
    };
  }
};
var ReferenceMap = class {
  constructor() {
    this.d = /* @__PURE__ */ new Map();
    this.e = 1;
  }
  createReferenceId(value) {
    const id2 = this.e++;
    this.d.set(id2, value);
    return id2;
  }
  disposeReferenceId(referenceId) {
    const value = this.d.get(referenceId);
    this.d.delete(referenceId);
    return value;
  }
  get(referenceId) {
    return this.d.get(referenceId);
  }
};
var SignatureHelpAdapter = class {
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.d = new $Jwc("SignatureHelp");
  }
  async provideSignatureHelp(resource, position, context, token) {
    const doc = this.e.getDocument(resource);
    const pos = Position.to(position);
    const vscodeContext = this.g(context);
    const value = await this.f.provideSignatureHelp(doc, pos, token, vscodeContext);
    if (value) {
      const id2 = this.d.add([value]);
      return { ...SignatureHelp.from(value), id: id2 };
    }
    return void 0;
  }
  g(context) {
    let activeSignatureHelp = void 0;
    if (context.activeSignatureHelp) {
      const revivedSignatureHelp = SignatureHelp.to(context.activeSignatureHelp);
      const saved = this.d.get(context.activeSignatureHelp.id, 0);
      if (saved) {
        activeSignatureHelp = saved;
        activeSignatureHelp.activeSignature = revivedSignatureHelp.activeSignature;
        activeSignatureHelp.activeParameter = revivedSignatureHelp.activeParameter;
      } else {
        activeSignatureHelp = revivedSignatureHelp;
      }
    }
    return { ...context, activeSignatureHelp };
  }
  releaseSignatureHelp(id2) {
    this.d.delete(id2);
  }
};
var InlayHintsAdapter = class {
  constructor(f, g, h, j, k) {
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.k = k;
    this.d = new $Jwc("InlayHints");
    this.e = /* @__PURE__ */ new Map();
  }
  async provideInlayHints(resource, ran, token) {
    const doc = this.f.getDocument(resource);
    const range = Range.to(ran);
    const hints = await this.h.provideInlayHints(doc, range, token);
    if (!Array.isArray(hints) || hints.length === 0) {
      this.j.trace(`[InlayHints] NO inlay hints from '${this.k.identifier.value}' for range ${JSON.stringify(ran)}`);
      return void 0;
    }
    if (token.isCancellationRequested) {
      return void 0;
    }
    const pid = this.d.add(hints);
    this.e.set(pid, new $2c());
    const result = { hints: [], cacheId: pid };
    for (let i = 0; i < hints.length; i++) {
      if (this.l(hints[i], range)) {
        result.hints.push(this.m(hints[i], [pid, i]));
      }
    }
    this.j.trace(`[InlayHints] ${result.hints.length} inlay hints from '${this.k.identifier.value}' for range ${JSON.stringify(ran)}`);
    return result;
  }
  async resolveInlayHint(id2, token) {
    if (typeof this.h.resolveInlayHint !== "function") {
      return void 0;
    }
    const item = this.d.get(...id2);
    if (!item) {
      return void 0;
    }
    const hint = await this.h.resolveInlayHint(item, token);
    if (!hint) {
      return void 0;
    }
    if (!this.l(hint)) {
      return void 0;
    }
    return this.m(hint, id2);
  }
  releaseHints(id2) {
    this.e.get(id2)?.dispose();
    this.e.delete(id2);
    this.d.delete(id2);
  }
  l(hint, range) {
    if (hint.label.length === 0 || Array.isArray(hint.label) && hint.label.every((part) => part.value.length === 0)) {
      console.log("INVALID inlay hint, empty label", hint);
      return false;
    }
    if (range && !range.contains(hint.position)) {
      return false;
    }
    return true;
  }
  m(hint, id2) {
    const disposables = this.e.get(id2[0]);
    if (!disposables) {
      throw Error("DisposableStore is missing...");
    }
    const result = {
      label: "",
      // fill-in below
      cacheId: id2,
      tooltip: MarkdownString.fromStrict(hint.tooltip),
      position: Position.from(hint.position),
      textEdits: hint.textEdits && hint.textEdits.map(TextEdit.from),
      kind: hint.kind && InlayHintKind3.from(hint.kind),
      paddingLeft: hint.paddingLeft,
      paddingRight: hint.paddingRight
    };
    if (typeof hint.label === "string") {
      result.label = hint.label;
    } else {
      const parts = [];
      result.label = parts;
      for (const part of hint.label) {
        if (!part.value) {
          console.warn("INVALID inlay hint, empty label part", this.k.identifier.value);
          continue;
        }
        const part2 = {
          label: part.value,
          tooltip: MarkdownString.fromStrict(part.tooltip)
        };
        if ($NT.isLocation(part.location)) {
          part2.location = location.from(part.location);
        }
        if (part.command) {
          part2.command = this.g.toInternal(part.command, disposables);
        }
        parts.push(part2);
      }
    }
    return result;
  }
};
var LinkProviderAdapter = class _LinkProviderAdapter {
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.d = new $Jwc("DocumentLink");
  }
  async provideLinks(resource, token) {
    const doc = this.e.getDocument(resource);
    const links = await this.f.provideDocumentLinks(doc, token);
    if (!Array.isArray(links) || links.length === 0) {
      return void 0;
    }
    if (token.isCancellationRequested) {
      return void 0;
    }
    if (typeof this.f.resolveDocumentLink !== "function") {
      return { links: links.filter(_LinkProviderAdapter.g).map(DocumentLink.from) };
    } else {
      const pid = this.d.add(links);
      const result = { links: [], cacheId: pid };
      for (let i = 0; i < links.length; i++) {
        if (!_LinkProviderAdapter.g(links[i])) {
          continue;
        }
        const dto = DocumentLink.from(links[i]);
        dto.cacheId = [pid, i];
        result.links.push(dto);
      }
      return result;
    }
  }
  static g(link2) {
    if (link2.target && link2.target.path.length > 5e4) {
      console.warn("DROPPING link because it is too long");
      return false;
    }
    return true;
  }
  async resolveLink(id2, token) {
    if (typeof this.f.resolveDocumentLink !== "function") {
      return void 0;
    }
    const item = this.d.get(...id2);
    if (!item) {
      return void 0;
    }
    const link2 = await this.f.resolveDocumentLink(item, token);
    if (!link2 || !_LinkProviderAdapter.g(link2)) {
      return void 0;
    }
    return DocumentLink.from(link2);
  }
  releaseLinks(id2) {
    this.d.delete(id2);
  }
};
var ColorProviderAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideColors(resource, token) {
    const doc = this.d.getDocument(resource);
    const colors = await this.e.provideDocumentColors(doc, token);
    if (!Array.isArray(colors)) {
      return [];
    }
    const colorInfos = colors.map((ci) => {
      return {
        color: Color.from(ci.color),
        range: Range.from(ci.range)
      };
    });
    return colorInfos;
  }
  async provideColorPresentations(resource, raw, token) {
    const document2 = this.d.getDocument(resource);
    const range = Range.to(raw.range);
    const color2 = Color.to(raw.color);
    const value = await this.e.provideColorPresentations(color2, { document: document2, range }, token);
    if (!Array.isArray(value)) {
      return void 0;
    }
    return value.map(ColorPresentation.from);
  }
};
var FoldingProviderAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideFoldingRanges(resource, context, token) {
    const doc = this.d.getDocument(resource);
    const ranges = await this.e.provideFoldingRanges(doc, context, token);
    if (!Array.isArray(ranges)) {
      return void 0;
    }
    return ranges.map(FoldingRange.from);
  }
};
var SelectionRangeAdapter = class {
  constructor(d, e, f) {
    this.d = d;
    this.e = e;
    this.f = f;
  }
  async provideSelectionRanges(resource, pos, token) {
    const document2 = this.d.getDocument(resource);
    const positions = pos.map(Position.to);
    const allProviderRanges = await this.e.provideSelectionRanges(document2, positions, token);
    if (!$Qb(allProviderRanges)) {
      return [];
    }
    if (allProviderRanges.length !== positions.length) {
      this.f.warn("BAD selection ranges, provider must return ranges for each position");
      return [];
    }
    const allResults = [];
    for (let i = 0; i < positions.length; i++) {
      const oneResult = [];
      allResults.push(oneResult);
      let last = positions[i];
      let selectionRange = allProviderRanges[i];
      while (true) {
        if (!selectionRange.range.contains(last)) {
          throw new Error("INVALID selection range, must contain the previous range");
        }
        oneResult.push(SelectionRange.from(selectionRange));
        if (!selectionRange.parent) {
          break;
        }
        last = selectionRange.range;
        selectionRange = selectionRange.parent;
      }
    }
    return allResults;
  }
};
var CallHierarchyAdapter = class {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.d = new $lW("");
    this.e = /* @__PURE__ */ new Map();
  }
  async prepareSession(uri, position, token) {
    const doc = this.f.getDocument(uri);
    const pos = Position.to(position);
    const items = await this.g.prepareCallHierarchy(doc, pos, token);
    if (!items) {
      return void 0;
    }
    const sessionId = this.d.nextId();
    this.e.set(sessionId, /* @__PURE__ */ new Map());
    if (Array.isArray(items)) {
      return items.map((item) => this.h(sessionId, item));
    } else {
      return [this.h(sessionId, items)];
    }
  }
  async provideCallsTo(sessionId, itemId, token) {
    const item = this.j(sessionId, itemId);
    if (!item) {
      throw new Error("missing call hierarchy item");
    }
    const calls = await this.g.provideCallHierarchyIncomingCalls(item, token);
    if (!calls) {
      return void 0;
    }
    return calls.map((call) => {
      return {
        from: this.h(sessionId, call.from),
        fromRanges: call.fromRanges.map((r) => Range.from(r))
      };
    });
  }
  async provideCallsFrom(sessionId, itemId, token) {
    const item = this.j(sessionId, itemId);
    if (!item) {
      throw new Error("missing call hierarchy item");
    }
    const calls = await this.g.provideCallHierarchyOutgoingCalls(item, token);
    if (!calls) {
      return void 0;
    }
    return calls.map((call) => {
      return {
        to: this.h(sessionId, call.to),
        fromRanges: call.fromRanges.map((r) => Range.from(r))
      };
    });
  }
  releaseSession(sessionId) {
    this.e.delete(sessionId);
  }
  h(sessionId, item) {
    const map = this.e.get(sessionId);
    const dto = CallHierarchyItem.from(item, sessionId, map.size.toString(36));
    map.set(dto._itemId, item);
    return dto;
  }
  j(sessionId, itemId) {
    const map = this.e.get(sessionId);
    return map?.get(itemId);
  }
};
var TypeHierarchyAdapter = class {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.d = new $lW("");
    this.e = /* @__PURE__ */ new Map();
  }
  async prepareSession(uri, position, token) {
    const doc = this.f.getDocument(uri);
    const pos = Position.to(position);
    const items = await this.g.prepareTypeHierarchy(doc, pos, token);
    if (!items) {
      return void 0;
    }
    const sessionId = this.d.nextId();
    this.e.set(sessionId, /* @__PURE__ */ new Map());
    if (Array.isArray(items)) {
      return items.map((item) => this.h(sessionId, item));
    } else {
      return [this.h(sessionId, items)];
    }
  }
  async provideSupertypes(sessionId, itemId, token) {
    const item = this.j(sessionId, itemId);
    if (!item) {
      throw new Error("missing type hierarchy item");
    }
    const supertypes = await this.g.provideTypeHierarchySupertypes(item, token);
    if (!supertypes) {
      return void 0;
    }
    return supertypes.map((supertype) => {
      return this.h(sessionId, supertype);
    });
  }
  async provideSubtypes(sessionId, itemId, token) {
    const item = this.j(sessionId, itemId);
    if (!item) {
      throw new Error("missing type hierarchy item");
    }
    const subtypes = await this.g.provideTypeHierarchySubtypes(item, token);
    if (!subtypes) {
      return void 0;
    }
    return subtypes.map((subtype) => {
      return this.h(sessionId, subtype);
    });
  }
  releaseSession(sessionId) {
    this.e.delete(sessionId);
  }
  h(sessionId, item) {
    const map = this.e.get(sessionId);
    const dto = TypeHierarchyItem.from(item, sessionId, map.size.toString(36));
    map.set(dto._itemId, item);
    return dto;
  }
  j(sessionId, itemId) {
    const map = this.e.get(sessionId);
    return map?.get(itemId);
  }
};
var DocumentDropEditAdapter = class {
  constructor(e, f, g, h, j) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.d = new $Jwc("DocumentDropEdit");
  }
  async provideDocumentOnDropEdits(requestId, uri, position, dataTransferDto, token) {
    const doc = this.f.getDocument(uri);
    const pos = Position.to(position);
    const dataTransfer = DataTransfer.toDataTransfer(dataTransferDto, async (id2) => {
      return (await this.e.$resolveDocumentOnDropFileData(this.h, requestId, id2)).buffer;
    });
    const edits = await this.g.provideDocumentDropEdits(doc, pos, dataTransfer, token);
    if (!edits) {
      return void 0;
    }
    const editsArray = $5b(edits);
    const cacheId = this.d.add(editsArray);
    return editsArray.map((edit2, i) => ({
      _cacheId: [cacheId, i],
      title: edit2.title ?? localize(2758, null, this.j.displayName || this.j.name),
      kind: edit2.kind?.value,
      yieldTo: edit2.yieldTo?.map((x) => x.value),
      insertText: typeof edit2.insertText === "string" ? edit2.insertText : { snippet: edit2.insertText.value },
      additionalEdit: edit2.additionalEdit ? WorkspaceEdit.from(edit2.additionalEdit, void 0) : void 0
    }));
  }
  async resolveDropEdit(id2, token) {
    const [sessionId, itemId] = id2;
    const item = this.d.get(sessionId, itemId);
    if (!item || !this.g.resolveDocumentDropEdit) {
      return {};
    }
    const resolvedItem = await this.g.resolveDocumentDropEdit(item, token) ?? item;
    const additionalEdit = resolvedItem.additionalEdit ? WorkspaceEdit.from(resolvedItem.additionalEdit, void 0) : void 0;
    return { additionalEdit };
  }
  releaseDropEdits(id2) {
    this.d.delete(id2);
  }
};
var MappedEditsAdapter = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  async provideMappedEdits(resource, codeBlocks, context, token) {
    const uri = URI.revive(resource);
    const doc = this.d.getDocument(uri);
    const reviveContextItem = (item) => ({
      uri: URI.revive(item.uri),
      version: item.version,
      ranges: item.ranges.map((r) => Range.to(r))
    });
    const usedContext = context.documents.map((docSubArray) => docSubArray.map(reviveContextItem));
    const ctx = {
      documents: usedContext,
      selections: usedContext[0]?.[0]?.ranges ?? [],
      // @ulugbekna: this is a hack for backward compatibility
      conversation: context.conversation?.map((c) => {
        if (c.type === "response") {
          return {
            type: "response",
            message: c.message,
            references: c.references?.map(reviveContextItem)
          };
        } else {
          return {
            type: "request",
            message: c.message
          };
        }
      })
    };
    const mappedEdits = await this.e.provideMappedEdits(doc, codeBlocks, ctx, token);
    return mappedEdits ? WorkspaceEdit.from(mappedEdits) : null;
  }
};
var AdapterData = class {
  constructor(adapter, extension) {
    this.adapter = adapter;
    this.extension = extension;
  }
};
var $Twc = class _$Twc {
  static {
    this.d = 0;
  }
  constructor(mainContext, g, h, j, k, l, m, n) {
    this.g = g;
    this.h = h;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.f = /* @__PURE__ */ new Map();
    this.e = mainContext.getProxy($xT.MainThreadLanguageFeatures);
  }
  o(selector, extension) {
    return DocumentSelector.from(selector, this.g, extension);
  }
  p(handle) {
    return new $zT(() => {
      this.f.delete(handle);
      this.e.$unregister(handle);
    });
  }
  q() {
    return _$Twc.d++;
  }
  async s(handle, ctor, callback, fallbackValue, tokenToRaceAgainst, doNotLog = false) {
    const data = this.f.get(handle);
    if (!data || !(data.adapter instanceof ctor)) {
      return fallbackValue;
    }
    const t1 = Date.now();
    if (!doNotLog) {
      this.l.trace(`[${data.extension.identifier.value}] INVOKE provider '${callback.toString().replace(/[\r\n]/g, "")}'`);
    }
    const result = callback(data.adapter, data.extension);
    Promise.resolve(result).catch((err) => {
      if (!$kb(err)) {
        this.l.error(`[${data.extension.identifier.value}] provider FAILED`);
        this.l.error(err);
        this.n.onExtensionError(data.extension.identifier, err);
      }
    }).finally(() => {
      if (!doNotLog) {
        this.l.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`);
      }
    });
    if (CancellationToken.isCancellationToken(tokenToRaceAgainst)) {
      return $Jh(result, tokenToRaceAgainst);
    }
    return result;
  }
  t(adapter, extension) {
    const handle = this.q();
    this.f.set(handle, new AdapterData(adapter, extension));
    return handle;
  }
  static u(ext) {
    return ext.displayName || ext.name;
  }
  static w(ext) {
    return ext.identifier.value;
  }
  // --- outline
  registerDocumentSymbolProvider(extension, selector, provider, metadata) {
    const handle = this.t(new DocumentSymbolAdapter(this.h, provider), extension);
    const displayName = metadata && metadata.label || _$Twc.u(extension);
    this.e.$registerDocumentSymbolProvider(handle, this.o(selector, extension), displayName);
    return this.p(handle);
  }
  $provideDocumentSymbols(handle, resource, token) {
    return this.s(handle, DocumentSymbolAdapter, (adapter) => adapter.provideDocumentSymbols(URI.revive(resource), token), void 0, token);
  }
  // --- code lens
  registerCodeLensProvider(extension, selector, provider) {
    const handle = this.q();
    const eventHandle = typeof provider.onDidChangeCodeLenses === "function" ? this.q() : void 0;
    this.f.set(handle, new AdapterData(new CodeLensAdapter(this.h, this.j.converter, provider, extension, this.n, this.l), extension));
    this.e.$registerCodeLensSupport(handle, this.o(selector, extension), eventHandle);
    let result = this.p(handle);
    if (eventHandle !== void 0) {
      const subscription = provider.onDidChangeCodeLenses((_) => this.e.$emitCodeLensEvent(eventHandle));
      result = $zT.from(result, subscription);
    }
    return result;
  }
  $provideCodeLenses(handle, resource, token) {
    return this.s(handle, CodeLensAdapter, (adapter) => adapter.provideCodeLenses(URI.revive(resource), token), void 0, token, resource.scheme === "output");
  }
  $resolveCodeLens(handle, symbol, token) {
    return this.s(handle, CodeLensAdapter, (adapter) => adapter.resolveCodeLens(symbol, token), void 0, void 0, true);
  }
  $releaseCodeLenses(handle, cacheId) {
    this.s(handle, CodeLensAdapter, (adapter) => Promise.resolve(adapter.releaseCodeLenses(cacheId)), void 0, void 0, true);
  }
  // --- declaration
  registerDefinitionProvider(extension, selector, provider) {
    const handle = this.t(new DefinitionAdapter(this.h, provider), extension);
    this.e.$registerDefinitionSupport(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideDefinition(handle, resource, position, token) {
    return this.s(handle, DefinitionAdapter, (adapter) => adapter.provideDefinition(URI.revive(resource), position, token), [], token);
  }
  registerDeclarationProvider(extension, selector, provider) {
    const handle = this.t(new DeclarationAdapter(this.h, provider), extension);
    this.e.$registerDeclarationSupport(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideDeclaration(handle, resource, position, token) {
    return this.s(handle, DeclarationAdapter, (adapter) => adapter.provideDeclaration(URI.revive(resource), position, token), [], token);
  }
  registerImplementationProvider(extension, selector, provider) {
    const handle = this.t(new ImplementationAdapter(this.h, provider), extension);
    this.e.$registerImplementationSupport(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideImplementation(handle, resource, position, token) {
    return this.s(handle, ImplementationAdapter, (adapter) => adapter.provideImplementation(URI.revive(resource), position, token), [], token);
  }
  registerTypeDefinitionProvider(extension, selector, provider) {
    const handle = this.t(new TypeDefinitionAdapter(this.h, provider), extension);
    this.e.$registerTypeDefinitionSupport(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideTypeDefinition(handle, resource, position, token) {
    return this.s(handle, TypeDefinitionAdapter, (adapter) => adapter.provideTypeDefinition(URI.revive(resource), position, token), [], token);
  }
  // --- extra info
  registerHoverProvider(extension, selector, provider, extensionId) {
    const handle = this.t(new HoverAdapter(this.h, provider), extension);
    this.e.$registerHoverProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideHover(handle, resource, position, context, token) {
    return this.s(handle, HoverAdapter, (adapter) => adapter.provideHover(URI.revive(resource), position, context, token), void 0, token);
  }
  $releaseHover(handle, id2) {
    this.s(handle, HoverAdapter, (adapter) => Promise.resolve(adapter.releaseHover(id2)), void 0, void 0);
  }
  // --- debug hover
  registerEvaluatableExpressionProvider(extension, selector, provider, extensionId) {
    const handle = this.t(new EvaluatableExpressionAdapter(this.h, provider), extension);
    this.e.$registerEvaluatableExpressionProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideEvaluatableExpression(handle, resource, position, token) {
    return this.s(handle, EvaluatableExpressionAdapter, (adapter) => adapter.provideEvaluatableExpression(URI.revive(resource), position, token), void 0, token);
  }
  // --- debug inline values
  registerInlineValuesProvider(extension, selector, provider, extensionId) {
    const eventHandle = typeof provider.onDidChangeInlineValues === "function" ? this.q() : void 0;
    const handle = this.t(new InlineValuesAdapter(this.h, provider), extension);
    this.e.$registerInlineValuesProvider(handle, this.o(selector, extension), eventHandle);
    let result = this.p(handle);
    if (eventHandle !== void 0) {
      const subscription = provider.onDidChangeInlineValues((_) => this.e.$emitInlineValuesEvent(eventHandle));
      result = $zT.from(result, subscription);
    }
    return result;
  }
  $provideInlineValues(handle, resource, range, context, token) {
    return this.s(handle, InlineValuesAdapter, (adapter) => adapter.provideInlineValues(URI.revive(resource), range, context, token), void 0, token);
  }
  // --- occurrences
  registerDocumentHighlightProvider(extension, selector, provider) {
    const handle = this.t(new DocumentHighlightAdapter(this.h, provider), extension);
    this.e.$registerDocumentHighlightProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  registerMultiDocumentHighlightProvider(extension, selector, provider) {
    const handle = this.t(new MultiDocumentHighlightAdapter(this.h, provider, this.l), extension);
    this.e.$registerMultiDocumentHighlightProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideDocumentHighlights(handle, resource, position, token) {
    return this.s(handle, DocumentHighlightAdapter, (adapter) => adapter.provideDocumentHighlights(URI.revive(resource), position, token), void 0, token);
  }
  $provideMultiDocumentHighlights(handle, resource, position, otherModels, token) {
    return this.s(handle, MultiDocumentHighlightAdapter, (adapter) => adapter.provideMultiDocumentHighlights(URI.revive(resource), position, otherModels.map((model) => URI.revive(model)), token), void 0, token);
  }
  // --- linked editing
  registerLinkedEditingRangeProvider(extension, selector, provider) {
    const handle = this.t(new LinkedEditingRangeAdapter(this.h, provider), extension);
    this.e.$registerLinkedEditingRangeProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideLinkedEditingRanges(handle, resource, position, token) {
    return this.s(handle, LinkedEditingRangeAdapter, async (adapter) => {
      const res = await adapter.provideLinkedEditingRanges(URI.revive(resource), position, token);
      if (res) {
        return {
          ranges: res.ranges,
          wordPattern: res.wordPattern ? _$Twc.y(res.wordPattern) : void 0
        };
      }
      return void 0;
    }, void 0, token);
  }
  // --- references
  registerReferenceProvider(extension, selector, provider) {
    const handle = this.t(new ReferenceAdapter(this.h, provider), extension);
    this.e.$registerReferenceSupport(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideReferences(handle, resource, position, context, token) {
    return this.s(handle, ReferenceAdapter, (adapter) => adapter.provideReferences(URI.revive(resource), position, context, token), void 0, token);
  }
  // --- code actions
  registerCodeActionProvider(extension, selector, provider, metadata) {
    const store = new $2c();
    const handle = this.t(new CodeActionAdapter(this.h, this.j.converter, this.k, provider, this.l, extension, this.m), extension);
    this.e.$registerCodeActionSupport(handle, this.o(selector, extension), {
      providedKinds: metadata?.providedCodeActionKinds?.map((kind) => kind.value),
      documentation: metadata?.documentation?.map((x) => ({
        kind: x.kind.value,
        command: this.j.converter.toInternal(x.command, store)
      }))
    }, _$Twc.u(extension), _$Twc.w(extension), Boolean(provider.resolveCodeAction));
    store.add(this.p(handle));
    return store;
  }
  $provideCodeActions(handle, resource, rangeOrSelection, context, token) {
    return this.s(handle, CodeActionAdapter, (adapter) => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token), void 0, token);
  }
  $resolveCodeAction(handle, id2, token) {
    return this.s(handle, CodeActionAdapter, (adapter) => adapter.resolveCodeAction(id2, token), {}, void 0);
  }
  $releaseCodeActions(handle, cacheId) {
    this.s(handle, CodeActionAdapter, (adapter) => Promise.resolve(adapter.releaseCodeActions(cacheId)), void 0, void 0);
  }
  // --- formatting
  registerDocumentFormattingEditProvider(extension, selector, provider) {
    const handle = this.t(new DocumentFormattingAdapter(this.h, provider), extension);
    this.e.$registerDocumentFormattingSupport(handle, this.o(selector, extension), extension.identifier, extension.displayName || extension.name);
    return this.p(handle);
  }
  $provideDocumentFormattingEdits(handle, resource, options2, token) {
    return this.s(handle, DocumentFormattingAdapter, (adapter) => adapter.provideDocumentFormattingEdits(URI.revive(resource), options2, token), void 0, token);
  }
  registerDocumentRangeFormattingEditProvider(extension, selector, provider) {
    const canFormatMultipleRanges = typeof provider.provideDocumentRangesFormattingEdits === "function";
    const handle = this.t(new RangeFormattingAdapter(this.h, provider), extension);
    this.e.$registerRangeFormattingSupport(handle, this.o(selector, extension), extension.identifier, extension.displayName || extension.name, canFormatMultipleRanges);
    return this.p(handle);
  }
  $provideDocumentRangeFormattingEdits(handle, resource, range, options2, token) {
    return this.s(handle, RangeFormattingAdapter, (adapter) => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options2, token), void 0, token);
  }
  $provideDocumentRangesFormattingEdits(handle, resource, ranges, options2, token) {
    return this.s(handle, RangeFormattingAdapter, (adapter) => adapter.provideDocumentRangesFormattingEdits(URI.revive(resource), ranges, options2, token), void 0, token);
  }
  registerOnTypeFormattingEditProvider(extension, selector, provider, triggerCharacters) {
    const handle = this.t(new OnTypeFormattingAdapter(this.h, provider), extension);
    this.e.$registerOnTypeFormattingSupport(handle, this.o(selector, extension), triggerCharacters, extension.identifier);
    return this.p(handle);
  }
  $provideOnTypeFormattingEdits(handle, resource, position, ch, options2, token) {
    return this.s(handle, OnTypeFormattingAdapter, (adapter) => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options2, token), void 0, token);
  }
  // --- navigate types
  registerWorkspaceSymbolProvider(extension, provider) {
    const handle = this.t(new NavigateTypeAdapter(provider, this.l), extension);
    this.e.$registerNavigateTypeSupport(handle, typeof provider.resolveWorkspaceSymbol === "function");
    return this.p(handle);
  }
  $provideWorkspaceSymbols(handle, search, token) {
    return this.s(handle, NavigateTypeAdapter, (adapter) => adapter.provideWorkspaceSymbols(search, token), { symbols: [] }, token);
  }
  $resolveWorkspaceSymbol(handle, symbol, token) {
    return this.s(handle, NavigateTypeAdapter, (adapter) => adapter.resolveWorkspaceSymbol(symbol, token), void 0, void 0);
  }
  $releaseWorkspaceSymbols(handle, id2) {
    this.s(handle, NavigateTypeAdapter, (adapter) => adapter.releaseWorkspaceSymbols(id2), void 0, void 0);
  }
  // --- rename
  registerRenameProvider(extension, selector, provider) {
    const handle = this.t(new RenameAdapter(this.h, provider, this.l), extension);
    this.e.$registerRenameSupport(handle, this.o(selector, extension), RenameAdapter.supportsResolving(provider));
    return this.p(handle);
  }
  $provideRenameEdits(handle, resource, position, newName, token) {
    return this.s(handle, RenameAdapter, (adapter) => adapter.provideRenameEdits(URI.revive(resource), position, newName, token), void 0, token);
  }
  $resolveRenameLocation(handle, resource, position, token) {
    return this.s(handle, RenameAdapter, (adapter) => adapter.resolveRenameLocation(URI.revive(resource), position, token), void 0, token);
  }
  registerNewSymbolNamesProvider(extension, selector, provider) {
    const handle = this.t(new NewSymbolNamesAdapter(this.h, provider, this.l), extension);
    this.e.$registerNewSymbolNamesProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $supportsAutomaticNewSymbolNamesTriggerKind(handle) {
    return this.s(handle, NewSymbolNamesAdapter, (adapter) => adapter.supportsAutomaticNewSymbolNamesTriggerKind(), false, void 0);
  }
  $provideNewSymbolNames(handle, resource, range, triggerKind, token) {
    return this.s(handle, NewSymbolNamesAdapter, (adapter) => adapter.provideNewSymbolNames(URI.revive(resource), range, triggerKind, token), void 0, token);
  }
  //#region semantic coloring
  registerDocumentSemanticTokensProvider(extension, selector, provider, legend) {
    const handle = this.t(new DocumentSemanticTokensAdapter(this.h, provider), extension);
    const eventHandle = typeof provider.onDidChangeSemanticTokens === "function" ? this.q() : void 0;
    this.e.$registerDocumentSemanticTokensProvider(handle, this.o(selector, extension), legend, eventHandle);
    let result = this.p(handle);
    if (eventHandle) {
      const subscription = provider.onDidChangeSemanticTokens((_) => this.e.$emitDocumentSemanticTokensEvent(eventHandle));
      result = $zT.from(result, subscription);
    }
    return result;
  }
  $provideDocumentSemanticTokens(handle, resource, previousResultId, token) {
    return this.s(handle, DocumentSemanticTokensAdapter, (adapter) => adapter.provideDocumentSemanticTokens(URI.revive(resource), previousResultId, token), null, token);
  }
  $releaseDocumentSemanticTokens(handle, semanticColoringResultId) {
    this.s(handle, DocumentSemanticTokensAdapter, (adapter) => adapter.releaseDocumentSemanticColoring(semanticColoringResultId), void 0, void 0);
  }
  registerDocumentRangeSemanticTokensProvider(extension, selector, provider, legend) {
    const handle = this.t(new DocumentRangeSemanticTokensAdapter(this.h, provider), extension);
    this.e.$registerDocumentRangeSemanticTokensProvider(handle, this.o(selector, extension), legend);
    return this.p(handle);
  }
  $provideDocumentRangeSemanticTokens(handle, resource, range, token) {
    return this.s(handle, DocumentRangeSemanticTokensAdapter, (adapter) => adapter.provideDocumentRangeSemanticTokens(URI.revive(resource), range, token), null, token);
  }
  //#endregion
  // --- suggestion
  registerCompletionItemProvider(extension, selector, provider, triggerCharacters) {
    const handle = this.t(new CompletionsAdapter(this.h, this.j.converter, provider, this.m, extension), extension);
    this.e.$registerCompletionsProvider(handle, this.o(selector, extension), triggerCharacters, CompletionsAdapter.supportsResolving(provider), extension.identifier);
    return this.p(handle);
  }
  $provideCompletionItems(handle, resource, position, context, token) {
    return this.s(handle, CompletionsAdapter, (adapter) => adapter.provideCompletionItems(URI.revive(resource), position, context, token), void 0, token);
  }
  $resolveCompletionItem(handle, id2, token) {
    return this.s(handle, CompletionsAdapter, (adapter) => adapter.resolveCompletionItem(id2, token), void 0, token);
  }
  $releaseCompletionItems(handle, id2) {
    this.s(handle, CompletionsAdapter, (adapter) => adapter.releaseCompletionItems(id2), void 0, void 0);
  }
  // --- ghost test
  registerInlineCompletionsProvider(extension, selector, provider, metadata) {
    const adapter = new InlineCompletionAdapter(extension, this.h, provider, this.j.converter);
    const handle = this.t(adapter, extension);
    this.e.$registerInlineCompletionsSupport(handle, this.o(selector, extension), adapter.supportsHandleEvents, $5z.toKey(extension.identifier.value), metadata?.yieldTo?.map((extId) => $5z.toKey(extId)) || []);
    return this.p(handle);
  }
  $provideInlineCompletions(handle, resource, position, context, token) {
    return this.s(handle, InlineCompletionAdapterBase, (adapter) => adapter.provideInlineCompletions(URI.revive(resource), position, context, token), void 0, token);
  }
  $provideInlineEditsForRange(handle, resource, range, context, token) {
    return this.s(handle, InlineCompletionAdapterBase, (adapter) => adapter.provideInlineEditsForRange(URI.revive(resource), range, context, token), void 0, token);
  }
  $handleInlineCompletionDidShow(handle, pid, idx, updatedInsertText) {
    this.s(handle, InlineCompletionAdapterBase, async (adapter) => {
      adapter.handleDidShowCompletionItem(pid, idx, updatedInsertText);
    }, void 0, void 0);
  }
  $handleInlineCompletionPartialAccept(handle, pid, idx, acceptedCharacters, info) {
    this.s(handle, InlineCompletionAdapterBase, async (adapter) => {
      adapter.handlePartialAccept(pid, idx, acceptedCharacters, info);
    }, void 0, void 0);
  }
  $freeInlineCompletionsList(handle, pid) {
    this.s(handle, InlineCompletionAdapterBase, async (adapter) => {
      adapter.disposeCompletions(pid);
    }, void 0, void 0);
  }
  // --- inline edit
  registerInlineEditProvider(extension, selector, provider) {
    const adapter = new InlineEditAdapter(extension, this.h, provider, this.j.converter);
    const handle = this.t(adapter, extension);
    this.e.$registerInlineEditProvider(handle, this.o(selector, extension), extension.identifier);
    return this.p(handle);
  }
  $provideInlineEdit(handle, resource, context, token) {
    return this.s(handle, InlineEditAdapter, (adapter) => adapter.provideInlineEdits(URI.revive(resource), context, token), void 0, token);
  }
  $freeInlineEdit(handle, pid) {
    this.s(handle, InlineEditAdapter, async (adapter) => {
      adapter.disposeEdit(pid);
    }, void 0, void 0);
  }
  // --- parameter hints
  registerSignatureHelpProvider(extension, selector, provider, metadataOrTriggerChars) {
    const metadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars;
    const handle = this.t(new SignatureHelpAdapter(this.h, provider), extension);
    this.e.$registerSignatureHelpProvider(handle, this.o(selector, extension), metadata);
    return this.p(handle);
  }
  $provideSignatureHelp(handle, resource, position, context, token) {
    return this.s(handle, SignatureHelpAdapter, (adapter) => adapter.provideSignatureHelp(URI.revive(resource), position, context, token), void 0, token);
  }
  $releaseSignatureHelp(handle, id2) {
    this.s(handle, SignatureHelpAdapter, (adapter) => adapter.releaseSignatureHelp(id2), void 0, void 0);
  }
  // --- inline hints
  registerInlayHintsProvider(extension, selector, provider) {
    const eventHandle = typeof provider.onDidChangeInlayHints === "function" ? this.q() : void 0;
    const handle = this.t(new InlayHintsAdapter(this.h, this.j.converter, provider, this.l, extension), extension);
    this.e.$registerInlayHintsProvider(handle, this.o(selector, extension), typeof provider.resolveInlayHint === "function", eventHandle, _$Twc.u(extension));
    let result = this.p(handle);
    if (eventHandle !== void 0) {
      const subscription = provider.onDidChangeInlayHints((uri) => this.e.$emitInlayHintsEvent(eventHandle));
      result = $zT.from(result, subscription);
    }
    return result;
  }
  $provideInlayHints(handle, resource, range, token) {
    return this.s(handle, InlayHintsAdapter, (adapter) => adapter.provideInlayHints(URI.revive(resource), range, token), void 0, token);
  }
  $resolveInlayHint(handle, id2, token) {
    return this.s(handle, InlayHintsAdapter, (adapter) => adapter.resolveInlayHint(id2, token), void 0, token);
  }
  $releaseInlayHints(handle, id2) {
    this.s(handle, InlayHintsAdapter, (adapter) => adapter.releaseHints(id2), void 0, void 0);
  }
  // --- links
  registerDocumentLinkProvider(extension, selector, provider) {
    const handle = this.t(new LinkProviderAdapter(this.h, provider), extension);
    this.e.$registerDocumentLinkProvider(handle, this.o(selector, extension), typeof provider.resolveDocumentLink === "function");
    return this.p(handle);
  }
  $provideDocumentLinks(handle, resource, token) {
    return this.s(handle, LinkProviderAdapter, (adapter) => adapter.provideLinks(URI.revive(resource), token), void 0, token, resource.scheme === "output");
  }
  $resolveDocumentLink(handle, id2, token) {
    return this.s(handle, LinkProviderAdapter, (adapter) => adapter.resolveLink(id2, token), void 0, void 0, true);
  }
  $releaseDocumentLinks(handle, id2) {
    this.s(handle, LinkProviderAdapter, (adapter) => adapter.releaseLinks(id2), void 0, void 0, true);
  }
  registerColorProvider(extension, selector, provider) {
    const handle = this.t(new ColorProviderAdapter(this.h, provider), extension);
    this.e.$registerDocumentColorProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideDocumentColors(handle, resource, token) {
    return this.s(handle, ColorProviderAdapter, (adapter) => adapter.provideColors(URI.revive(resource), token), [], token);
  }
  $provideColorPresentations(handle, resource, colorInfo, token) {
    return this.s(handle, ColorProviderAdapter, (adapter) => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token), void 0, token);
  }
  registerFoldingRangeProvider(extension, selector, provider) {
    const handle = this.q();
    const eventHandle = typeof provider.onDidChangeFoldingRanges === "function" ? this.q() : void 0;
    this.f.set(handle, new AdapterData(new FoldingProviderAdapter(this.h, provider), extension));
    this.e.$registerFoldingRangeProvider(handle, this.o(selector, extension), extension.identifier, eventHandle);
    let result = this.p(handle);
    if (eventHandle !== void 0) {
      const subscription = provider.onDidChangeFoldingRanges(() => this.e.$emitFoldingRangeEvent(eventHandle));
      result = $zT.from(result, subscription);
    }
    return result;
  }
  $provideFoldingRanges(handle, resource, context, token) {
    return this.s(handle, FoldingProviderAdapter, (adapter) => adapter.provideFoldingRanges(URI.revive(resource), context, token), void 0, token);
  }
  // --- smart select
  registerSelectionRangeProvider(extension, selector, provider) {
    const handle = this.t(new SelectionRangeAdapter(this.h, provider, this.l), extension);
    this.e.$registerSelectionRangeProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $provideSelectionRanges(handle, resource, positions, token) {
    return this.s(handle, SelectionRangeAdapter, (adapter) => adapter.provideSelectionRanges(URI.revive(resource), positions, token), [], token);
  }
  // --- call hierarchy
  registerCallHierarchyProvider(extension, selector, provider) {
    const handle = this.t(new CallHierarchyAdapter(this.h, provider), extension);
    this.e.$registerCallHierarchyProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $prepareCallHierarchy(handle, resource, position, token) {
    return this.s(handle, CallHierarchyAdapter, (adapter) => Promise.resolve(adapter.prepareSession(URI.revive(resource), position, token)), void 0, token);
  }
  $provideCallHierarchyIncomingCalls(handle, sessionId, itemId, token) {
    return this.s(handle, CallHierarchyAdapter, (adapter) => adapter.provideCallsTo(sessionId, itemId, token), void 0, token);
  }
  $provideCallHierarchyOutgoingCalls(handle, sessionId, itemId, token) {
    return this.s(handle, CallHierarchyAdapter, (adapter) => adapter.provideCallsFrom(sessionId, itemId, token), void 0, token);
  }
  $releaseCallHierarchy(handle, sessionId) {
    this.s(handle, CallHierarchyAdapter, (adapter) => Promise.resolve(adapter.releaseSession(sessionId)), void 0, void 0);
  }
  // --- type hierarchy
  registerTypeHierarchyProvider(extension, selector, provider) {
    const handle = this.t(new TypeHierarchyAdapter(this.h, provider), extension);
    this.e.$registerTypeHierarchyProvider(handle, this.o(selector, extension));
    return this.p(handle);
  }
  $prepareTypeHierarchy(handle, resource, position, token) {
    return this.s(handle, TypeHierarchyAdapter, (adapter) => Promise.resolve(adapter.prepareSession(URI.revive(resource), position, token)), void 0, token);
  }
  $provideTypeHierarchySupertypes(handle, sessionId, itemId, token) {
    return this.s(handle, TypeHierarchyAdapter, (adapter) => adapter.provideSupertypes(sessionId, itemId, token), void 0, token);
  }
  $provideTypeHierarchySubtypes(handle, sessionId, itemId, token) {
    return this.s(handle, TypeHierarchyAdapter, (adapter) => adapter.provideSubtypes(sessionId, itemId, token), void 0, token);
  }
  $releaseTypeHierarchy(handle, sessionId) {
    this.s(handle, TypeHierarchyAdapter, (adapter) => Promise.resolve(adapter.releaseSession(sessionId)), void 0, void 0);
  }
  // --- Document on drop
  registerDocumentOnDropEditProvider(extension, selector, provider, metadata) {
    const handle = this.q();
    this.f.set(handle, new AdapterData(new DocumentDropEditAdapter(this.e, this.h, provider, handle, extension), extension));
    this.e.$registerDocumentOnDropEditProvider(handle, this.o(selector, extension), $zN(extension, "documentPaste") && metadata ? {
      supportsResolve: !!provider.resolveDocumentDropEdit,
      dropMimeTypes: metadata.dropMimeTypes,
      providedDropKinds: metadata.providedDropEditKinds?.map((x) => x.value)
    } : void 0);
    return this.p(handle);
  }
  $provideDocumentOnDropEdits(handle, requestId, resource, position, dataTransferDto, token) {
    return this.s(handle, DocumentDropEditAdapter, (adapter) => Promise.resolve(adapter.provideDocumentOnDropEdits(requestId, URI.revive(resource), position, dataTransferDto, token)), void 0, void 0);
  }
  $resolveDropEdit(handle, id2, token) {
    return this.s(handle, DocumentDropEditAdapter, (adapter) => adapter.resolveDropEdit(id2, token), {}, void 0);
  }
  $releaseDocumentOnDropEdits(handle, cacheId) {
    this.s(handle, DocumentDropEditAdapter, (adapter) => Promise.resolve(adapter.releaseDropEdits(cacheId)), void 0, void 0);
  }
  // --- mapped edits
  registerMappedEditsProvider(extension, selector, provider) {
    const handle = this.t(new MappedEditsAdapter(this.h, provider), extension);
    this.e.$registerMappedEditsProvider(handle, this.o(selector, extension), extension.displayName ?? extension.name);
    return this.p(handle);
  }
  $provideMappedEdits(handle, document2, codeBlocks, context, token) {
    return this.s(handle, MappedEditsAdapter, (adapter) => Promise.resolve(adapter.provideMappedEdits(document2, codeBlocks, context, token)), null, token);
  }
  // --- copy/paste actions
  registerDocumentPasteEditProvider(extension, selector, provider, metadata) {
    const handle = this.q();
    this.f.set(handle, new AdapterData(new DocumentPasteEditProvider(this.e, this.h, provider, handle, extension), extension));
    this.e.$registerPasteEditProvider(handle, this.o(selector, extension), {
      supportsCopy: !!provider.prepareDocumentPaste,
      supportsPaste: !!provider.provideDocumentPasteEdits,
      supportsResolve: !!provider.resolveDocumentPasteEdit,
      providedPasteEditKinds: metadata.providedPasteEditKinds?.map((x) => x.value),
      copyMimeTypes: metadata.copyMimeTypes,
      pasteMimeTypes: metadata.pasteMimeTypes
    });
    return this.p(handle);
  }
  $prepareDocumentPaste(handle, resource, ranges, dataTransfer, token) {
    return this.s(handle, DocumentPasteEditProvider, (adapter) => adapter.prepareDocumentPaste(URI.revive(resource), ranges, dataTransfer, token), void 0, token);
  }
  $providePasteEdits(handle, requestId, resource, ranges, dataTransferDto, context, token) {
    return this.s(handle, DocumentPasteEditProvider, (adapter) => adapter.providePasteEdits(requestId, URI.revive(resource), ranges, dataTransferDto, context, token), void 0, token);
  }
  $resolvePasteEdit(handle, id2, token) {
    return this.s(handle, DocumentPasteEditProvider, (adapter) => adapter.resolvePasteEdit(id2, token), {}, void 0);
  }
  $releasePasteEdits(handle, cacheId) {
    this.s(handle, DocumentPasteEditProvider, (adapter) => Promise.resolve(adapter.releasePasteEdits(cacheId)), void 0, void 0);
  }
  // --- configuration
  static y(regExp) {
    return {
      pattern: regExp.source,
      flags: regExp.flags
    };
  }
  static z(indentationRule) {
    return {
      decreaseIndentPattern: _$Twc.y(indentationRule.decreaseIndentPattern),
      increaseIndentPattern: _$Twc.y(indentationRule.increaseIndentPattern),
      indentNextLinePattern: indentationRule.indentNextLinePattern ? _$Twc.y(indentationRule.indentNextLinePattern) : void 0,
      unIndentedLinePattern: indentationRule.unIndentedLinePattern ? _$Twc.y(indentationRule.unIndentedLinePattern) : void 0
    };
  }
  static B(onEnterRule) {
    return {
      beforeText: _$Twc.y(onEnterRule.beforeText),
      afterText: onEnterRule.afterText ? _$Twc.y(onEnterRule.afterText) : void 0,
      previousLineText: onEnterRule.previousLineText ? _$Twc.y(onEnterRule.previousLineText) : void 0,
      action: onEnterRule.action
    };
  }
  static C(onEnterRules) {
    return onEnterRules.map(_$Twc.B);
  }
  static D(autoClosingPair) {
    return {
      open: autoClosingPair.open,
      close: autoClosingPair.close,
      notIn: autoClosingPair.notIn ? autoClosingPair.notIn.map((v) => SyntaxTokenType.toString(v)) : void 0
    };
  }
  static E(autoClosingPairs) {
    return autoClosingPairs.map(_$Twc.D);
  }
  setLanguageConfiguration(extension, languageId, configuration) {
    const { wordPattern } = configuration;
    if (wordPattern && $Kf(wordPattern)) {
      throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`);
    }
    if (wordPattern) {
      this.h.setWordDefinitionFor(languageId, wordPattern);
    } else {
      this.h.setWordDefinitionFor(languageId, void 0);
    }
    if (configuration.__electricCharacterSupport) {
      this.m.report("LanguageConfiguration.__electricCharacterSupport", extension, `Do not use.`);
    }
    if (configuration.__characterPairSupport) {
      this.m.report("LanguageConfiguration.__characterPairSupport", extension, `Do not use.`);
    }
    const handle = this.q();
    const serializedConfiguration = {
      comments: configuration.comments,
      brackets: configuration.brackets,
      wordPattern: configuration.wordPattern ? _$Twc.y(configuration.wordPattern) : void 0,
      indentationRules: configuration.indentationRules ? _$Twc.z(configuration.indentationRules) : void 0,
      onEnterRules: configuration.onEnterRules ? _$Twc.C(configuration.onEnterRules) : void 0,
      __electricCharacterSupport: configuration.__electricCharacterSupport,
      __characterPairSupport: configuration.__characterPairSupport,
      autoClosingPairs: configuration.autoClosingPairs ? _$Twc.E(configuration.autoClosingPairs) : void 0
    };
    this.e.$setLanguageConfiguration(handle, languageId, serializedConfiguration);
    return this.p(handle);
  }
  $setWordDefinitions(wordDefinitions) {
    for (const wordDefinition of wordDefinitions) {
      this.h.setWordDefinitionFor(wordDefinition.languageId, new RegExp(wordDefinition.regexSource, wordDefinition.regexFlags));
    }
  }
};

// out-build/vs/workbench/contrib/chat/common/languageModelToolsService.js
function $lO(obj) {
  return typeof obj === "object" && typeof obj.sessionId === "string";
}
var $mO = $Qk("ILanguageModelToolsService");

// out-build/vs/workbench/api/common/extHostLanguageModelTools.js
var $qyc = class {
  constructor(mainContext) {
    this.a = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadLanguageModelTools);
    this.b.$getTools().then((tools) => {
      for (const tool of tools) {
        this.d.set(tool.id, $cu(tool));
      }
    });
  }
  async $countTokensForInvocation(callId, input, token) {
    const fn = this.c.get(callId);
    if (!fn) {
      throw new Error(`Tool invocation call ${callId} not found`);
    }
    return await fn(input, token);
  }
  async invokeTool(toolId, options2, token) {
    const callId = $ps();
    if (options2.tokenizationOptions) {
      this.c.set(callId, options2.tokenizationOptions.countTokens);
    }
    if (options2.toolInvocationToken && !$lO(options2.toolInvocationToken)) {
      throw new Error(`Invalid tool invocation token`);
    }
    try {
      const result = await this.b.$invokeTool({
        toolId,
        callId,
        parameters: options2.input,
        tokenBudget: options2.tokenizationOptions?.tokenBudget,
        context: options2.toolInvocationToken
      }, token);
      return LanguageModelToolResult.to(result);
    } finally {
      this.c.delete(callId);
    }
  }
  $onDidChangeTools(tools) {
    this.d.clear();
    for (const tool of tools) {
      this.d.set(tool.id, tool);
    }
  }
  get tools() {
    return Array.from(this.d.values()).map((tool) => LanguageModelToolDescription.to(tool));
  }
  async $invokeTool(dto, token) {
    const item = this.a.get(dto.toolId);
    if (!item) {
      throw new Error(`Unknown tool ${dto.toolId}`);
    }
    const options2 = { input: dto.parameters, toolInvocationToken: dto.context };
    if (dto.tokenBudget !== void 0) {
      options2.tokenizationOptions = {
        tokenBudget: dto.tokenBudget,
        countTokens: this.c.get(dto.callId) || ((value, token2 = CancellationToken.None) => this.b.$countTokensForInvocation(dto.callId, value, token2))
      };
    }
    const extensionResult = await $Ih(Promise.resolve(item.tool.invoke(options2, token)), token);
    if (!extensionResult) {
      throw new $lb();
    }
    return LanguageModelToolResult.from(extensionResult);
  }
  async $prepareToolInvocation(toolId, input, token) {
    const item = this.a.get(toolId);
    if (!item) {
      throw new Error(`Unknown tool ${toolId}`);
    }
    if (!item.tool.prepareInvocation) {
      return void 0;
    }
    const options2 = { input };
    const result = await item.tool.prepareInvocation(options2, token);
    if (!result) {
      return void 0;
    }
    return {
      confirmationMessages: result.confirmationMessages ? {
        title: result.confirmationMessages.title,
        message: typeof result.confirmationMessages.message === "string" ? result.confirmationMessages.message : MarkdownString.from(result.confirmationMessages.message)
      } : void 0,
      invocationMessage: typeof result.invocationMessage === "string" ? result.invocationMessage : result.invocationMessage ? MarkdownString.from(result.invocationMessage) : void 0
    };
  }
  registerTool(extension, id2, tool) {
    this.a.set(id2, { extension, tool });
    this.b.$registerTool(id2);
    return $1c(() => {
      this.a.delete(id2);
      this.b.$unregisterTool(id2);
    });
  }
};

// out-build/vs/workbench/api/common/extHostLanguages.js
var $ryc = class {
  constructor(mainContext, c, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.b = [];
    this.f = 0;
    this.g = /* @__PURE__ */ new Set();
    this.a = mainContext.getProxy($xT.MainThreadLanguages);
  }
  $acceptLanguageIds(ids) {
    this.b = ids;
  }
  async getLanguages() {
    return this.b.slice(0);
  }
  async changeLanguage(uri, languageId) {
    await this.a.$changeLanguage(uri, languageId);
    const data = this.c.getDocumentData(uri);
    if (!data) {
      throw new Error(`document '${uri.toString()}' NOT found`);
    }
    return data.document;
  }
  async tokenAtPosition(document2, position) {
    const versionNow = document2.version;
    const pos = Position.from(position);
    const info = await this.a.$tokensAtPosition(document2.uri, pos);
    const defaultRange = {
      type: StandardTokenType.Other,
      range: document2.getWordRangeAtPosition(position) ?? new $BT(position.line, position.character, position.line, position.character)
    };
    if (!info) {
      return defaultRange;
    }
    const result = {
      range: Range.to(info.range),
      type: TokenType2.to(info.type)
    };
    if (!result.range.contains(position)) {
      return defaultRange;
    }
    if (versionNow !== document2.version) {
      return defaultRange;
    }
    return result;
  }
  createLanguageStatusItem(extension, id2, selector) {
    const handle = this.f++;
    const proxy = this.a;
    const ids = this.g;
    const fullyQualifiedId = `${extension.identifier.value}/${id2}`;
    if (ids.has(fullyQualifiedId)) {
      throw new Error(`LanguageStatusItem with id '${id2}' ALREADY exists`);
    }
    ids.add(fullyQualifiedId);
    const data = {
      selector,
      id: id2,
      name: extension.displayName ?? extension.name,
      severity: LanguageStatusSeverity.Information,
      command: void 0,
      text: "",
      detail: "",
      busy: false
    };
    let soonHandle;
    const commandDisposables = new $2c();
    const updateAsync = () => {
      soonHandle?.dispose();
      if (!ids.has(fullyQualifiedId)) {
        console.warn(`LanguageStatusItem (${id2}) from ${extension.identifier.value} has been disposed and CANNOT be updated anymore`);
        return;
      }
      soonHandle = $Xh(() => {
        commandDisposables.clear();
        this.a.$setLanguageStatus(handle, {
          id: fullyQualifiedId,
          name: data.name ?? extension.displayName ?? extension.name,
          source: extension.displayName ?? extension.name,
          selector: DocumentSelector.from(data.selector, this.e),
          label: data.text,
          detail: data.detail ?? "",
          severity: data.severity === LanguageStatusSeverity.Error ? severity_default.Error : data.severity === LanguageStatusSeverity.Warning ? severity_default.Warning : severity_default.Info,
          command: data.command && this.d.toInternal(data.command, commandDisposables),
          accessibilityInfo: data.accessibilityInformation,
          busy: data.busy
        });
      }, 0);
    };
    const result = {
      dispose() {
        commandDisposables.dispose();
        soonHandle?.dispose();
        proxy.$removeLanguageStatus(handle);
        ids.delete(fullyQualifiedId);
      },
      get id() {
        return data.id;
      },
      get name() {
        return data.name;
      },
      set name(value) {
        data.name = value;
        updateAsync();
      },
      get selector() {
        return data.selector;
      },
      set selector(value) {
        data.selector = value;
        updateAsync();
      },
      get text() {
        return data.text;
      },
      set text(value) {
        data.text = value;
        updateAsync();
      },
      set text2(value) {
        $AN(extension, "languageStatusText");
        data.text = value;
        updateAsync();
      },
      get text2() {
        $AN(extension, "languageStatusText");
        return data.text;
      },
      get detail() {
        return data.detail;
      },
      set detail(value) {
        data.detail = value;
        updateAsync();
      },
      get severity() {
        return data.severity;
      },
      set severity(value) {
        data.severity = value;
        updateAsync();
      },
      get accessibilityInformation() {
        return data.accessibilityInformation;
      },
      set accessibilityInformation(value) {
        data.accessibilityInformation = value;
        updateAsync();
      },
      get command() {
        return data.command;
      },
      set command(value) {
        data.command = value;
        updateAsync();
      },
      get busy() {
        return data.busy;
      },
      set busy(value) {
        data.busy = value;
        updateAsync();
      }
    };
    updateAsync();
    return result;
  }
};

// out-build/vs/workbench/api/common/extHostMessageService.js
function isMessageItem(item) {
  return item && item.title;
}
var $syc = class $syc2 {
  constructor(mainContext, b) {
    this.b = b;
    this.a = mainContext.getProxy($xT.MainThreadMessageService);
  }
  showMessage(extension, severity, message, optionsOrFirstItem, rest) {
    const options2 = {
      source: { identifier: extension.identifier, label: extension.displayName || extension.name }
    };
    let items;
    if (typeof optionsOrFirstItem === "string" || isMessageItem(optionsOrFirstItem)) {
      items = [optionsOrFirstItem, ...rest];
    } else {
      options2.modal = optionsOrFirstItem?.modal;
      options2.useCustom = optionsOrFirstItem?.useCustom;
      options2.detail = optionsOrFirstItem?.detail;
      items = rest;
    }
    if (options2.useCustom) {
      $AN(extension, "resolvers");
    }
    const commands = [];
    let hasCloseAffordance = false;
    for (let handle = 0; handle < items.length; handle++) {
      const command = items[handle];
      if (typeof command === "string") {
        commands.push({ title: command, handle, isCloseAffordance: false });
      } else if (typeof command === "object") {
        const { title, isCloseAffordance } = command;
        commands.push({ title, isCloseAffordance: !!isCloseAffordance, handle });
        if (isCloseAffordance) {
          if (hasCloseAffordance) {
            this.b.warn(`[${extension.identifier}] Only one message item can have 'isCloseAffordance':`, command);
          } else {
            hasCloseAffordance = true;
          }
        }
      } else {
        this.b.warn(`[${extension.identifier}] Invalid message item:`, command);
      }
    }
    return this.a.$showMessage(severity, message, options2, commands).then((handle) => {
      if (typeof handle === "number") {
        return items[handle];
      }
      return void 0;
    });
  }
};
$syc = __decorate([
  __param(1, $wn)
], $syc);

// out-build/vs/workbench/api/common/extHostNotebookDocument.js
var RawContentChangeEvent = class {
  constructor(start, deletedCount, deletedItems, items) {
    this.start = start;
    this.deletedCount = deletedCount;
    this.deletedItems = deletedItems;
    this.items = items;
  }
  asApiEvent() {
    return {
      range: new $6U(this.start, this.start + this.deletedCount),
      addedCells: this.items.map((cell) => cell.apiCell),
      removedCells: this.deletedItems
    };
  }
};
var $0xc = class {
  static asModelAddData(cell) {
    return {
      EOL: cell.eol,
      lines: cell.source,
      languageId: cell.language,
      uri: cell.uri,
      isDirty: false,
      versionId: 1
    };
  }
  constructor(notebook, h, j) {
    this.notebook = notebook;
    this.h = h;
    this.j = j;
    this.handle = j.handle;
    this.uri = URI.revive(j.uri);
    this.cellKind = j.cellKind;
    this.a = j.outputs.map(NotebookCellOutput.to);
    this.e = j.internalMetadata ?? {};
    this.b = Object.freeze(j.metadata ?? {});
    this.d = Object.freeze(NotebookCellExecutionSummary.to(j.internalMetadata ?? {}));
  }
  get internalMetadata() {
    return this.e;
  }
  get apiCell() {
    if (!this.f) {
      const that = this;
      const data = this.h.getDocument(this.uri);
      if (!data) {
        throw new Error(`MISSING extHostDocument for notebook cell: ${this.uri}`);
      }
      const apiCell = {
        get index() {
          return that.notebook.getCellIndex(that);
        },
        notebook: that.notebook.apiNotebook,
        kind: NotebookCellKind2.to(this.j.cellKind),
        document: data.document,
        get mime() {
          return that.g;
        },
        set mime(value) {
          that.g = value;
        },
        get outputs() {
          return that.a.slice(0);
        },
        get metadata() {
          return that.b;
        },
        get executionSummary() {
          return that.d;
        }
      };
      this.f = Object.freeze(apiCell);
    }
    return this.f;
  }
  setOutputs(newOutputs) {
    this.a = newOutputs.map(NotebookCellOutput.to);
  }
  setOutputItems(outputId, append, newOutputItems) {
    const newItems = newOutputItems.map(NotebookCellOutputItem.to);
    const output = this.a.find((op) => op.id === outputId);
    if (output) {
      if (!append) {
        output.items.length = 0;
      }
      output.items.push(...newItems);
      if (output.items.length > 1 && output.items.every((item) => $tM(item.mime))) {
        const mimeOutputs = /* @__PURE__ */ new Map();
        const mimeTypes = [];
        output.items.forEach((item) => {
          let items;
          if (mimeOutputs.has(item.mime)) {
            items = mimeOutputs.get(item.mime);
          } else {
            items = [];
            mimeOutputs.set(item.mime, items);
            mimeTypes.push(item.mime);
          }
          items.push(item.data);
        });
        output.items.length = 0;
        mimeTypes.forEach((mime) => {
          const compressed = $uM(mimeOutputs.get(mime));
          output.items.push({
            mime,
            data: compressed.data.buffer
          });
        });
      }
    }
  }
  setMetadata(newMetadata) {
    this.b = Object.freeze(newMetadata);
  }
  setInternalMetadata(newInternalMetadata) {
    this.e = newInternalMetadata;
    this.d = Object.freeze(NotebookCellExecutionSummary.to(newInternalMetadata));
  }
  setMime(newMime) {
  }
};
var $$xc = class _$$xc {
  static {
    this.a = 0;
  }
  constructor(k, l, m, uri, data) {
    this.k = k;
    this.l = l;
    this.m = m;
    this.uri = uri;
    this.handle = _$$xc.a++;
    this.b = [];
    this.g = 0;
    this.h = false;
    this.j = false;
    this.d = data.viewType;
    this.f = Object.freeze(data.metadata ?? /* @__PURE__ */ Object.create(null));
    this.r([[0, 0, data.cells]], true, void 0);
    this.g = data.versionId;
  }
  dispose() {
    this.j = true;
  }
  get versionId() {
    return this.g;
  }
  get apiNotebook() {
    if (!this.e) {
      const that = this;
      const apiObject = {
        get uri() {
          return that.uri;
        },
        get version() {
          return that.g;
        },
        get notebookType() {
          return that.d;
        },
        get isDirty() {
          return that.h;
        },
        get isUntitled() {
          return that.uri.scheme === Schemas.untitled;
        },
        get isClosed() {
          return that.j;
        },
        get metadata() {
          return that.f;
        },
        get cellCount() {
          return that.b.length;
        },
        cellAt(index) {
          index = that.n(index);
          return that.b[index].apiCell;
        },
        getCells(range) {
          const cells = range ? that.p(range) : that.b;
          return cells.map((cell) => cell.apiCell);
        },
        save() {
          return that.q();
        },
        [Symbol.for("debug.description")]() {
          return `NotebookDocument(${this.uri.toString()})`;
        }
      };
      this.e = Object.freeze(apiObject);
    }
    return this.e;
  }
  acceptDocumentPropertiesChanged(data) {
    if (data.metadata) {
      this.f = Object.freeze({ ...this.f, ...data.metadata });
    }
  }
  acceptDirty(isDirty) {
    this.h = isDirty;
  }
  acceptModelChanged(event, isDirty, newMetadata) {
    this.g = event.versionId;
    this.h = isDirty;
    this.acceptDocumentPropertiesChanged({ metadata: newMetadata });
    const result = {
      notebook: this.apiNotebook,
      metadata: newMetadata,
      cellChanges: [],
      contentChanges: []
    };
    const relaxedCellChanges = [];
    for (const rawEvent of event.rawEvents) {
      if (rawEvent.kind === NotebookCellsChangeType.ModelChange) {
        this.r(rawEvent.changes, false, result.contentChanges);
      } else if (rawEvent.kind === NotebookCellsChangeType.Move) {
        this.s(rawEvent.index, rawEvent.length, rawEvent.newIdx, result.contentChanges);
      } else if (rawEvent.kind === NotebookCellsChangeType.Output) {
        this.t(rawEvent.index, rawEvent.outputs);
        relaxedCellChanges.push({ cell: this.b[rawEvent.index].apiCell, outputs: this.b[rawEvent.index].apiCell.outputs });
      } else if (rawEvent.kind === NotebookCellsChangeType.OutputItem) {
        this.u(rawEvent.index, rawEvent.outputId, rawEvent.append, rawEvent.outputItems);
        relaxedCellChanges.push({ cell: this.b[rawEvent.index].apiCell, outputs: this.b[rawEvent.index].apiCell.outputs });
      } else if (rawEvent.kind === NotebookCellsChangeType.ChangeCellLanguage) {
        this.v(rawEvent.index, rawEvent.language);
        relaxedCellChanges.push({ cell: this.b[rawEvent.index].apiCell, document: this.b[rawEvent.index].apiCell.document });
      } else if (rawEvent.kind === NotebookCellsChangeType.ChangeCellContent) {
        relaxedCellChanges.push({ cell: this.b[rawEvent.index].apiCell, document: this.b[rawEvent.index].apiCell.document });
      } else if (rawEvent.kind === NotebookCellsChangeType.ChangeCellMime) {
        this.w(rawEvent.index, rawEvent.mime);
      } else if (rawEvent.kind === NotebookCellsChangeType.ChangeCellMetadata) {
        this.x(rawEvent.index, rawEvent.metadata);
        relaxedCellChanges.push({ cell: this.b[rawEvent.index].apiCell, metadata: this.b[rawEvent.index].apiCell.metadata });
      } else if (rawEvent.kind === NotebookCellsChangeType.ChangeCellInternalMetadata) {
        this.y(rawEvent.index, rawEvent.internalMetadata);
        relaxedCellChanges.push({ cell: this.b[rawEvent.index].apiCell, executionSummary: this.b[rawEvent.index].apiCell.executionSummary });
      }
    }
    const map = /* @__PURE__ */ new Map();
    for (let i = 0; i < relaxedCellChanges.length; i++) {
      const relaxedCellChange = relaxedCellChanges[i];
      const existing = map.get(relaxedCellChange.cell);
      if (existing === void 0) {
        const newLen = result.cellChanges.push({
          document: void 0,
          executionSummary: void 0,
          metadata: void 0,
          outputs: void 0,
          ...relaxedCellChange
        });
        map.set(relaxedCellChange.cell, newLen - 1);
      } else {
        result.cellChanges[existing] = {
          ...result.cellChanges[existing],
          ...relaxedCellChange
        };
      }
    }
    Object.freeze(result);
    Object.freeze(result.cellChanges);
    Object.freeze(result.contentChanges);
    return result;
  }
  n(index) {
    index = index | 0;
    if (index < 0) {
      return 0;
    } else if (index >= this.b.length) {
      return this.b.length - 1;
    } else {
      return index;
    }
  }
  o(range) {
    let start = range.start | 0;
    let end = range.end | 0;
    if (start < 0) {
      start = 0;
    }
    if (end > this.b.length) {
      end = this.b.length;
    }
    return range.with({ start, end });
  }
  p(range) {
    range = this.o(range);
    const result = [];
    for (let i = range.start; i < range.end; i++) {
      result.push(this.b[i]);
    }
    return result;
  }
  async q() {
    if (this.j) {
      return Promise.reject(new Error("Notebook has been closed"));
    }
    return this.k.$trySaveNotebook(this.uri);
  }
  r(splices, initialization, bucket) {
    if (this.j) {
      return;
    }
    const contentChangeEvents = [];
    const addedCellDocuments = [];
    const removedCellDocuments = [];
    splices.reverse().forEach((splice) => {
      const cellDtos = splice[2];
      const newCells = cellDtos.map((cell) => {
        const extCell = new $0xc(this, this.l, cell);
        if (!initialization) {
          addedCellDocuments.push($0xc.asModelAddData(cell));
        }
        return extCell;
      });
      const changeEvent = new RawContentChangeEvent(splice[0], splice[1], [], newCells);
      const deletedItems = this.b.splice(splice[0], splice[1], ...newCells);
      for (const cell of deletedItems) {
        removedCellDocuments.push(cell.uri);
        changeEvent.deletedItems.push(cell.apiCell);
      }
      contentChangeEvents.push(changeEvent);
    });
    this.l.acceptDocumentsAndEditorsDelta({
      addedDocuments: addedCellDocuments,
      removedDocuments: removedCellDocuments
    });
    if (bucket) {
      for (const changeEvent of contentChangeEvents) {
        bucket.push(changeEvent.asApiEvent());
      }
    }
  }
  s(index, length, newIdx, bucket) {
    const cells = this.b.splice(index, length);
    this.b.splice(newIdx, 0, ...cells);
    const changes = [
      new RawContentChangeEvent(index, length, cells.map((c) => c.apiCell), []),
      new RawContentChangeEvent(newIdx, 0, [], cells)
    ];
    for (const change of changes) {
      bucket.push(change.asApiEvent());
    }
  }
  t(index, outputs) {
    const cell = this.b[index];
    cell.setOutputs(outputs);
  }
  u(index, outputId, append, outputItems) {
    const cell = this.b[index];
    cell.setOutputItems(outputId, append, outputItems);
  }
  v(index, newLanguageId) {
    const cell = this.b[index];
    if (cell.apiCell.document.languageId !== newLanguageId) {
      this.m.$acceptModelLanguageChanged(cell.uri, newLanguageId);
    }
  }
  w(index, newMime) {
    const cell = this.b[index];
    cell.apiCell.mime = newMime;
  }
  x(index, newMetadata) {
    const cell = this.b[index];
    cell.setMetadata(newMetadata);
  }
  y(index, newInternalMetadata) {
    const cell = this.b[index];
    cell.setInternalMetadata(newInternalMetadata);
  }
  getCellFromApiCell(apiCell) {
    return this.b.find((cell) => cell.apiCell === apiCell);
  }
  getCellFromIndex(index) {
    return this.b[index];
  }
  getCell(cellHandle) {
    return this.b.find((cell) => cell.handle === cellHandle);
  }
  getCellIndex(cell) {
    return this.b.indexOf(cell);
  }
};

// out-build/vs/workbench/api/common/extHostNotebookEditor.js
var $_xc = class _$_xc {
  static {
    this.apiEditorsToExtHost = /* @__PURE__ */ new WeakMap();
  }
  constructor(id2, c, notebookData, d, e, f, g) {
    this.id = id2;
    this.c = c;
    this.notebookData = notebookData;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.a = false;
  }
  get apiEditor() {
    if (!this.b) {
      const that = this;
      this.b = {
        get notebook() {
          return that.notebookData.apiNotebook;
        },
        get selection() {
          return that.e[0];
        },
        set selection(selection) {
          this.selections = [selection];
        },
        get selections() {
          return that.e;
        },
        set selections(value) {
          if (!Array.isArray(value) || !value.every($6U.isNotebookRange)) {
            throw $nb("selections");
          }
          that.e = value;
          that.h(value);
        },
        get visibleRanges() {
          return that.d;
        },
        revealRange(range, revealType) {
          that.c.$tryRevealRange(that.id, NotebookRange.from(range), revealType ?? NotebookEditorRevealType2.Default);
        },
        get viewColumn() {
          return that.f;
        },
        get replOptions() {
          if (that.g === "repl") {
            return { appendIndex: this.notebook.cellCount - 1 };
          }
          return void 0;
        },
        [Symbol.for("debug.description")]() {
          return `NotebookEditor(${this.notebook.uri.toString()})`;
        }
      };
      _$_xc.apiEditorsToExtHost.set(this.b, this);
    }
    return this.b;
  }
  get visible() {
    return this.a;
  }
  _acceptVisibility(value) {
    this.a = value;
  }
  _acceptVisibleRanges(value) {
    this.d = value;
  }
  _acceptSelections(selections) {
    this.e = selections;
  }
  h(value) {
    this.c.$trySetSelections(this.id, value.map(NotebookRange.from));
  }
  _acceptViewColumn(value) {
    this.f = value;
  }
};

// out-build/vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase.js
var $8H = class {
  constructor(piece, color2) {
    this.piece = piece;
    this.color = color2;
    this.size_left = 0;
    this.lf_left = 0;
    this.parent = this;
    this.left = this;
    this.right = this;
  }
  next() {
    if (this.right !== $9H) {
      return $0H(this.right);
    }
    let node = this;
    while (node.parent !== $9H) {
      if (node.parent.left === node) {
        break;
      }
      node = node.parent;
    }
    if (node.parent === $9H) {
      return $9H;
    } else {
      return node.parent;
    }
  }
  prev() {
    if (this.left !== $9H) {
      return $$H(this.left);
    }
    let node = this;
    while (node.parent !== $9H) {
      if (node.parent.right === node) {
        break;
      }
      node = node.parent;
    }
    if (node.parent === $9H) {
      return $9H;
    } else {
      return node.parent;
    }
  }
  detach() {
    this.parent = null;
    this.left = null;
    this.right = null;
  }
};
var NodeColor;
(function(NodeColor2) {
  NodeColor2[NodeColor2["Black"] = 0] = "Black";
  NodeColor2[NodeColor2["Red"] = 1] = "Red";
})(NodeColor || (NodeColor = {}));
var $9H = new $8H(
  null,
  0
  /* NodeColor.Black */
);
$9H.parent = $9H;
$9H.left = $9H;
$9H.right = $9H;
$9H.color = 0;
function $0H(node) {
  while (node.left !== $9H) {
    node = node.left;
  }
  return node;
}
function $$H(node) {
  while (node.right !== $9H) {
    node = node.right;
  }
  return node;
}
function calculateSize(node) {
  if (node === $9H) {
    return 0;
  }
  return node.size_left + node.piece.length + calculateSize(node.right);
}
function calculateLF(node) {
  if (node === $9H) {
    return 0;
  }
  return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
}
function resetSentinel() {
  $9H.parent = $9H;
}
function $_H(tree, 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 !== $9H) {
    y.left.parent = x;
  }
  y.parent = x.parent;
  if (x.parent === $9H) {
    tree.root = y;
  } else if (x.parent.left === x) {
    x.parent.left = y;
  } else {
    x.parent.right = y;
  }
  y.left = x;
  x.parent = y;
}
function $aI(tree, y) {
  const x = y.left;
  y.left = x.right;
  if (x.right !== $9H) {
    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 === $9H) {
    tree.root = x;
  } else if (y === y.parent.right) {
    y.parent.right = x;
  } else {
    y.parent.left = x;
  }
  x.right = y;
  y.parent = x;
}
function $bI(tree, z) {
  let x;
  let y;
  if (z.left === $9H) {
    y = z;
    x = y.right;
  } else if (z.right === $9H) {
    y = z;
    x = y.left;
  } else {
    y = $0H(z.right);
    x = y.right;
  }
  if (y === tree.root) {
    tree.root = x;
    x.color = 0;
    z.detach();
    resetSentinel();
    tree.root.parent = $9H;
    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;
    $eI(tree, x);
  } else {
    if (y.parent === z) {
      x.parent = y;
    } else {
      x.parent = y.parent;
    }
    $eI(tree, x);
    y.left = z.left;
    y.right = z.right;
    y.parent = z.parent;
    y.color = z.color;
    if (z === tree.root) {
      tree.root = y;
    } else {
      if (z === z.parent.left) {
        z.parent.left = y;
      } else {
        z.parent.right = y;
      }
    }
    if (y.left !== $9H) {
      y.left.parent = y;
    }
    if (y.right !== $9H) {
      y.right.parent = y;
    }
    y.size_left = z.size_left;
    y.lf_left = z.lf_left;
    $eI(tree, 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 delta2 = newSizeLeft - x.parent.size_left;
      const lf_delta = newLFLeft - x.parent.lf_left;
      x.parent.size_left = newSizeLeft;
      x.parent.lf_left = newLFLeft;
      $dI(tree, x.parent, delta2, lf_delta);
    }
  }
  $eI(tree, x.parent);
  if (yWasRed) {
    resetSentinel();
    return;
  }
  let w;
  while (x !== tree.root && x.color === 0) {
    if (x === x.parent.left) {
      w = x.parent.right;
      if (w.color === 1) {
        w.color = 0;
        x.parent.color = 1;
        $_H(tree, 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;
          $aI(tree, w);
          w = x.parent.right;
        }
        w.color = x.parent.color;
        x.parent.color = 0;
        w.right.color = 0;
        $_H(tree, x.parent);
        x = tree.root;
      }
    } else {
      w = x.parent.left;
      if (w.color === 1) {
        w.color = 0;
        x.parent.color = 1;
        $aI(tree, 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;
          $_H(tree, w);
          w = x.parent.left;
        }
        w.color = x.parent.color;
        x.parent.color = 0;
        w.left.color = 0;
        $aI(tree, x.parent);
        x = tree.root;
      }
    }
  }
  x.color = 0;
  resetSentinel();
}
function $cI(tree, x) {
  $eI(tree, x);
  while (x !== tree.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;
          $_H(tree, x);
        }
        x.parent.color = 0;
        x.parent.parent.color = 1;
        $aI(tree, 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;
          $aI(tree, x);
        }
        x.parent.color = 0;
        x.parent.parent.color = 1;
        $_H(tree, x.parent.parent);
      }
    }
  }
  tree.root.color = 0;
}
function $dI(tree, x, delta2, lineFeedCntDelta) {
  while (x !== tree.root && x !== $9H) {
    if (x.parent.left === x) {
      x.parent.size_left += delta2;
      x.parent.lf_left += lineFeedCntDelta;
    }
    x = x.parent;
  }
}
function $eI(tree, x) {
  let delta2 = 0;
  let lf_delta = 0;
  if (x === tree.root) {
    return;
  }
  while (x !== tree.root && x === x.parent.right) {
    x = x.parent;
  }
  if (x === tree.root) {
    return;
  }
  x = x.parent;
  delta2 = calculateSize(x.left) - x.size_left;
  lf_delta = calculateLF(x.left) - x.lf_left;
  x.size_left += delta2;
  x.lf_left += lf_delta;
  while (x !== tree.root && (delta2 !== 0 || lf_delta !== 0)) {
    if (x.parent.left === x) {
      x.parent.size_left += delta2;
      x.parent.lf_left += lf_delta;
    }
    x = x.parent;
  }
}

// out-build/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase.js
var 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;
}
var LineStarts = class {
  constructor(lineStarts, cr, lf, crlf, isBasicASCII) {
    this.lineStarts = lineStarts;
    this.cr = cr;
    this.lf = lf;
    this.crlf = crlf;
    this.isBasicASCII = isBasicASCII;
  }
};
function $lI(str, readonly = true) {
  const r = [0];
  let rLength = 1;
  for (let i = 0, len = str.length; i < len; i++) {
    const chr = str.charCodeAt(i);
    if (chr === 13) {
      if (i + 1 < len && str.charCodeAt(i + 1) === 10) {
        r[rLength++] = i + 2;
        i++;
      } else {
        r[rLength++] = i + 1;
      }
    } else if (chr === 10) {
      r[rLength++] = i + 1;
    }
  }
  if (readonly) {
    return createUintArray(r);
  } else {
    return r;
  }
}
function $mI(r, str) {
  r.length = 0;
  r[0] = 0;
  let rLength = 1;
  let cr = 0, lf = 0, crlf = 0;
  let isBasicASCII = true;
  for (let i = 0, len = str.length; i < len; i++) {
    const chr = str.charCodeAt(i);
    if (chr === 13) {
      if (i + 1 < len && str.charCodeAt(i + 1) === 10) {
        crlf++;
        r[rLength++] = i + 2;
        i++;
      } else {
        cr++;
        r[rLength++] = i + 1;
      }
    } else if (chr === 10) {
      lf++;
      r[rLength++] = i + 1;
    } else {
      if (isBasicASCII) {
        if (chr !== 9 && (chr < 32 || chr > 126)) {
          isBasicASCII = false;
        }
      }
    }
  }
  const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);
  r.length = 0;
  return result;
}
var $nI = class {
  constructor(bufferIndex, start, end, lineFeedCnt, length) {
    this.bufferIndex = bufferIndex;
    this.start = start;
    this.end = end;
    this.lineFeedCnt = lineFeedCnt;
    this.length = length;
  }
};
var $oI = class {
  constructor(buffer, lineStarts) {
    this.buffer = buffer;
    this.lineStarts = lineStarts;
  }
};
var PieceTreeSnapshot = class {
  constructor(tree, BOM) {
    this.a = [];
    this.c = tree;
    this.d = BOM;
    this.b = 0;
    if (tree.root !== $9H) {
      tree.iterate(tree.root, (node) => {
        if (node !== $9H) {
          this.a.push(node.piece);
        }
        return true;
      });
    }
  }
  read() {
    if (this.a.length === 0) {
      if (this.b === 0) {
        this.b++;
        return this.d;
      } else {
        return null;
      }
    }
    if (this.b > this.a.length - 1) {
      return null;
    }
    if (this.b === 0) {
      return this.d + this.c.getPieceContent(this.a[this.b++]);
    }
    return this.c.getPieceContent(this.a[this.b++]);
  }
};
var PieceTreeSearchCache = class {
  constructor(limit) {
    this.a = limit;
    this.b = [];
  }
  get(offset) {
    for (let i = this.b.length - 1; i >= 0; i--) {
      const nodePos = this.b[i];
      if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
        return nodePos;
      }
    }
    return null;
  }
  get2(lineNumber) {
    for (let i = this.b.length - 1; i >= 0; i--) {
      const nodePos = this.b[i];
      if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
        return nodePos;
      }
    }
    return null;
  }
  set(nodePosition) {
    if (this.b.length >= this.a) {
      this.b.shift();
    }
    this.b.push(nodePosition);
  }
  validate(offset) {
    let hasInvalidVal = false;
    const tmp = this.b;
    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.b = newArr;
    }
  }
};
var $pI = class {
  constructor(chunks, eol, eolNormalized) {
    this.create(chunks, eol, eolNormalized);
  }
  create(chunks, eol, eolNormalized) {
    this.a = [
      new $oI("", [0])
    ];
    this.g = { line: 0, column: 0 };
    this.root = $9H;
    this.b = 1;
    this.c = 0;
    this.d = eol;
    this.e = eol.length;
    this.f = 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 = $lI(chunks[i].buffer);
        }
        const piece = new $nI(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.a.push(chunks[i]);
        lastNode = this.S(lastNode, piece);
      }
    }
    this.h = new PieceTreeSearchCache(1);
    this.j = { lineNumber: 0, value: "" };
    this.y();
  }
  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, (node) => {
      const str = this.R(node);
      const len = str.length;
      if (tempChunkLen <= min || tempChunkLen + len < max) {
        tempChunk += str;
        tempChunkLen += len;
        return true;
      }
      const text = tempChunk.replace(/\r\n|\r|\n/g, eol);
      chunks.push(new $oI(text, $lI(text)));
      tempChunk = str;
      tempChunkLen = len;
      return true;
    });
    if (tempChunkLen > 0) {
      const text = tempChunk.replace(/\r\n|\r|\n/g, eol);
      chunks.push(new $oI(text, $lI(text)));
    }
    this.create(chunks, eol, true);
  }
  // #region Buffer API
  getEOL() {
    return this.d;
  }
  setEOL(newEOL) {
    this.d = newEOL;
    this.e = this.d.length;
    this.normalizeEOL(newEOL);
  }
  createSnapshot(BOM) {
    return new PieceTreeSnapshot(this, BOM);
  }
  equal(other) {
    if (this.getLength() !== other.getLength()) {
      return false;
    }
    if (this.getLineCount() !== other.getLineCount()) {
      return false;
    }
    let offset = 0;
    const ret = this.iterate(this.root, (node) => {
      if (node === $9H) {
        return true;
      }
      const str = this.R(node);
      const len = str.length;
      const startPosition = other.G(offset);
      const endPosition = other.G(offset + len);
      const val = other.getValueInRange2(startPosition, endPosition);
      offset += len;
      return str === val;
    });
    return ret;
  }
  getOffsetAt(lineNumber, column) {
    let leftLen = 0;
    let x = this.root;
    while (x !== $9H) {
      if (x.left !== $9H && 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.B(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 !== $9H) {
      if (x.size_left !== 0 && x.size_left >= offset) {
        x = x.left;
      } else if (x.size_left + x.piece.length >= offset) {
        const out = this.A(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 $8C(lfCnt + 1, column + 1);
        }
        return new $8C(lfCnt + 1, out.remainder + 1);
      } else {
        offset -= x.size_left + x.piece.length;
        lfCnt += x.lf_left + x.piece.lineFeedCnt;
        if (x.right === $9H) {
          const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
          const column = originalOffset - offset - lineStartOffset;
          return new $8C(lfCnt + 1, column + 1);
        } else {
          x = x.right;
        }
      }
    }
    return new $8C(1, 1);
  }
  getValueInRange(range, eol) {
    if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
      return "";
    }
    const startPosition = this.H(range.startLineNumber, range.startColumn);
    const endPosition = this.H(range.endLineNumber, range.endColumn);
    const value = this.getValueInRange2(startPosition, endPosition);
    if (eol) {
      if (eol !== this.d || !this.f) {
        return value.replace(/\r\n|\r|\n/g, eol);
      }
      if (eol === this.getEOL() && this.f) {
        if (eol === "\r\n") {
        }
        return value;
      }
      return value.replace(/\r\n|\r|\n/g, eol);
    }
    return value;
  }
  getValueInRange2(startPosition, endPosition) {
    if (startPosition.node === endPosition.node) {
      const node = startPosition.node;
      const buffer2 = this.a[node.piece.bufferIndex].buffer;
      const startOffset2 = this.u(node.piece.bufferIndex, node.piece.start);
      return buffer2.substring(startOffset2 + startPosition.remainder, startOffset2 + endPosition.remainder);
    }
    let x = startPosition.node;
    const buffer = this.a[x.piece.bufferIndex].buffer;
    const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
    let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
    x = x.next();
    while (x !== $9H) {
      const buffer2 = this.a[x.piece.bufferIndex].buffer;
      const startOffset2 = this.u(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, (node) => {
      if (node === $9H) {
        return true;
      }
      const piece = node.piece;
      let pieceLength = piece.length;
      if (pieceLength === 0) {
        return true;
      }
      const buffer = this.a[piece.bufferIndex].buffer;
      const lineStarts = this.a[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.f && buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === 13) {
          danglingCR = true;
          currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
        } else {
          currentLine += buffer.substr(pieceStartOffset, pieceLength);
        }
        return true;
      }
      currentLine += this.f ? buffer.substring(pieceStartOffset, Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - this.e)) : buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, "");
      lines[linesLength++] = currentLine;
      for (let line = pieceStartLine + 1; line < pieceEndLine; line++) {
        currentLine = this.f ? buffer.substring(lineStarts[line], lineStarts[line + 1] - this.e) : buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, "");
        lines[linesLength++] = currentLine;
      }
      if (!this.f && 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.c;
  }
  getLineCount() {
    return this.b;
  }
  getLineContent(lineNumber) {
    if (this.j.lineNumber === lineNumber) {
      return this.j.value;
    }
    this.j.lineNumber = lineNumber;
    if (lineNumber === this.b) {
      this.j.value = this.getLineRawContent(lineNumber);
    } else if (this.f) {
      this.j.value = this.getLineRawContent(lineNumber, this.e);
    } else {
      this.j.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, "");
    }
    return this.j.value;
  }
  l(nodePos) {
    if (nodePos.remainder === nodePos.node.piece.length) {
      const matchingNode = nodePos.node.next();
      if (!matchingNode) {
        return 0;
      }
      const buffer = this.a[matchingNode.piece.bufferIndex];
      const startOffset = this.u(matchingNode.piece.bufferIndex, matchingNode.piece.start);
      return buffer.buffer.charCodeAt(startOffset);
    } else {
      const buffer = this.a[nodePos.node.piece.bufferIndex];
      const startOffset = this.u(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
      const targetOffset = startOffset + nodePos.remainder;
      return buffer.buffer.charCodeAt(targetOffset);
    }
  }
  getLineCharCode(lineNumber, index) {
    const nodePos = this.H(lineNumber, index + 1);
    return this.l(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.e;
  }
  getCharCode(offset) {
    const nodePos = this.G(offset);
    return this.l(nodePos);
  }
  getNearestChunk(offset) {
    const nodePos = this.G(offset);
    if (nodePos.remainder === nodePos.node.piece.length) {
      const matchingNode = nodePos.node.next();
      if (!matchingNode || matchingNode === $9H) {
        return "";
      }
      const buffer = this.a[matchingNode.piece.bufferIndex];
      const startOffset = this.u(matchingNode.piece.bufferIndex, matchingNode.piece.start);
      return buffer.buffer.substring(startOffset, startOffset + matchingNode.piece.length);
    } else {
      const buffer = this.a[nodePos.node.piece.bufferIndex];
      const startOffset = this.u(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
      const targetOffset = startOffset + nodePos.remainder;
      const targetEnd = startOffset + nodePos.node.piece.length;
      return buffer.buffer.substring(targetOffset, targetEnd);
    }
  }
  findMatchesInNode(node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) {
    const buffer = this.a[node.piece.bufferIndex];
    const startOffsetInBuffer = this.u(node.piece.bufferIndex, node.piece.start);
    const start = this.u(node.piece.bufferIndex, startCursor);
    const end = this.u(node.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.s(node, offsetInBuffer(m.index) - startOffsetInBuffer, ret);
        const lineFeedCnt = this.t(node.piece.bufferIndex, startCursor, ret);
        const retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
        const retEndColumn = retStartColumn + m[0].length;
        result[resultLen++] = $hI(new $9C(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 result = [];
    let resultLen = 0;
    const searcher = new $kI(searchData.wordSeparators, searchData.regex);
    let startPosition = this.H(searchRange.startLineNumber, searchRange.startColumn);
    if (startPosition === null) {
      return [];
    }
    const endPosition = this.H(searchRange.endLineNumber, searchRange.endColumn);
    if (endPosition === null) {
      return [];
    }
    let start = this.s(startPosition.node, startPosition.remainder);
    const end = this.s(endPosition.node, endPosition.remainder);
    if (startPosition.node === endPosition.node) {
      this.findMatchesInNode(startPosition.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
      return result;
    }
    let startLineNumber = searchRange.startLineNumber;
    let currentNode = startPosition.node;
    while (currentNode !== endPosition.node) {
      const lineBreakCnt = this.t(currentNode.piece.bufferIndex, start, currentNode.piece.end);
      if (lineBreakCnt >= 1) {
        const lineStarts = this.a[currentNode.piece.bufferIndex].lineStarts;
        const startOffsetInBuffer = this.u(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.s(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result);
        if (resultLen >= limitResultCount) {
          return result;
        }
        startLineNumber += lineBreakCnt;
      }
      const startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
      if (startLineNumber === searchRange.endLineNumber) {
        const text = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
        resultLen = this.n(searchData, searcher, text, searchRange.endLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
        return result;
      }
      resultLen = this.n(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn2), startLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
      if (resultLen >= limitResultCount) {
        return result;
      }
      startLineNumber++;
      startPosition = this.H(startLineNumber, 1);
      currentNode = startPosition.node;
      start = this.s(startPosition.node, startPosition.remainder);
    }
    if (startLineNumber === searchRange.endLineNumber) {
      const startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
      const text = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
      resultLen = this.n(searchData, searcher, text, searchRange.endLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
      return result;
    }
    const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
    resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
    return result;
  }
  n(searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
    const wordSeparators2 = searchData.wordSeparators;
    if (!captureMatches && searchData.simpleSearch) {
      const searchString = searchData.simpleSearch;
      const searchStringLen = searchString.length;
      const textLength = text.length;
      let lastMatchIndex = -searchStringLen;
      while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
        if (!wordSeparators2 || $jI(wordSeparators2, text, textLength, lastMatchIndex, searchStringLen)) {
          result[resultLen++] = new $eG(new $9C(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(text);
      if (m) {
        result[resultLen++] = $hI(new $9C(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.f = this.f && eolNormalized;
    this.j.lineNumber = 0;
    this.j.value = "";
    if (this.root !== $9H) {
      const { node, remainder, nodeStartOffset } = this.G(offset);
      const piece = node.piece;
      const bufferIndex = piece.bufferIndex;
      const insertPosInBuffer = this.s(node, remainder);
      if (node.piece.bufferIndex === 0 && piece.end.line === this.g.line && piece.end.column === this.g.column && nodeStartOffset + piece.length === offset && value.length < AverageBufferSize) {
        this.F(node, value);
        this.y();
        return;
      }
      if (nodeStartOffset === offset) {
        this.o(value, node);
        this.h.validate(offset);
      } else if (nodeStartOffset + node.piece.length > offset) {
        const nodesToDel = [];
        let newRightPiece = new $nI(piece.bufferIndex, insertPosInBuffer, piece.end, this.t(piece.bufferIndex, insertPosInBuffer, piece.end), this.u(bufferIndex, piece.end) - this.u(bufferIndex, insertPosInBuffer));
        if (this.K() && this.M(value)) {
          const headOfRight = this.I(node, remainder);
          if (headOfRight === 10) {
            const newStart = { line: newRightPiece.start.line + 1, column: 0 };
            newRightPiece = new $nI(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.t(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
            value += "\n";
          }
        }
        if (this.K() && this.L(value)) {
          const tailOfLeft = this.I(node, remainder - 1);
          if (tailOfLeft === 13) {
            const previousPos = this.s(node, remainder - 1);
            this.C(node, previousPos);
            value = "\r" + value;
            if (node.piece.length === 0) {
              nodesToDel.push(node);
            }
          } else {
            this.C(node, insertPosInBuffer);
          }
        } else {
          this.C(node, insertPosInBuffer);
        }
        const newPieces = this.w(value);
        if (newRightPiece.length > 0) {
          this.S(node, newRightPiece);
        }
        let tmpNode = node;
        for (let k = 0; k < newPieces.length; k++) {
          tmpNode = this.S(tmpNode, newPieces[k]);
        }
        this.v(nodesToDel);
      } else {
        this.q(value, node);
      }
    } else {
      const pieces = this.w(value);
      let node = this.T(null, pieces[0]);
      for (let k = 1; k < pieces.length; k++) {
        node = this.S(node, pieces[k]);
      }
    }
    this.y();
  }
  delete(offset, cnt) {
    this.j.lineNumber = 0;
    this.j.value = "";
    if (cnt <= 0 || this.root === $9H) {
      return;
    }
    const startPosition = this.G(offset);
    const endPosition = this.G(offset + cnt);
    const startNode = startPosition.node;
    const endNode = endPosition.node;
    if (startNode === endNode) {
      const startSplitPosInBuffer2 = this.s(startNode, startPosition.remainder);
      const endSplitPosInBuffer2 = this.s(startNode, endPosition.remainder);
      if (startPosition.nodeStartOffset === offset) {
        if (cnt === startNode.piece.length) {
          const next = startNode.next();
          $bI(this, startNode);
          this.N(next);
          this.y();
          return;
        }
        this.D(startNode, endSplitPosInBuffer2);
        this.h.validate(offset);
        this.N(startNode);
        this.y();
        return;
      }
      if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
        this.C(startNode, startSplitPosInBuffer2);
        this.O(startNode);
        this.y();
        return;
      }
      this.E(startNode, startSplitPosInBuffer2, endSplitPosInBuffer2);
      this.y();
      return;
    }
    const nodesToDel = [];
    const startSplitPosInBuffer = this.s(startNode, startPosition.remainder);
    this.C(startNode, startSplitPosInBuffer);
    this.h.validate(offset);
    if (startNode.piece.length === 0) {
      nodesToDel.push(startNode);
    }
    const endSplitPosInBuffer = this.s(endNode, endPosition.remainder);
    this.D(endNode, endSplitPosInBuffer);
    if (endNode.piece.length === 0) {
      nodesToDel.push(endNode);
    }
    const secondNode = startNode.next();
    for (let node = secondNode; node !== $9H && node !== endNode; node = node.next()) {
      nodesToDel.push(node);
    }
    const prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
    this.v(nodesToDel);
    this.O(prev);
    this.y();
  }
  o(value, node) {
    const nodesToDel = [];
    if (this.K() && this.M(value) && this.L(node)) {
      const piece = node.piece;
      const newStart = { line: piece.start.line + 1, column: 0 };
      const nPiece = new $nI(piece.bufferIndex, newStart, piece.end, this.t(piece.bufferIndex, newStart, piece.end), piece.length - 1);
      node.piece = nPiece;
      value += "\n";
      $dI(this, node, -1, -1);
      if (node.piece.length === 0) {
        nodesToDel.push(node);
      }
    }
    const newPieces = this.w(value);
    let newNode = this.T(node, newPieces[newPieces.length - 1]);
    for (let k = newPieces.length - 2; k >= 0; k--) {
      newNode = this.T(newNode, newPieces[k]);
    }
    this.N(newNode);
    this.v(nodesToDel);
  }
  q(value, node) {
    if (this.Q(value, node)) {
      value += "\n";
    }
    const newPieces = this.w(value);
    const newNode = this.S(node, newPieces[0]);
    let tmpNode = newNode;
    for (let k = 1; k < newPieces.length; k++) {
      tmpNode = this.S(tmpNode, newPieces[k]);
    }
    this.N(newNode);
  }
  s(node, remainder, ret) {
    const piece = node.piece;
    const bufferIndex = node.piece.bufferIndex;
    const lineStarts = this.a[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
    };
  }
  t(bufferIndex, start, end) {
    if (end.column === 0) {
      return end.line - start.line;
    }
    const lineStarts = this.a[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.a[bufferIndex].buffer;
    if (buffer.charCodeAt(previousCharOffset) === 13) {
      return end.line - start.line + 1;
    } else {
      return end.line - start.line;
    }
  }
  u(bufferIndex, cursor) {
    const lineStarts = this.a[bufferIndex].lineStarts;
    return lineStarts[cursor.line] + cursor.column;
  }
  v(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      $bI(this, nodes[i]);
    }
  }
  w(text) {
    if (text.length > AverageBufferSize) {
      const newPieces = [];
      while (text.length > AverageBufferSize) {
        const lastChar = text.charCodeAt(AverageBufferSize - 1);
        let splitText;
        if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
          splitText = text.substring(0, AverageBufferSize - 1);
          text = text.substring(AverageBufferSize - 1);
        } else {
          splitText = text.substring(0, AverageBufferSize);
          text = text.substring(AverageBufferSize);
        }
        const lineStarts3 = $lI(splitText);
        newPieces.push(new $nI(
          this.a.length,
          /* buffer index */
          { line: 0, column: 0 },
          { line: lineStarts3.length - 1, column: splitText.length - lineStarts3[lineStarts3.length - 1] },
          lineStarts3.length - 1,
          splitText.length
        ));
        this.a.push(new $oI(splitText, lineStarts3));
      }
      const lineStarts2 = $lI(text);
      newPieces.push(new $nI(
        this.a.length,
        /* buffer index */
        { line: 0, column: 0 },
        { line: lineStarts2.length - 1, column: text.length - lineStarts2[lineStarts2.length - 1] },
        lineStarts2.length - 1,
        text.length
      ));
      this.a.push(new $oI(text, lineStarts2));
      return newPieces;
    }
    let startOffset = this.a[0].buffer.length;
    const lineStarts = $lI(text, false);
    let start = this.g;
    if (this.a[0].lineStarts[this.a[0].lineStarts.length - 1] === startOffset && startOffset !== 0 && this.L(text) && this.M(this.a[0].buffer)) {
      this.g = { line: this.g.line, column: this.g.column + 1 };
      start = this.g;
      for (let i = 0; i < lineStarts.length; i++) {
        lineStarts[i] += startOffset + 1;
      }
      this.a[0].lineStarts = this.a[0].lineStarts.concat(lineStarts.slice(1));
      this.a[0].buffer += "_" + text;
      startOffset += 1;
    } else {
      if (startOffset !== 0) {
        for (let i = 0; i < lineStarts.length; i++) {
          lineStarts[i] += startOffset;
        }
      }
      this.a[0].lineStarts = this.a[0].lineStarts.concat(lineStarts.slice(1));
      this.a[0].buffer += text;
    }
    const endOffset = this.a[0].buffer.length;
    const endIndex = this.a[0].lineStarts.length - 1;
    const endColumn = endOffset - this.a[0].lineStarts[endIndex];
    const endPos = { line: endIndex, column: endColumn };
    const newPiece = new $nI(
      0,
      /** todo@peng */
      start,
      endPos,
      this.t(0, start, endPos),
      endOffset - startOffset
    );
    this.g = endPos;
    return [newPiece];
  }
  getLinesRawContent() {
    return this.U(this.root);
  }
  getLineRawContent(lineNumber, endOffset = 0) {
    let x = this.root;
    let ret = "";
    const cache = this.h.get2(lineNumber);
    if (cache) {
      x = cache.node;
      const prevAccumulatedValue = this.B(x, lineNumber - cache.nodeStartLineNumber - 1);
      const buffer = this.a[x.piece.bufferIndex].buffer;
      const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
      if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
        ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
      } else {
        const accumulatedValue = this.B(x, lineNumber - cache.nodeStartLineNumber);
        return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
      }
    } else {
      let nodeStartOffset = 0;
      const originalLineNumber = lineNumber;
      while (x !== $9H) {
        if (x.left !== $9H && x.lf_left >= lineNumber - 1) {
          x = x.left;
        } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
          const prevAccumulatedValue = this.B(x, lineNumber - x.lf_left - 2);
          const accumulatedValue = this.B(x, lineNumber - x.lf_left - 1);
          const buffer = this.a[x.piece.bufferIndex].buffer;
          const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
          nodeStartOffset += x.size_left;
          this.h.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.B(x, lineNumber - x.lf_left - 2);
          const buffer = this.a[x.piece.bufferIndex].buffer;
          const startOffset = this.u(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 !== $9H) {
      const buffer = this.a[x.piece.bufferIndex].buffer;
      if (x.piece.lineFeedCnt > 0) {
        const accumulatedValue = this.B(x, 0);
        const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
        ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
        return ret;
      } else {
        const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
        ret += buffer.substr(startOffset, x.piece.length);
      }
      x = x.next();
    }
    return ret;
  }
  y() {
    let x = this.root;
    let lfCnt = 1;
    let len = 0;
    while (x !== $9H) {
      lfCnt += x.lf_left + x.piece.lineFeedCnt;
      len += x.size_left + x.piece.length;
      x = x.right;
    }
    this.b = lfCnt;
    this.c = len;
    this.h.validate(this.c);
  }
  // #region node operations
  A(node, accumulatedValue) {
    const piece = node.piece;
    const pos = this.s(node, accumulatedValue);
    const lineCnt = pos.line - piece.start.line;
    if (this.u(piece.bufferIndex, piece.end) - this.u(piece.bufferIndex, piece.start) === accumulatedValue) {
      const realLineCnt = this.t(node.piece.bufferIndex, piece.start, pos);
      if (realLineCnt !== lineCnt) {
        return { index: realLineCnt, remainder: 0 };
      }
    }
    return { index: lineCnt, remainder: pos.column };
  }
  B(node, index) {
    if (index < 0) {
      return 0;
    }
    const piece = node.piece;
    const lineStarts = this.a[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;
    }
  }
  C(node, pos) {
    const piece = node.piece;
    const originalLFCnt = piece.lineFeedCnt;
    const originalEndOffset = this.u(piece.bufferIndex, piece.end);
    const newEnd = pos;
    const newEndOffset = this.u(piece.bufferIndex, newEnd);
    const newLineFeedCnt = this.t(piece.bufferIndex, piece.start, newEnd);
    const lf_delta = newLineFeedCnt - originalLFCnt;
    const size_delta = newEndOffset - originalEndOffset;
    const newLength = piece.length + size_delta;
    node.piece = new $nI(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
    $dI(this, node, size_delta, lf_delta);
  }
  D(node, pos) {
    const piece = node.piece;
    const originalLFCnt = piece.lineFeedCnt;
    const originalStartOffset = this.u(piece.bufferIndex, piece.start);
    const newStart = pos;
    const newLineFeedCnt = this.t(piece.bufferIndex, newStart, piece.end);
    const newStartOffset = this.u(piece.bufferIndex, newStart);
    const lf_delta = newLineFeedCnt - originalLFCnt;
    const size_delta = originalStartOffset - newStartOffset;
    const newLength = piece.length + size_delta;
    node.piece = new $nI(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
    $dI(this, node, size_delta, lf_delta);
  }
  E(node, start, end) {
    const piece = node.piece;
    const originalStartPos = piece.start;
    const originalEndPos = piece.end;
    const oldLength = piece.length;
    const oldLFCnt = piece.lineFeedCnt;
    const newEnd = start;
    const newLineFeedCnt = this.t(piece.bufferIndex, piece.start, newEnd);
    const newLength = this.u(piece.bufferIndex, start) - this.u(piece.bufferIndex, originalStartPos);
    node.piece = new $nI(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
    $dI(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
    const newPiece = new $nI(piece.bufferIndex, end, originalEndPos, this.t(piece.bufferIndex, end, originalEndPos), this.u(piece.bufferIndex, originalEndPos) - this.u(piece.bufferIndex, end));
    const newNode = this.S(node, newPiece);
    this.N(newNode);
  }
  F(node, value) {
    if (this.Q(value, node)) {
      value += "\n";
    }
    const hitCRLF = this.K() && this.L(value) && this.M(node);
    const startOffset = this.a[0].buffer.length;
    this.a[0].buffer += value;
    const lineStarts = $lI(value, false);
    for (let i = 0; i < lineStarts.length; i++) {
      lineStarts[i] += startOffset;
    }
    if (hitCRLF) {
      const prevStartOffset = this.a[0].lineStarts[this.a[0].lineStarts.length - 2];
      this.a[0].lineStarts.pop();
      this.g = { line: this.g.line - 1, column: startOffset - prevStartOffset };
    }
    this.a[0].lineStarts = this.a[0].lineStarts.concat(lineStarts.slice(1));
    const endIndex = this.a[0].lineStarts.length - 1;
    const endColumn = this.a[0].buffer.length - this.a[0].lineStarts[endIndex];
    const newEnd = { line: endIndex, column: endColumn };
    const newLength = node.piece.length + value.length;
    const oldLineFeedCnt = node.piece.lineFeedCnt;
    const newLineFeedCnt = this.t(0, node.piece.start, newEnd);
    const lf_delta = newLineFeedCnt - oldLineFeedCnt;
    node.piece = new $nI(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
    this.g = newEnd;
    $dI(this, node, value.length, lf_delta);
  }
  G(offset) {
    let x = this.root;
    const cache = this.h.get(offset);
    if (cache) {
      return {
        node: cache.node,
        nodeStartOffset: cache.nodeStartOffset,
        remainder: offset - cache.nodeStartOffset
      };
    }
    let nodeStartOffset = 0;
    while (x !== $9H) {
      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.h.set(ret);
        return ret;
      } else {
        offset -= x.size_left + x.piece.length;
        nodeStartOffset += x.size_left + x.piece.length;
        x = x.right;
      }
    }
    return null;
  }
  H(lineNumber, column) {
    let x = this.root;
    let nodeStartOffset = 0;
    while (x !== $9H) {
      if (x.left !== $9H && x.lf_left >= lineNumber - 1) {
        x = x.left;
      } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
        const prevAccumualtedValue = this.B(x, lineNumber - x.lf_left - 2);
        const accumulatedValue = this.B(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.B(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 !== $9H) {
      if (x.piece.lineFeedCnt > 0) {
        const accumulatedValue = this.B(x, 0);
        const nodeStartOffset2 = this.J(x);
        return {
          node: x,
          remainder: Math.min(column - 1, accumulatedValue),
          nodeStartOffset: nodeStartOffset2
        };
      } else {
        if (x.piece.length >= column - 1) {
          const nodeStartOffset2 = this.J(x);
          return {
            node: x,
            remainder: column - 1,
            nodeStartOffset: nodeStartOffset2
          };
        } else {
          column -= x.piece.length;
        }
      }
      x = x.next();
    }
    return null;
  }
  I(node, offset) {
    if (node.piece.lineFeedCnt < 1) {
      return -1;
    }
    const buffer = this.a[node.piece.bufferIndex];
    const newOffset = this.u(node.piece.bufferIndex, node.piece.start) + offset;
    return buffer.buffer.charCodeAt(newOffset);
  }
  J(node) {
    if (!node) {
      return 0;
    }
    let pos = node.size_left;
    while (node !== this.root) {
      if (node.parent.right === node) {
        pos += node.parent.size_left + node.parent.piece.length;
      }
      node = node.parent;
    }
    return pos;
  }
  // #endregion
  // #region CRLF
  K() {
    return !(this.f && this.d === "\n");
  }
  L(val) {
    if (typeof val === "string") {
      return val.charCodeAt(0) === 10;
    }
    if (val === $9H || val.piece.lineFeedCnt === 0) {
      return false;
    }
    const piece = val.piece;
    const lineStarts = this.a[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.a[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
  }
  M(val) {
    if (typeof val === "string") {
      return val.charCodeAt(val.length - 1) === 13;
    }
    if (val === $9H || val.piece.lineFeedCnt === 0) {
      return false;
    }
    return this.I(val, val.piece.length - 1) === 13;
  }
  N(nextNode) {
    if (this.K() && this.L(nextNode)) {
      const node = nextNode.prev();
      if (this.M(node)) {
        this.P(node, nextNode);
      }
    }
  }
  O(node) {
    if (this.K() && this.M(node)) {
      const nextNode = node.next();
      if (this.L(nextNode)) {
        this.P(node, nextNode);
      }
    }
  }
  P(prev, next) {
    const nodesToDel = [];
    const lineStarts = this.a[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 $nI(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
    $dI(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.t(next.piece.bufferIndex, newStart, next.piece.end);
    next.piece = new $nI(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
    $dI(this, next, -1, -1);
    if (next.piece.length === 0) {
      nodesToDel.push(next);
    }
    const pieces = this.w("\r\n");
    this.S(prev, pieces[0]);
    for (let i = 0; i < nodesToDel.length; i++) {
      $bI(this, nodesToDel[i]);
    }
  }
  Q(value, node) {
    if (this.K() && this.M(value)) {
      const nextNode = node.next();
      if (this.L(nextNode)) {
        value += "\n";
        if (nextNode.piece.length === 1) {
          $bI(this, nextNode);
        } else {
          const piece = nextNode.piece;
          const newStart = { line: piece.start.line + 1, column: 0 };
          const newLength = piece.length - 1;
          const newLineFeedCnt = this.t(piece.bufferIndex, newStart, piece.end);
          nextNode.piece = new $nI(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
          $dI(this, nextNode, -1, -1);
        }
        return true;
      }
    }
    return false;
  }
  // #endregion
  // #endregion
  // #region Tree operations
  iterate(node, callback) {
    if (node === $9H) {
      return callback($9H);
    }
    const leftRet = this.iterate(node.left, callback);
    if (!leftRet) {
      return leftRet;
    }
    return callback(node) && this.iterate(node.right, callback);
  }
  R(node) {
    if (node === $9H) {
      return "";
    }
    const buffer = this.a[node.piece.bufferIndex];
    const piece = node.piece;
    const startOffset = this.u(piece.bufferIndex, piece.start);
    const endOffset = this.u(piece.bufferIndex, piece.end);
    const currentContent = buffer.buffer.substring(startOffset, endOffset);
    return currentContent;
  }
  getPieceContent(piece) {
    const buffer = this.a[piece.bufferIndex];
    const startOffset = this.u(piece.bufferIndex, piece.start);
    const endOffset = this.u(piece.bufferIndex, piece.end);
    const currentContent = buffer.buffer.substring(startOffset, endOffset);
    return currentContent;
  }
  /**
   *      node              node
   *     /  \              /  \
   *    a   b    <----   a    b
   *                         /
   *                        z
   */
  S(node, p) {
    const z = new $8H(
      p,
      1
      /* NodeColor.Red */
    );
    z.left = $9H;
    z.right = $9H;
    z.parent = $9H;
    z.size_left = 0;
    z.lf_left = 0;
    const x = this.root;
    if (x === $9H) {
      this.root = z;
      z.color = 0;
    } else if (node.right === $9H) {
      node.right = z;
      z.parent = node;
    } else {
      const nextNode = $0H(node.right);
      nextNode.left = z;
      z.parent = nextNode;
    }
    $cI(this, z);
    return z;
  }
  /**
   *      node              node
   *     /  \              /  \
   *    a   b     ---->   a    b
   *                       \
   *                        z
   */
  T(node, p) {
    const z = new $8H(
      p,
      1
      /* NodeColor.Red */
    );
    z.left = $9H;
    z.right = $9H;
    z.parent = $9H;
    z.size_left = 0;
    z.lf_left = 0;
    if (this.root === $9H) {
      this.root = z;
      z.color = 0;
    } else if (node.left === $9H) {
      node.left = z;
      z.parent = node;
    } else {
      const prevNode = $$H(node.left);
      prevNode.right = z;
      z.parent = prevNode;
    }
    $cI(this, z);
    return z;
  }
  U(node) {
    let str = "";
    this.iterate(node, (node2) => {
      str += this.R(node2);
      return true;
    });
    return str;
  }
};

// out-build/vs/editor/common/core/eolCounter.js
var StringEOL;
(function(StringEOL2) {
  StringEOL2[StringEOL2["Unknown"] = 0] = "Unknown";
  StringEOL2[StringEOL2["Invalid"] = 3] = "Invalid";
  StringEOL2[StringEOL2["LF"] = 1] = "LF";
  StringEOL2[StringEOL2["CRLF"] = 2] = "CRLF";
})(StringEOL || (StringEOL = {}));
function $tE(text) {
  let eolCount = 0;
  let firstLineLength = 0;
  let lastLineStart = 0;
  let eol = 0;
  for (let i = 0, len = text.length; i < len; i++) {
    const chr = text.charCodeAt(i);
    if (chr === 13) {
      if (eolCount === 0) {
        firstLineLength = i;
      }
      eolCount++;
      if (i + 1 < len && text.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 = text.length;
  }
  return [eolCount, firstLineLength, text.length - lastLineStart, eol];
}

// out-build/vs/editor/common/core/stringBuilder.js
var _utf16LE_TextDecoder;
function getUTF16LE_TextDecoder() {
  if (!_utf16LE_TextDecoder) {
    _utf16LE_TextDecoder = new TextDecoder("UTF-16LE");
  }
  return _utf16LE_TextDecoder;
}
function $bE(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 result = [];
  let resultLen = 0;
  for (let i = 0; i < len; i++) {
    const charCode = $Ei(source, offset);
    offset += 2;
    result[resultLen++] = String.fromCharCode(charCode);
  }
  return result.join("");
}

// out-build/vs/editor/common/core/textChange.js
function escapeNewLine(str) {
  return str.replace(/\n/g, "\\n").replace(/\r/g, "\\r");
}
var $dE = class _$dE {
  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 a(str) {
    return 4 + 2 * str.length;
  }
  static c(b, str, offset) {
    const len = str.length;
    $Hi(b, len, offset);
    offset += 4;
    for (let i = 0; i < len; i++) {
      $Fi(b, str.charCodeAt(i), offset);
      offset += 2;
    }
    return offset;
  }
  static d(b, offset) {
    const len = $Gi(b, offset);
    offset += 4;
    return $bE(b, offset, len);
  }
  writeSize() {
    return 4 + 4 + _$dE.a(this.oldText) + _$dE.a(this.newText);
  }
  write(b, offset) {
    $Hi(b, this.oldPosition, offset);
    offset += 4;
    $Hi(b, this.newPosition, offset);
    offset += 4;
    offset = _$dE.c(b, this.oldText, offset);
    offset = _$dE.c(b, this.newText, offset);
    return offset;
  }
  static read(b, offset, dest) {
    const oldPosition = $Gi(b, offset);
    offset += 4;
    const newPosition = $Gi(b, offset);
    offset += 4;
    const oldText = _$dE.d(b, offset);
    offset += _$dE.a(oldText);
    const newText = _$dE.d(b, offset);
    offset += _$dE.a(newText);
    dest.push(new _$dE(oldPosition, oldText, newPosition, newText));
    return offset;
  }
};

// out-build/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer.js
var $qI = class _$qI extends $3c {
  constructor(chunks, BOM, eol, containsRTL, containsUnusualLineTerminators, isBasicASCII, eolNormalized) {
    super();
    this.m = this.B(new $ze());
    this.onDidChangeContent = this.m.event;
    this.f = BOM;
    this.j = !isBasicASCII;
    this.g = containsRTL;
    this.h = containsUnusualLineTerminators;
    this.c = new $pI(chunks, eol, eolNormalized);
  }
  // #region TextBuffer
  equals(other) {
    if (!(other instanceof _$qI)) {
      return false;
    }
    if (this.f !== other.f) {
      return false;
    }
    if (this.getEOL() !== other.getEOL()) {
      return false;
    }
    return this.c.equal(other.c);
  }
  mightContainRTL() {
    return this.g;
  }
  mightContainUnusualLineTerminators() {
    return this.h;
  }
  resetMightContainUnusualLineTerminators() {
    this.h = false;
  }
  mightContainNonBasicASCII() {
    return this.j;
  }
  getBOM() {
    return this.f;
  }
  getEOL() {
    return this.c.getEOL();
  }
  createSnapshot(preserveBOM) {
    return this.c.createSnapshot(preserveBOM ? this.f : "");
  }
  getOffsetAt(lineNumber, column) {
    return this.c.getOffsetAt(lineNumber, column);
  }
  getPositionAt(offset) {
    return this.c.getPositionAt(offset);
  }
  getRangeAt(start, length) {
    const end = start + length;
    const startPosition = this.getPositionAt(start);
    const endPosition = this.getPositionAt(end);
    return new $9C(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
  }
  getValueInRange(range, eol = 0) {
    if (range.isEmpty()) {
      return "";
    }
    const lineEnding = this.n(eol);
    return this.c.getValueInRange(range, lineEnding);
  }
  getValueLengthInRange(range, eol = 0) {
    if (range.isEmpty()) {
      return 0;
    }
    if (range.startLineNumber === range.endLineNumber) {
      return range.endColumn - range.startColumn;
    }
    const startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn);
    const endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn);
    let eolOffsetCompensation = 0;
    const desiredEOL = this.n(eol);
    const actualEOL = this.getEOL();
    if (desiredEOL.length !== actualEOL.length) {
      const delta2 = desiredEOL.length - actualEOL.length;
      const eolCount = range.endLineNumber - range.startLineNumber;
      eolOffsetCompensation = delta2 * eolCount;
    }
    return endOffset - startOffset + eolOffsetCompensation;
  }
  getCharacterCountInRange(range, eol = 0) {
    if (this.j) {
      let result = 0;
      const fromLineNumber = range.startLineNumber;
      const toLineNumber = range.endLineNumber;
      for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
        const lineContent = this.getLineContent(lineNumber);
        const fromOffset = lineNumber === fromLineNumber ? range.startColumn - 1 : 0;
        const toOffset = lineNumber === toLineNumber ? range.endColumn - 1 : lineContent.length;
        for (let offset = fromOffset; offset < toOffset; offset++) {
          if ($5f(lineContent.charCodeAt(offset))) {
            result = result + 1;
            offset = offset + 1;
          } else {
            result = result + 1;
          }
        }
      }
      result += this.n(eol).length * (toLineNumber - fromLineNumber);
      return result;
    }
    return this.getValueLengthInRange(range, eol);
  }
  getNearestChunk(offset) {
    return this.c.getNearestChunk(offset);
  }
  getLength() {
    return this.c.getLength();
  }
  getLineCount() {
    return this.c.getLineCount();
  }
  getLinesContent() {
    return this.c.getLinesContent();
  }
  getLineContent(lineNumber) {
    return this.c.getLineContent(lineNumber);
  }
  getLineCharCode(lineNumber, index) {
    return this.c.getLineCharCode(lineNumber, index);
  }
  getCharCode(offset) {
    return this.c.getCharCode(offset);
  }
  getLineLength(lineNumber) {
    return this.c.getLineLength(lineNumber);
  }
  getLineMinColumn(lineNumber) {
    return 1;
  }
  getLineMaxColumn(lineNumber) {
    return this.getLineLength(lineNumber) + 1;
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    const result = $Of(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 1;
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    const result = $Qf(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 2;
  }
  n(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.c.setEOL(newEOL);
  }
  applyEdits(rawOperations, recordTrimAutoWhitespace, computeUndoEdits) {
    let mightContainRTL = this.g;
    let mightContainUnusualLineTerminators = this.h;
    let mightContainNonBasicASCII = this.j;
    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 = !$dg(op.text);
          mightContainNonBasicASCII = textMightContainNonBasicASCII;
        }
        if (!mightContainRTL && textMightContainNonBasicASCII) {
          mightContainRTL = $cg(op.text);
        }
        if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) {
          mightContainUnusualLineTerminators = $fg(op.text);
        }
      }
      let validText = "";
      let eolCount = 0;
      let firstLineLength = 0;
      let lastLineLength = 0;
      if (op.text) {
        let strEOL;
        [eolCount, firstLineLength, lastLineLength, strEOL] = $tE(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,
        forceMoveMarkers: Boolean(op.forceMoveMarkers),
        isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
      };
    }
    operations.sort(_$qI.u);
    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.s(operations);
    }
    const reverseRanges = computeUndoEdits || recordTrimAutoWhitespace ? _$qI._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 ($Of(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 $dE(op.rangeOffset, bufferText, reverseRangeOffset, op.text)
        };
      }
      if (!hasTouchingRanges) {
        reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex);
      }
    }
    this.g = mightContainRTL;
    this.h = mightContainUnusualLineTerminators;
    this.j = mightContainNonBasicASCII;
    const contentChanges = this.t(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 || $Of(lineContent) !== -1) {
          continue;
        }
        trimAutoWhitespaceLineNumbers.push(lineNumber);
      }
    }
    this.m.fire();
    return new $jG(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);
  }
  /**
   * Transform operations such that they represent the same logic edit,
   * but that they also do not cause OOM crashes.
   */
  s(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 $9C(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn);
    let lastEndLineNumber = firstEditRange.startLineNumber;
    let lastEndColumn = firstEditRange.startColumn;
    const result = [];
    for (let i = 0, len = operations.length; i < len; i++) {
      const operation = operations[i];
      const range = operation.range;
      forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
      result.push(this.getValueInRange(new $9C(lastEndLineNumber, lastEndColumn, range.startLineNumber, range.startColumn)));
      if (operation.text.length > 0) {
        result.push(operation.text);
      }
      lastEndLineNumber = range.endLineNumber;
      lastEndColumn = range.endColumn;
    }
    const text = result.join("");
    const [eolCount, firstLineLength, lastLineLength] = $tE(text);
    return {
      sortIndex: 0,
      identifier: operations[0].identifier,
      range: entireEditRange,
      rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
      rangeLength: this.getValueLengthInRange(
        entireEditRange,
        0
        /* EndOfLinePreference.TextDefined */
      ),
      text,
      eolCount,
      firstLineLength,
      lastLineLength,
      forceMoveMarkers,
      isAutoWhitespaceEdit: false
    };
  }
  t(operations) {
    operations.sort(_$qI.w);
    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.c.delete(op.rangeOffset, op.rangeLength);
        this.c.insert(op.rangeOffset, op.text, true);
      } else {
        this.c.delete(op.rangeOffset, op.rangeLength);
      }
      const contentChangeRange = new $9C(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.c.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
  }
  // #endregion
  // #region helper
  // testing purpose.
  getPieceTree() {
    return this.c;
  }
  static _getInverseEditRange(range, text) {
    const startLineNumber = range.startLineNumber;
    const startColumn = range.startColumn;
    const [eolCount, firstLineLength, lastLineLength] = $tE(text);
    let resultRange;
    if (text.length > 0) {
      const lineCount = eolCount + 1;
      if (lineCount === 1) {
        resultRange = new $9C(startLineNumber, startColumn, startLineNumber, startColumn + firstLineLength);
      } else {
        resultRange = new $9C(startLineNumber, startColumn, startLineNumber + lineCount - 1, lastLineLength + 1);
      }
    } else {
      resultRange = new $9C(startLineNumber, startColumn, startLineNumber, startColumn);
    }
    return resultRange;
  }
  /**
   * Assumes `operations` are validated and sorted ascending
   */
  static _getInverseEditRanges(operations) {
    const result = [];
    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 $9C(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength);
        } else {
          resultRange = new $9C(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1);
        }
      } else {
        resultRange = new $9C(startLineNumber, startColumn, startLineNumber, startColumn);
      }
      prevOpEndLineNumber = resultRange.endLineNumber;
      prevOpEndColumn = resultRange.endColumn;
      result.push(resultRange);
      prevOp = op;
    }
    return result;
  }
  static u(a, b) {
    const r = $9C.compareRangesUsingEnds(a.range, b.range);
    if (r === 0) {
      return a.sortIndex - b.sortIndex;
    }
    return r;
  }
  static w(a, b) {
    const r = $9C.compareRangesUsingEnds(a.range, b.range);
    if (r === 0) {
      return b.sortIndex - a.sortIndex;
    }
    return -r;
  }
};

// out-build/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder.js
var PieceTreeTextBufferFactory = class {
  constructor(a, b, c, d, e, f, g, h, j) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
  }
  k(defaultEOL) {
    const totalEOLCount = this.c + this.d + this.e;
    const totalCRCount = this.c + this.e;
    if (totalEOLCount === 0) {
      return defaultEOL === 1 ? "\n" : "\r\n";
    }
    if (totalCRCount > totalEOLCount / 2) {
      return "\r\n";
    }
    return "\n";
  }
  create(defaultEOL) {
    const eol = this.k(defaultEOL);
    const chunks = this.a;
    if (this.j && (eol === "\r\n" && (this.c > 0 || this.d > 0) || eol === "\n" && (this.c > 0 || this.e > 0))) {
      for (let i = 0, len = chunks.length; i < len; i++) {
        const str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
        const newLineStart = $lI(str);
        chunks[i] = new $oI(str, newLineStart);
      }
    }
    const textBuffer = new $qI(chunks, this.b, eol, this.f, this.g, this.h, this.j);
    return { textBuffer, disposable: textBuffer };
  }
  getFirstLineText(lengthLimit) {
    return this.a[0].buffer.substr(0, lengthLimit).split(/\r\n|\r|\n/)[0];
  }
};
var $rI = class {
  constructor() {
    this.a = [];
    this.b = "";
    this.c = false;
    this.d = 0;
    this.e = [];
    this.f = 0;
    this.g = 0;
    this.h = 0;
    this.j = false;
    this.k = false;
    this.l = true;
  }
  acceptChunk(chunk) {
    if (chunk.length === 0) {
      return;
    }
    if (this.a.length === 0) {
      if ($ng(chunk)) {
        this.b = $mg;
        chunk = chunk.substr(1);
      }
    }
    const lastChar = chunk.charCodeAt(chunk.length - 1);
    if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
      this.m(chunk.substr(0, chunk.length - 1), false);
      this.c = true;
      this.d = lastChar;
    } else {
      this.m(chunk, false);
      this.c = false;
      this.d = lastChar;
    }
  }
  m(chunk, allowEmptyStrings) {
    if (!allowEmptyStrings && chunk.length === 0) {
      return;
    }
    if (this.c) {
      this.n(String.fromCharCode(this.d) + chunk);
    } else {
      this.n(chunk);
    }
  }
  n(chunk) {
    const lineStarts = $mI(this.e, chunk);
    this.a.push(new $oI(chunk, lineStarts.lineStarts));
    this.f += lineStarts.cr;
    this.g += lineStarts.lf;
    this.h += lineStarts.crlf;
    if (!lineStarts.isBasicASCII) {
      this.l = false;
      if (!this.j) {
        this.j = $cg(chunk);
      }
      if (!this.k) {
        this.k = $fg(chunk);
      }
    }
  }
  finish(normalizeEOL = true) {
    this.o();
    return new PieceTreeTextBufferFactory(this.a, this.b, this.f, this.g, this.h, this.j, this.k, this.l, normalizeEOL);
  }
  o() {
    if (this.a.length === 0) {
      this.m("", true);
    }
    if (this.c) {
      this.c = false;
      const lastChunk = this.a[this.a.length - 1];
      lastChunk.buffer += String.fromCharCode(this.d);
      const newLineStarts = $lI(lastChunk.buffer);
      lastChunk.lineStarts = newLineStarts;
      if (this.d === 13) {
        this.f++;
      }
    }
  }
};

// out-build/vs/workbench/contrib/search/common/cellSearchModel.js
var $A7b = class extends $3c {
  constructor(_source, b, c) {
    super();
    this._source = _source;
    this.b = b;
    this.c = c;
    this.a = void 0;
  }
  f(buffer) {
    const lineCount = buffer.getLineCount();
    return new $9C(1, 1, lineCount, this.g(buffer, lineCount));
  }
  g(buffer, lineNumber) {
    if (lineNumber < 1 || lineNumber > buffer.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    return buffer.getLineLength(lineNumber) + 1;
  }
  get inputTextBuffer() {
    if (!this.b) {
      const builder = new $rI();
      builder.acceptChunk(this._source);
      const bufferFactory = builder.finish(true);
      const { textBuffer, disposable } = bufferFactory.create(
        1
        /* DefaultEndOfLine.LF */
      );
      this.b = textBuffer;
      this.B(disposable);
    }
    return this.b;
  }
  get outputTextBuffers() {
    if (!this.a) {
      this.a = this.c.map((output) => {
        const builder = new $rI();
        builder.acceptChunk(output);
        const bufferFactory = builder.finish(true);
        const { textBuffer, disposable } = bufferFactory.create(
          1
          /* DefaultEndOfLine.LF */
        );
        this.B(disposable);
        return textBuffer;
      });
    }
    return this.a;
  }
  findInInputs(target) {
    const searchParams = new $fI(target, false, false, null);
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return [];
    }
    const fullInputRange = this.f(this.inputTextBuffer);
    return this.inputTextBuffer.findMatchesLineByLine(fullInputRange, searchData, true, 5e3);
  }
  findInOutputs(target) {
    const searchParams = new $fI(target, false, false, null);
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return [];
    }
    return this.outputTextBuffers.map((buffer) => {
      const matches = buffer.findMatchesLineByLine(this.f(buffer), searchData, true, 5e3);
      if (matches.length === 0) {
        return void 0;
      }
      return {
        textBuffer: buffer,
        matches
      };
    }).filter((item) => !!item);
  }
};

// out-build/vs/workbench/contrib/search/common/searchNotebookHelpers.js
function $iS(contentMatches, buffer) {
  let previousEndLine = -1;
  const contextGroupings = [];
  let currentContextGrouping = [];
  contentMatches.forEach((match) => {
    if (match.range.startLineNumber !== previousEndLine) {
      if (currentContextGrouping.length > 0) {
        contextGroupings.push([...currentContextGrouping]);
        currentContextGrouping = [];
      }
    }
    currentContextGrouping.push(match);
    previousEndLine = match.range.endLineNumber;
  });
  if (currentContextGrouping.length > 0) {
    contextGroupings.push([...currentContextGrouping]);
  }
  const textSearchResults = contextGroupings.map((grouping) => {
    const lineTexts = [];
    const firstLine = grouping[0].range.startLineNumber;
    const lastLine = grouping[grouping.length - 1].range.endLineNumber;
    for (let i = firstLine; i <= lastLine; i++) {
      lineTexts.push(buffer.getLineContent(i));
    }
    return new $YN(lineTexts.join("\n") + "\n", grouping.map((m) => new $9C(m.range.startLineNumber - 1, m.range.startColumn - 1, m.range.endLineNumber - 1, m.range.endColumn - 1)));
  });
  return textSearchResults;
}

// out-build/vs/workbench/common/configuration.js
var $TL = Object.freeze({
  "id": "application",
  "order": 100,
  "title": localize(4053, null),
  "type": "object"
});
var $UL = Object.freeze({
  "id": "workbench",
  "order": 7,
  "title": localize(4054, null),
  "type": "object"
});
var $VL = Object.freeze({
  "id": "security",
  "scope": 1,
  "title": localize(4055, null),
  "type": "object",
  "order": 7
});
var $WL = Object.freeze({
  "id": "problems",
  "title": localize(4056, null),
  "type": "object",
  "order": 101
});
var $XL = Object.freeze({
  "id": "window",
  "order": 8,
  "title": localize(4057, null),
  "type": "object"
});
var $YL = {
  ConfigurationMigration: "base.contributions.configuration.migration"
};
var ConfigurationMigrationRegistry = class {
  constructor() {
    this.migrations = [];
    this.a = new $ze();
    this.onDidRegisterConfigurationMigration = this.a.event;
  }
  registerConfigurationMigrations(configurationMigrations) {
    this.migrations.push(...configurationMigrations);
  }
};
var configurationMigrationRegistry = new ConfigurationMigrationRegistry();
$Wn.add($YL.ConfigurationMigration, configurationMigrationRegistry);
var $ZL = class $ZL2 extends $3c {
  static {
    this.ID = "workbench.contrib.configurationMigration";
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(this.b.onDidChangeWorkspaceFolders(async (e) => {
      for (const folder of e.added) {
        await this.f(folder, configurationMigrationRegistry.migrations);
      }
    }));
    this.c(configurationMigrationRegistry.migrations);
    this.B(configurationMigrationRegistry.onDidRegisterConfigurationMigration((migration) => this.c(migration)));
  }
  async c(migrations) {
    await this.f(void 0, migrations);
    for (const folder of this.b.getWorkspace().folders) {
      await this.f(folder, migrations);
    }
  }
  async f(folder, migrations) {
    await Promise.all([migrations.map((migration) => this.g(migration, folder?.uri))]);
  }
  async g(migration, resource) {
    const inspectData = this.a.inspect(migration.key, { resource });
    const targetPairs = this.b.getWorkbenchState() === 3 ? [
      [
        "user",
        2
        /* ConfigurationTarget.USER */
      ],
      [
        "userLocal",
        3
        /* ConfigurationTarget.USER_LOCAL */
      ],
      [
        "userRemote",
        4
        /* ConfigurationTarget.USER_REMOTE */
      ],
      [
        "workspace",
        5
        /* ConfigurationTarget.WORKSPACE */
      ],
      [
        "workspaceFolder",
        6
        /* ConfigurationTarget.WORKSPACE_FOLDER */
      ]
    ] : [
      [
        "user",
        2
        /* ConfigurationTarget.USER */
      ],
      [
        "userLocal",
        3
        /* ConfigurationTarget.USER_LOCAL */
      ],
      [
        "userRemote",
        4
        /* ConfigurationTarget.USER_REMOTE */
      ],
      [
        "workspace",
        5
        /* ConfigurationTarget.WORKSPACE */
      ]
    ];
    for (const [dataKey, target] of targetPairs) {
      const inspectValue = inspectData[dataKey];
      if (!inspectValue) {
        continue;
      }
      const migrationValues = [];
      if (inspectValue.value !== void 0) {
        const keyValuePairs = await this.h(migration, dataKey, inspectValue.value, resource, void 0);
        for (const keyValuePair of keyValuePairs ?? []) {
          migrationValues.push([keyValuePair, []]);
        }
      }
      for (const { identifiers: identifiers2, value } of inspectValue.overrides ?? []) {
        if (value !== void 0) {
          const keyValuePairs = await this.h(migration, dataKey, value, resource, identifiers2);
          for (const keyValuePair of keyValuePairs ?? []) {
            migrationValues.push([keyValuePair, identifiers2]);
          }
        }
      }
      if (migrationValues.length) {
        await Promise.allSettled(migrationValues.map(async ([[key, value], overrideIdentifiers]) => this.a.updateValue(key, value.value, { resource, overrideIdentifiers }, target)));
      }
    }
  }
  async h(migration, dataKey, value, resource, overrideIdentifiers) {
    const valueAccessor = (key) => {
      const inspectData = this.a.inspect(key, { resource });
      const inspectValue = inspectData[dataKey];
      if (!inspectValue) {
        return void 0;
      }
      if (!overrideIdentifiers) {
        return inspectValue.value;
      }
      return inspectValue.overrides?.find(({ identifiers: identifiers2 }) => $Pv(identifiers2, overrideIdentifiers))?.value;
    };
    const result = await migration.migrateFn(value, valueAccessor);
    return Array.isArray(result) ? result : [[migration.key, result]];
  }
};
$ZL = __decorate([
  __param(0, $kl),
  __param(1, $Zk)
], $ZL);
var $1L = class $1L2 extends $3c {
  static {
    this.ID = "workbench.contrib.dynamicWorkbenchSecurityConfiguration";
  }
  constructor(b) {
    super();
    this.b = b;
    this.a = new $gi();
    this.ready = this.a.p;
    this.c();
  }
  async c() {
    try {
      await this.f();
    } finally {
      this.a.complete();
    }
  }
  async f() {
    if (!$l) {
      const remoteEnvironment = await this.b.getEnvironment();
      if (remoteEnvironment?.os !== 1) {
        return;
      }
    }
    const registry = $Wn.as($Ht.Configuration);
    registry.registerConfiguration({
      ...$VL,
      "properties": {
        "security.allowedUNCHosts": {
          "type": "array",
          "items": {
            "type": "string",
            "pattern": "^[^\\\\]+$",
            "patternErrorMessage": localize(4058, null)
          },
          "default": [],
          "markdownDescription": localize(4059, null),
          "scope": 2
          /* ConfigurationScope.MACHINE */
        },
        "security.restrictUNCAccess": {
          "type": "boolean",
          "default": true,
          "markdownDescription": localize(4060, null),
          "scope": 2
          /* ConfigurationScope.MACHINE */
        }
      }
    });
  }
};
$1L = __decorate([
  __param(0, $RL)
], $1L);
var $2L = "window.newWindowProfile";
var $3L = class $3L2 extends $3c {
  static {
    this.ID = "workbench.contrib.dynamicWindowConfiguration";
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.g();
    this.B(this.c.onDidChangeProfiles((e) => this.g()));
    this.h();
    this.j();
    this.B(f.onDidChangeConfiguration((e) => {
      if (e.source !== 7 && e.affectsConfiguration($2L)) {
        this.h();
      }
    }));
    this.B(this.c.onDidChangeProfiles(() => this.j()));
  }
  g() {
    const registry = $Wn.as($Ht.Configuration);
    const configurationNode = {
      ...$XL,
      "properties": {
        [$2L]: {
          "type": ["string", "null"],
          "default": null,
          "enum": [...this.c.profiles.map((profile) => profile.name), null],
          "enumItemLabels": [...this.c.profiles.map((p) => ""), localize(4061, null)],
          "description": localize(4062, null),
          "scope": 1
        }
      }
    };
    if (this.a) {
      registry.updateConfigurations({ add: [configurationNode], remove: [this.a] });
    } else {
      registry.registerConfiguration(configurationNode);
    }
    this.a = configurationNode;
  }
  h() {
    const newWindowProfileName = this.f.getValue($2L);
    this.b = newWindowProfileName ? this.c.profiles.find((profile) => profile.name === newWindowProfileName) : void 0;
  }
  j() {
    const newWindowProfileName = this.f.getValue($2L);
    if (!newWindowProfileName) {
      return;
    }
    const profile = this.b ? this.c.profiles.find((profile2) => profile2.id === this.b.id) : void 0;
    if (newWindowProfileName === profile?.name) {
      return;
    }
    this.f.updateValue($2L, profile?.name);
  }
};
$3L = __decorate([
  __param(0, $rs),
  __param(1, $kl)
], $3L);

// out-build/vs/workbench/services/editor/common/editorResolverService.js
var $4L = $Qk("editorResolverService");
var configurationRegistry2 = $Wn.as($Ht.Configuration);
var editorAssociationsConfigurationNode = {
  ...$UL,
  properties: {
    "workbench.editorAssociations": {
      type: "object",
      markdownDescription: localize(12702, null),
      additionalProperties: {
        type: "string"
      }
    }
  }
};
configurationRegistry2.registerConfiguration(editorAssociationsConfigurationNode);
var RegisteredEditorPriority;
(function(RegisteredEditorPriority2) {
  RegisteredEditorPriority2["builtin"] = "builtin";
  RegisteredEditorPriority2["option"] = "option";
  RegisteredEditorPriority2["exclusive"] = "exclusive";
  RegisteredEditorPriority2["default"] = "default";
})(RegisteredEditorPriority || (RegisteredEditorPriority = {}));
var ResolvedStatus;
(function(ResolvedStatus2) {
  ResolvedStatus2[ResolvedStatus2["ABORT"] = 1] = "ABORT";
  ResolvedStatus2[ResolvedStatus2["NONE"] = 2] = "NONE";
})(ResolvedStatus || (ResolvedStatus = {}));
function $7L(globPattern, resource) {
  const excludedSchemes = /* @__PURE__ */ new Set([
    Schemas.extension,
    Schemas.webviewPanel,
    Schemas.vscodeWorkspaceTrust,
    Schemas.vscodeSettings
  ]);
  if (excludedSchemes.has(resource.scheme)) {
    return false;
  }
  const matchOnPath = typeof globPattern === "string" && globPattern.indexOf($kc.sep) >= 0;
  const target = matchOnPath ? `${resource.scheme}:${resource.path}` : $sh(resource);
  return $Cl(typeof globPattern === "string" ? globPattern.toLowerCase() : globPattern, target.toLowerCase());
}

// out-build/vs/workbench/api/common/extHostNotebook.js
var $nyc = class _$nyc {
  static {
    this.a = 0;
  }
  get activeNotebookEditor() {
    return this.k?.apiEditor;
  }
  get visibleNotebookEditors() {
    return this.l.map((editor) => editor.apiEditor);
  }
  constructor(mainContext, commands, q, r, s, t, u) {
    this.q = q;
    this.r = r;
    this.s = s;
    this.t = t;
    this.u = u;
    this.f = /* @__PURE__ */ new Map();
    this.g = new $Ec();
    this.h = /* @__PURE__ */ new Map();
    this.j = new $ze();
    this.onDidChangeActiveNotebookEditor = this.j.event;
    this.l = [];
    this.m = new $ze();
    this.onDidOpenNotebookDocument = this.m.event;
    this.n = new $ze();
    this.onDidCloseNotebookDocument = this.n.event;
    this.o = new $ze();
    this.onDidChangeVisibleNotebookEditors = this.o.event;
    this.p = new $Jwc("NotebookCellStatusBarCache");
    this.x = 0;
    this.y = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadNotebook);
    this.c = mainContext.getProxy($xT.MainThreadNotebookDocuments);
    this.d = mainContext.getProxy($xT.MainThreadNotebookEditors);
    this.i = commands.converter;
    commands.registerArgumentProcessor({
      // Serialized INotebookCellActionContext
      processArgument: (arg) => {
        if (arg && arg.$mid === 13) {
          const notebookUri = arg.notebookEditor?.notebookUri;
          const cellHandle = arg.cell.handle;
          const data = this.g.get(notebookUri);
          const cell = data?.getCell(cellHandle);
          if (cell) {
            return cell.apiCell;
          }
        }
        if (arg && arg.$mid === 14) {
          const notebookUri = arg.uri;
          const data = this.g.get(notebookUri);
          if (data) {
            return data.apiNotebook;
          }
        }
        return arg;
      }
    });
    _$nyc.C(commands);
  }
  getEditorById(editorId) {
    const editor = this.h.get(editorId);
    if (!editor) {
      throw new Error(`unknown text editor: ${editorId}. known editors: ${[...this.h.keys()]} `);
    }
    return editor;
  }
  getIdByEditor(editor) {
    for (const [id2, candidate] of this.h) {
      if (candidate.apiEditor === editor) {
        return id2;
      }
    }
    return void 0;
  }
  get notebookDocuments() {
    return [...this.g.values()];
  }
  getNotebookDocument(uri, relaxed) {
    const result = this.g.get(uri);
    if (!result && !relaxed) {
      throw new Error(`NO notebook document for '${uri}'`);
    }
    return result;
  }
  static w(extension, registration) {
    if (!registration) {
      return;
    }
    const viewOptionsFilenamePattern = registration.filenamePattern.map((pattern) => NotebookExclusiveDocumentPattern.from(pattern)).filter((pattern) => pattern !== void 0);
    if (registration.filenamePattern && !viewOptionsFilenamePattern) {
      console.warn(`Notebook content provider view options file name pattern is invalid ${registration.filenamePattern}`);
      return void 0;
    }
    return {
      extension: extension.identifier,
      providerDisplayName: extension.displayName || extension.name,
      displayName: registration.displayName,
      filenamePattern: viewOptionsFilenamePattern,
      priority: registration.exclusive ? RegisteredEditorPriority.exclusive : void 0
    };
  }
  registerNotebookCellStatusBarItemProvider(extension, notebookType, provider) {
    const handle = _$nyc.a++;
    const eventHandle = typeof provider.onDidChangeCellStatusBarItems === "function" ? _$nyc.a++ : void 0;
    this.f.set(handle, provider);
    this.b.$registerNotebookCellStatusBarItemProvider(handle, eventHandle, notebookType);
    let subscription;
    if (eventHandle !== void 0) {
      subscription = provider.onDidChangeCellStatusBarItems((_) => this.b.$emitCellStatusBarEvent(eventHandle));
    }
    return new $zT(() => {
      this.f.delete(handle);
      this.b.$unregisterNotebookCellStatusBarItemProvider(handle, eventHandle);
      subscription?.dispose();
    });
  }
  async createNotebookDocument(options2) {
    const canonicalUri = await this.c.$tryCreateNotebook({
      viewType: options2.viewType,
      content: options2.content && NotebookData.from(options2.content)
    });
    return URI.revive(canonicalUri);
  }
  async openNotebookDocument(uri) {
    const cached = this.g.get(uri);
    if (cached) {
      return cached.apiNotebook;
    }
    const canonicalUri = await this.c.$tryOpenNotebook(uri);
    const document2 = this.g.get(URI.revive(canonicalUri));
    return $Kg(document2?.apiNotebook);
  }
  async showNotebookDocument(notebook, options2) {
    let resolvedOptions;
    if (typeof options2 === "object") {
      resolvedOptions = {
        position: ViewColumn2.from(options2.viewColumn),
        preserveFocus: options2.preserveFocus,
        selections: options2.selections && options2.selections.map(NotebookRange.from),
        pinned: typeof options2.preview === "boolean" ? !options2.preview : void 0,
        label: typeof options2.asRepl === "string" ? options2.asRepl : typeof options2.asRepl === "object" ? options2.asRepl.label : void 0
      };
    } else {
      resolvedOptions = {
        preserveFocus: false,
        pinned: true
      };
    }
    const viewType = !!options2?.asRepl ? "repl" : notebook.notebookType;
    const editorId = await this.d.$tryShowNotebookDocument(notebook.uri, viewType, resolvedOptions);
    const editor = editorId && this.h.get(editorId)?.apiEditor;
    if (editor) {
      return editor;
    }
    if (editorId) {
      throw new Error(`Could NOT open editor for "${notebook.uri.toString()}" because another editor opened in the meantime.`);
    } else {
      throw new Error(`Could NOT open editor for "${notebook.uri.toString()}".`);
    }
  }
  async $provideNotebookCellStatusBarItems(handle, uri, index, token) {
    const provider = this.f.get(handle);
    const revivedUri = URI.revive(uri);
    const document2 = this.g.get(revivedUri);
    if (!document2 || !provider) {
      return;
    }
    const cell = document2.getCellFromIndex(index);
    if (!cell) {
      return;
    }
    const result = await provider.provideCellStatusBarItems(cell.apiCell, token);
    if (!result) {
      return void 0;
    }
    const disposables = new $2c();
    const cacheId = this.p.add([disposables]);
    const resultArr = Array.isArray(result) ? result : [result];
    const items = resultArr.map((item) => NotebookStatusBarItem.from(item, this.i, disposables));
    return {
      cacheId,
      items
    };
  }
  $releaseNotebookCellStatusBarItems(cacheId) {
    this.p.delete(cacheId);
  }
  registerNotebookSerializer(extension, viewType, serializer, options2, registration) {
    if ($vf(viewType)) {
      throw new Error(`viewType cannot be empty or just whitespace`);
    }
    const handle = this.x++;
    this.y.set(handle, { viewType, serializer, options: options2 });
    this.b.$registerNotebookSerializer(handle, { id: extension.identifier, location: extension.extensionLocation }, viewType, NotebookDocumentContentOptions.from(options2), _$nyc.w(extension, registration));
    return $1c(() => {
      this.b.$unregisterNotebookSerializer(handle);
    });
  }
  async $dataToNotebook(handle, bytes, token) {
    const serializer = this.y.get(handle);
    if (!serializer) {
      throw new Error("NO serializer found");
    }
    const data = await serializer.serializer.deserializeNotebook(bytes.buffer, token);
    return new $ES(NotebookData.from(data));
  }
  async $notebookToData(handle, data, token) {
    const serializer = this.y.get(handle);
    if (!serializer) {
      throw new Error("NO serializer found");
    }
    const bytes = await serializer.serializer.serializeNotebook(NotebookData.to(data.value), token);
    return $Ci.wrap(bytes);
  }
  async $saveNotebook(handle, uriComponents, versionId, options2, token) {
    const uri = URI.revive(uriComponents);
    const serializer = this.y.get(handle);
    this.D(`enter saveNotebook(versionId: ${versionId}, ${uri.toString()})`);
    if (!serializer) {
      throw new Error("NO serializer found");
    }
    const document2 = this.g.get(uri);
    if (!document2) {
      throw new Error("Document NOT found");
    }
    if (document2.versionId !== versionId) {
      throw new Error("Document version mismatch");
    }
    if (!this.s.value.isWritableFileSystem(uri.scheme)) {
      throw new $Fm(
        localize(2763, null, this.A(uri)),
        6
        /* files.FileOperationResult.FILE_PERMISSION_DENIED */
      );
    }
    const data = {
      metadata: $Tv(document2.apiNotebook.metadata, (key) => !(serializer.options?.transientDocumentMetadata ?? {})[key]),
      cells: []
    };
    for (const cell of document2.apiNotebook.getCells()) {
      const cellData = new $7U(cell.kind, cell.document.getText(), cell.document.languageId, cell.mime, !serializer.options?.transientOutputs ? [...cell.outputs] : [], cell.metadata, cell.executionSummary);
      cellData.metadata = $Tv(cell.metadata, (key) => !(serializer.options?.transientCellMetadata ?? {})[key]);
      data.cells.push(cellData);
    }
    await this.z(uri, options2);
    if (token.isCancellationRequested) {
      throw new Error("canceled");
    }
    const bytes = await serializer.serializer.serializeNotebook(data, token);
    if (token.isCancellationRequested) {
      throw new Error("canceled");
    }
    this.D(`serialized versionId: ${versionId} ${uri.toString()}`);
    await this.s.value.writeFile(uri, bytes);
    this.D(`Finished write versionId: ${versionId} ${uri.toString()}`);
    const providerExtUri = this.s.getFileSystemProviderExtUri(uri.scheme);
    const stat2 = await this.s.value.stat(uri);
    const fileStats = {
      name: providerExtUri.basename(uri),
      isFile: (stat2.type & FileType.File) !== 0,
      isDirectory: (stat2.type & FileType.Directory) !== 0,
      isSymbolicLink: (stat2.type & FileType.SymbolicLink) !== 0,
      mtime: stat2.mtime,
      ctime: stat2.ctime,
      size: stat2.size,
      readonly: Boolean((stat2.permissions ?? 0) & FilePermission.Readonly) || !this.s.value.isWritableFileSystem(uri.scheme),
      locked: Boolean((stat2.permissions ?? 0) & FilePermission.Locked),
      etag: $Qm({ mtime: stat2.mtime, size: stat2.size }),
      children: void 0
    };
    this.D(`exit saveNotebook(versionId: ${versionId}, ${uri.toString()})`);
    return fileStats;
  }
  /**
   * Search for query in all notebooks that can be deserialized by the serializer fetched by `handle`.
   *
   * @param handle used to get notebook serializer
   * @param textQuery the text query to search using
   * @param viewTypeFileTargets the globs (and associated ranks) that are targetting for opening this type of notebook
   * @param otherViewTypeFileTargets ranked globs for other editors that we should consider when deciding whether it will open as this notebook
   * @param token cancellation token
   * @returns `IRawClosedNotebookFileMatch` for every file. Files without matches will just have a `IRawClosedNotebookFileMatch`
   * 	with no `cellResults`. This allows the caller to know what was searched in already, even if it did not yield results.
   */
  async $searchInNotebooks(handle, textQuery, viewTypeFileTargets, otherViewTypeFileTargets, token) {
    const serializer = this.y.get(handle)?.serializer;
    if (!serializer) {
      return {
        limitHit: false,
        results: []
      };
    }
    const finalMatchedTargets = new $Fc();
    const runFileQueries = async (includes, token2, textQuery2) => {
      await Promise.all(includes.map(async (include) => await Promise.all(include.filenamePatterns.map((filePattern) => {
        const query = {
          _reason: textQuery2._reason,
          folderQueries: textQuery2.folderQueries,
          includePattern: textQuery2.includePattern,
          excludePattern: textQuery2.excludePattern,
          maxResults: textQuery2.maxResults,
          type: 1,
          filePattern
        };
        return this.t.doInternalFileSearchWithCustomCallback(query, token2, (data) => {
          data.forEach((uri) => {
            if (finalMatchedTargets.has(uri)) {
              return;
            }
            const hasOtherMatches = otherViewTypeFileTargets.some((target) => {
              if (include.isFromSettings && !target.isFromSettings) {
                return false;
              } else {
                return target.filenamePatterns.some((targetFilePattern) => $7L(targetFilePattern, uri));
              }
            });
            if (hasOtherMatches) {
              return;
            }
            finalMatchedTargets.add(uri);
          });
        }).catch((err) => {
          if (err.code === "ENOENT") {
            console.warn(`Could not find notebook search results, ignoring notebook results.`);
            return {
              limitHit: false,
              messages: []
            };
          } else {
            throw err;
          }
        });
      }))));
      return;
    };
    await runFileQueries(viewTypeFileTargets, token, textQuery);
    const results = new $Ec();
    let limitHit = false;
    const promises8 = Array.from(finalMatchedTargets).map(async (uri) => {
      const cellMatches = [];
      try {
        if (token.isCancellationRequested) {
          return;
        }
        if (textQuery.maxResults && [...results.values()].reduce((acc, value) => acc + value.cellResults.length, 0) > textQuery.maxResults) {
          limitHit = true;
          return;
        }
        const simpleCells = [];
        const notebook = this.g.get(uri);
        if (notebook) {
          const cells = notebook.apiNotebook.getCells();
          cells.forEach((e) => simpleCells.push({
            input: e.document.getText(),
            outputs: e.outputs.flatMap((value) => value.items.map((output) => output.data.toString()))
          }));
        } else {
          const fileContent = await this.s.value.readFile(uri);
          const bytes = $Ci.fromString(fileContent.toString());
          const notebook2 = await serializer.deserializeNotebook(bytes.buffer, token);
          if (token.isCancellationRequested) {
            return;
          }
          const data = NotebookData.from(notebook2);
          data.cells.forEach((cell) => simpleCells.push({
            input: cell.source,
            outputs: cell.outputs.flatMap((value) => value.items.map((output) => output.valueBytes.toString()))
          }));
        }
        if (token.isCancellationRequested) {
          return;
        }
        simpleCells.forEach((cell, index) => {
          const target = textQuery.contentPattern.pattern;
          const cellModel = new $A7b(cell.input, void 0, cell.outputs);
          const inputMatches = cellModel.findInInputs(target);
          const outputMatches = cellModel.findInOutputs(target);
          const webviewResults = outputMatches.flatMap((outputMatch) => $iS(outputMatch.matches, outputMatch.textBuffer)).map((textMatch, index2) => {
            textMatch.webviewIndex = index2;
            return textMatch;
          });
          if (inputMatches.length > 0 || outputMatches.length > 0) {
            const cellMatch = {
              index,
              contentResults: $iS(inputMatches, cellModel.inputTextBuffer),
              webviewResults
            };
            cellMatches.push(cellMatch);
          }
        });
        const fileMatch = {
          resource: uri,
          cellResults: cellMatches
        };
        results.set(uri, fileMatch);
        return;
      } catch (e) {
        return;
      }
    });
    await Promise.all(promises8);
    return {
      limitHit,
      results: [...results.values()]
    };
  }
  async z(uri, options2) {
    const stat2 = await this.s.value.stat(uri);
    if (typeof options2?.mtime === "number" && typeof options2.etag === "string" && options2.etag !== $Pm && typeof stat2.mtime === "number" && typeof stat2.size === "number" && options2.mtime < stat2.mtime && options2.etag !== $Qm({ mtime: options2.mtime, size: stat2.size })) {
      throw new $Fm(localize(2764, null), 3, options2);
    }
    return;
  }
  A(uri) {
    return uri.scheme === Schemas.file ? uri.fsPath : uri.toString();
  }
  // --- open, save, saveAs, backup
  B(document2, editorId, data) {
    if (this.h.has(editorId)) {
      throw new Error(`editor with id ALREADY EXSIST: ${editorId}`);
    }
    const editor = new $_xc(editorId, this.d, document2, data.visibleRanges.map(NotebookRange.to), data.selections.map(NotebookRange.to), typeof data.viewColumn === "number" ? ViewColumn2.to(data.viewColumn) : void 0, data.viewType);
    this.h.set(editorId, editor);
  }
  $acceptDocumentAndEditorsDelta(delta2) {
    if (delta2.value.removedDocuments) {
      for (const uri of delta2.value.removedDocuments) {
        const revivedUri = URI.revive(uri);
        const document2 = this.g.get(revivedUri);
        if (document2) {
          document2.dispose();
          this.g.delete(revivedUri);
          this.q.$acceptDocumentsAndEditorsDelta({ removedDocuments: document2.apiNotebook.getCells().map((cell) => cell.document.uri) });
          this.n.fire(document2.apiNotebook);
        }
        for (const editor of this.h.values()) {
          if (editor.notebookData.uri.toString() === revivedUri.toString()) {
            this.h.delete(editor.id);
          }
        }
      }
    }
    if (delta2.value.addedDocuments) {
      const addedCellDocuments = [];
      for (const modelData of delta2.value.addedDocuments) {
        const uri = URI.revive(modelData.uri);
        if (this.g.has(uri)) {
          throw new Error(`adding EXISTING notebook ${uri} `);
        }
        const document2 = new $$xc(this.c, this.q, this.r, uri, modelData);
        addedCellDocuments.push(...modelData.cells.map((cell) => $0xc.asModelAddData(cell)));
        this.g.get(uri)?.dispose();
        this.g.set(uri, document2);
        this.q.$acceptDocumentsAndEditorsDelta({ addedDocuments: addedCellDocuments });
        this.m.fire(document2.apiNotebook);
      }
    }
    if (delta2.value.addedEditors) {
      for (const editorModelData of delta2.value.addedEditors) {
        if (this.h.has(editorModelData.id)) {
          return;
        }
        const revivedUri = URI.revive(editorModelData.documentUri);
        const document2 = this.g.get(revivedUri);
        if (document2) {
          this.B(document2, editorModelData.id, editorModelData);
        }
      }
    }
    const removedEditors = [];
    if (delta2.value.removedEditors) {
      for (const editorid of delta2.value.removedEditors) {
        const editor = this.h.get(editorid);
        if (editor) {
          this.h.delete(editorid);
          if (this.k?.id === editor.id) {
            this.k = void 0;
          }
          removedEditors.push(editor);
        }
      }
    }
    if (delta2.value.visibleEditors) {
      this.l = delta2.value.visibleEditors.map((id2) => this.h.get(id2)).filter((editor) => !!editor);
      const visibleEditorsSet = /* @__PURE__ */ new Set();
      this.l.forEach((editor) => visibleEditorsSet.add(editor.id));
      for (const editor of this.h.values()) {
        const newValue = visibleEditorsSet.has(editor.id);
        editor._acceptVisibility(newValue);
      }
      this.l = [...this.h.values()].map((e) => e).filter((e) => e.visible);
      this.o.fire(this.visibleNotebookEditors);
    }
    if (delta2.value.newActiveEditor === null) {
      this.k = void 0;
    } else if (delta2.value.newActiveEditor) {
      const activeEditor = this.h.get(delta2.value.newActiveEditor);
      if (!activeEditor) {
        console.error(`FAILED to find active notebook editor ${delta2.value.newActiveEditor}`);
      }
      this.k = this.h.get(delta2.value.newActiveEditor);
    }
    if (delta2.value.newActiveEditor !== void 0) {
      this.j.fire(this.k?.apiEditor);
    }
  }
  static C(extHostCommands) {
    const notebookTypeArg = $EW.String.with("notebookType", "A notebook type");
    const commandDataToNotebook = new $GW("vscode.executeDataToNotebook", "_executeDataToNotebook", "Invoke notebook serializer", [notebookTypeArg, new $EW("data", "Bytes to convert to data", (v) => v instanceof Uint8Array, (v) => $Ci.wrap(v))], new $FW("Notebook Data", (data) => NotebookData.to(data.value)));
    const commandNotebookToData = new $GW("vscode.executeNotebookToData", "_executeNotebookToData", "Invoke notebook serializer", [notebookTypeArg, new $EW("NotebookData", "Notebook data to convert to bytes", (v) => true, (v) => new $ES(NotebookData.from(v)))], new $FW("Bytes", (dto) => dto.buffer));
    extHostCommands.registerApiCommand(commandDataToNotebook);
    extHostCommands.registerApiCommand(commandNotebookToData);
  }
  D(msg) {
    this.u.trace(`[Extension Host Notebook] ${msg}`);
  }
};

// out-build/vs/workbench/api/common/extHostNotebookDocumentSaveParticipant.js
var $tyc = class {
  constructor(b, c, d, f = { timeout: 1500, errors: 3 }) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.a = new $Be();
  }
  dispose() {
  }
  getOnWillSaveNotebookDocumentEvent(extension) {
    return (listener, thisArg, disposables) => {
      const wrappedListener = function wrapped(e) {
        listener.call(thisArg, e);
      };
      wrappedListener.extension = extension;
      return this.a.event(wrappedListener, void 0, disposables);
    };
  }
  async $participateInSave(resource, reason, token) {
    const revivedUri = URI.revive(resource);
    const document2 = this.c.getNotebookDocument(revivedUri);
    if (!document2) {
      throw new Error("Unable to resolve notebook document");
    }
    const edits = [];
    await this.a.fireAsync({ notebook: document2.apiNotebook, reason: TextDocumentSaveReason2.to(reason) }, token, async (thenable, listener) => {
      const now = Date.now();
      const data = await await Promise.resolve(thenable);
      if (Date.now() - now > this.f.timeout) {
        this.b.warn("onWillSaveNotebookDocument-listener from extension", listener.extension.identifier);
      }
      if (token.isCancellationRequested) {
        return;
      }
      if (data) {
        if (data instanceof $LT) {
          edits.push(data);
        } else {
          this.b.warn("onWillSaveNotebookDocument-listener from extension", listener.extension.identifier, "ignored due to invalid data");
        }
      }
      return;
    });
    if (token.isCancellationRequested) {
      return false;
    }
    if (edits.length === 0) {
      return true;
    }
    const dto = { edits: [] };
    for (const edit2 of edits) {
      const { edits: edits2 } = WorkspaceEdit.from(edit2);
      dto.edits = dto.edits.concat(edits2);
    }
    return this.d.$tryApplyWorkspaceEdit(new $ES(dto));
  }
};

// out-build/vs/workbench/api/common/extHostNotebookDocuments.js
var $uyc = class {
  constructor(c) {
    this.c = c;
    this.a = new $ze();
    this.onDidSaveNotebookDocument = this.a.event;
    this.b = new $ze();
    this.onDidChangeNotebookDocument = this.b.event;
  }
  $acceptModelChanged(uri, event, isDirty, newMetadata) {
    const document2 = this.c.getNotebookDocument(URI.revive(uri));
    const e = document2.acceptModelChanged(event.value, isDirty, newMetadata);
    this.b.fire(e);
  }
  $acceptDirtyStateChanged(uri, isDirty) {
    const document2 = this.c.getNotebookDocument(URI.revive(uri));
    document2.acceptDirty(isDirty);
  }
  $acceptModelSaved(uri) {
    const document2 = this.c.getNotebookDocument(URI.revive(uri));
    this.a.fire(document2.apiNotebook);
  }
};

// out-build/vs/workbench/api/common/extHostNotebookEditors.js
var $vyc = class $vyc2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.a = new $ze();
    this.b = new $ze();
    this.onDidChangeNotebookEditorSelection = this.a.event;
    this.onDidChangeNotebookEditorVisibleRanges = this.b.event;
  }
  $acceptEditorPropertiesChanged(id2, data) {
    this.c.debug("ExtHostNotebook#$acceptEditorPropertiesChanged", id2, data);
    const editor = this.d.getEditorById(id2);
    if (data.visibleRanges) {
      editor._acceptVisibleRanges(data.visibleRanges.ranges.map(NotebookRange.to));
    }
    if (data.selections) {
      editor._acceptSelections(data.selections.selections.map(NotebookRange.to));
    }
    if (data.visibleRanges) {
      this.b.fire({
        notebookEditor: editor.apiEditor,
        visibleRanges: editor.apiEditor.visibleRanges
      });
    }
    if (data.selections) {
      this.a.fire(Object.freeze({
        notebookEditor: editor.apiEditor,
        selections: editor.apiEditor.selections
      }));
    }
  }
  $acceptEditorViewColumns(data) {
    for (const id2 in data) {
      const editor = this.d.getEditorById(id2);
      editor._acceptViewColumn(ViewColumn2.to(data[id2]));
    }
  }
};
$vyc = __decorate([
  __param(0, $wn)
], $vyc);

// out-build/vs/workbench/contrib/notebook/common/notebookExecutionService.js
var CellExecutionUpdateType;
(function(CellExecutionUpdateType2) {
  CellExecutionUpdateType2[CellExecutionUpdateType2["Output"] = 1] = "Output";
  CellExecutionUpdateType2[CellExecutionUpdateType2["OutputItems"] = 2] = "OutputItems";
  CellExecutionUpdateType2[CellExecutionUpdateType2["ExecutionState"] = 3] = "ExecutionState";
})(CellExecutionUpdateType || (CellExecutionUpdateType = {}));
var $vL = $Qk("INotebookExecutionService");

// out-build/vs/workbench/contrib/notebook/common/notebookKernelService.js
var $BL = 100;
var ProxyKernelState;
(function(ProxyKernelState2) {
  ProxyKernelState2[ProxyKernelState2["Disconnected"] = 1] = "Disconnected";
  ProxyKernelState2[ProxyKernelState2["Connected"] = 2] = "Connected";
  ProxyKernelState2[ProxyKernelState2["Initializing"] = 3] = "Initializing";
})(ProxyKernelState || (ProxyKernelState = {}));
var $CL = $Qk("INotebookKernelService");
var $DL = $Qk("INotebookKernelHistoryService");

// out-build/vs/workbench/api/common/extHostNotebookKernels.js
var $wyc = class $wyc2 {
  constructor(mainContext, m, n, o, q) {
    this.m = m;
    this.n = n;
    this.o = o;
    this.q = q;
    this.b = new $Ec();
    this.c = new $Ec();
    this.f = /* @__PURE__ */ new Map();
    this.g = 0;
    this.h = /* @__PURE__ */ new Map();
    this.i = 0;
    this.j = /* @__PURE__ */ new Map();
    this.k = 0;
    this.l = new $ze();
    this.onDidChangeNotebookCellExecutionState = this.l.event;
    this.r = 0;
    this.s = {};
    this.a = mainContext.getProxy($xT.MainThreadNotebookKernels);
    const selectKernelApiCommand = new $GW("notebook.selectKernel", "_notebook.selectKernel", "Trigger kernel picker for specified notebook editor widget", [
      new $EW("options", "Select kernel options", (v) => true, (v) => {
        if (v && "notebookEditor" in v && "id" in v) {
          const notebookEditorId = this.n.getIdByEditor(v.notebookEditor);
          return {
            id: v.id,
            extension: v.extension,
            notebookEditorId
          };
        } else if (v && "notebookEditor" in v) {
          const notebookEditorId = this.n.getIdByEditor(v.notebookEditor);
          if (notebookEditorId === void 0) {
            throw new Error(`Cannot invoke 'notebook.selectKernel' for unrecognized notebook editor ${v.notebookEditor.notebook.uri.toString()}`);
          }
          return { notebookEditorId };
        }
        return v;
      })
    ], $FW.Void);
    const requestKernelVariablesApiCommand = new $GW("vscode.executeNotebookVariableProvider", "_executeNotebookVariableProvider", "Execute notebook variable provider", [$EW.Uri], new $FW("A promise that resolves to an array of variables", (value, apiArgs) => {
      return value.map((variable) => {
        return {
          variable: {
            name: variable.name,
            value: variable.value,
            expression: variable.expression,
            type: variable.type,
            language: variable.language
          },
          hasNamedChildren: variable.hasNamedChildren,
          indexedChildrenCount: variable.indexedChildrenCount
        };
      });
    }));
    this.o.registerApiCommand(selectKernelApiCommand);
    this.o.registerApiCommand(requestKernelVariablesApiCommand);
  }
  createNotebookController(extension, id2, viewType, label, handler, preloads) {
    for (const data2 of this.j.values()) {
      if (data2.controller.id === id2 && $5z.equals(extension.identifier, data2.extensionId)) {
        throw new Error(`notebook controller with id '${id2}' ALREADY exist`);
      }
    }
    const handle = this.k++;
    const that = this;
    this.q.trace(`NotebookController[${handle}], CREATED by ${extension.identifier.value}, ${id2}`);
    const _defaultExecutHandler = () => console.warn(`NO execute handler from notebook controller '${data.id}' of extension: '${extension.identifier}'`);
    let isDisposed = false;
    const onDidChangeSelection = new $ze();
    const onDidReceiveMessage = new $ze();
    const data = {
      id: $xyc(extension.identifier, id2),
      notebookType: viewType,
      extensionId: extension.identifier,
      extensionLocation: extension.extensionLocation,
      label: label || extension.identifier.value,
      preloads: preloads ? preloads.map(NotebookRendererScript.from) : []
    };
    let _executeHandler = handler ?? _defaultExecutHandler;
    let _interruptHandler;
    let _variableProvider;
    this.a.$addKernel(handle, data).catch((err) => {
      console.log(err);
      isDisposed = true;
    });
    let tokenPool = 0;
    const _update = () => {
      if (isDisposed) {
        return;
      }
      const myToken = ++tokenPool;
      Promise.resolve().then(() => {
        if (myToken === tokenPool) {
          this.a.$updateKernel(handle, data);
        }
      });
    };
    const associatedNotebooks = new $Ec();
    const controller = {
      get id() {
        return id2;
      },
      get notebookType() {
        return data.notebookType;
      },
      onDidChangeSelectedNotebooks: onDidChangeSelection.event,
      get label() {
        return data.label;
      },
      set label(value) {
        data.label = value ?? extension.displayName ?? extension.name;
        _update();
      },
      get detail() {
        return data.detail ?? "";
      },
      set detail(value) {
        data.detail = value;
        _update();
      },
      get description() {
        return data.description ?? "";
      },
      set description(value) {
        data.description = value;
        _update();
      },
      get supportedLanguages() {
        return data.supportedLanguages;
      },
      set supportedLanguages(value) {
        data.supportedLanguages = value;
        _update();
      },
      get supportsExecutionOrder() {
        return data.supportsExecutionOrder ?? false;
      },
      set supportsExecutionOrder(value) {
        data.supportsExecutionOrder = value;
        _update();
      },
      get rendererScripts() {
        return data.preloads ? data.preloads.map(NotebookRendererScript.to) : [];
      },
      get executeHandler() {
        return _executeHandler;
      },
      set executeHandler(value) {
        _executeHandler = value ?? _defaultExecutHandler;
      },
      get interruptHandler() {
        return _interruptHandler;
      },
      set interruptHandler(value) {
        _interruptHandler = value;
        data.supportsInterrupt = Boolean(value);
        _update();
      },
      set variableProvider(value) {
        $AN(extension, "notebookVariableProvider");
        _variableProvider = value;
        data.hasVariableProvider = !!value;
        value?.onDidChangeVariables((e) => that.a.$variablesUpdated(e.uri));
        _update();
      },
      get variableProvider() {
        return _variableProvider;
      },
      createNotebookCellExecution(cell) {
        if (isDisposed) {
          throw new Error("notebook controller is DISPOSED");
        }
        if (!associatedNotebooks.has(cell.notebook.uri)) {
          that.q.trace(`NotebookController[${handle}] NOT associated to notebook, associated to THESE notebooks:`, Array.from(associatedNotebooks.keys()).map((u) => u.toString()));
          throw new Error(`notebook controller is NOT associated to notebook: ${cell.notebook.uri.toString()}`);
        }
        return that._createNotebookCellExecution(cell, $xyc(extension.identifier, this.id));
      },
      createNotebookExecution(notebook) {
        $AN(extension, "notebookExecution");
        if (isDisposed) {
          throw new Error("notebook controller is DISPOSED");
        }
        if (!associatedNotebooks.has(notebook.uri)) {
          that.q.trace(`NotebookController[${handle}] NOT associated to notebook, associated to THESE notebooks:`, Array.from(associatedNotebooks.keys()).map((u) => u.toString()));
          throw new Error(`notebook controller is NOT associated to notebook: ${notebook.uri.toString()}`);
        }
        return that._createNotebookExecution(notebook, $xyc(extension.identifier, this.id));
      },
      dispose: () => {
        if (!isDisposed) {
          this.q.trace(`NotebookController[${handle}], DISPOSED`);
          isDisposed = true;
          this.j.delete(handle);
          onDidChangeSelection.dispose();
          onDidReceiveMessage.dispose();
          this.a.$removeKernel(handle);
        }
      },
      // --- priority
      updateNotebookAffinity(notebook, priority) {
        if (priority === NotebookControllerAffinity2.Hidden) {
          $AN(extension, "notebookControllerAffinityHidden");
        }
        that.a.$updateNotebookPriority(handle, notebook.uri, priority);
      },
      // --- ipc
      onDidReceiveMessage: onDidReceiveMessage.event,
      postMessage(message, editor) {
        $AN(extension, "notebookMessaging");
        return that.a.$postMessage(handle, editor && that.n.getIdByEditor(editor), message);
      },
      asWebviewUri(uri) {
        $AN(extension, "notebookMessaging");
        return $HJb(uri, that.m.remote);
      }
    };
    this.j.set(handle, {
      extensionId: extension.identifier,
      controller,
      onDidReceiveMessage,
      onDidChangeSelection,
      associatedNotebooks
    });
    return controller;
  }
  getIdByController(controller) {
    for (const [_, candidate] of this.j) {
      if (candidate.controller === controller) {
        return $xyc(candidate.extensionId, controller.id);
      }
    }
    return null;
  }
  createNotebookControllerDetectionTask(extension, viewType) {
    const handle = this.g++;
    const that = this;
    this.q.trace(`NotebookControllerDetectionTask[${handle}], CREATED by ${extension.identifier.value}`);
    this.a.$addKernelDetectionTask(handle, viewType);
    const detectionTask = {
      dispose: () => {
        this.f.delete(handle);
        that.a.$removeKernelDetectionTask(handle);
      }
    };
    this.f.set(handle, detectionTask);
    return detectionTask;
  }
  registerKernelSourceActionProvider(extension, viewType, provider) {
    const handle = this.i++;
    const eventHandle = typeof provider.onDidChangeNotebookKernelSourceActions === "function" ? handle : void 0;
    const that = this;
    this.h.set(handle, provider);
    this.q.trace(`NotebookKernelSourceActionProvider[${handle}], CREATED by ${extension.identifier.value}`);
    this.a.$addKernelSourceActionProvider(handle, handle, viewType);
    let subscription;
    if (eventHandle !== void 0) {
      subscription = provider.onDidChangeNotebookKernelSourceActions((_) => this.a.$emitNotebookKernelSourceActionsChangeEvent(eventHandle));
    }
    return {
      dispose: () => {
        this.h.delete(handle);
        that.a.$removeKernelSourceActionProvider(handle, handle);
        subscription?.dispose();
      }
    };
  }
  async $provideKernelSourceActions(handle, token) {
    const provider = this.h.get(handle);
    if (provider) {
      const disposables = new $2c();
      const ret = await provider.provideNotebookKernelSourceActions(token);
      return (ret ?? []).map((item) => NotebookKernelSourceAction.from(item, this.o.converter, disposables));
    }
    return [];
  }
  $acceptNotebookAssociation(handle, uri, value) {
    const obj = this.j.get(handle);
    if (obj) {
      const notebook = this.n.getNotebookDocument(URI.revive(uri));
      if (value) {
        obj.associatedNotebooks.set(notebook.uri, true);
      } else {
        obj.associatedNotebooks.delete(notebook.uri);
      }
      this.q.trace(`NotebookController[${handle}] ASSOCIATE notebook`, notebook.uri.toString(), value);
      obj.onDidChangeSelection.fire({
        selected: value,
        notebook: notebook.apiNotebook
      });
    }
  }
  async $executeCells(handle, uri, handles) {
    const obj = this.j.get(handle);
    if (!obj) {
      return;
    }
    const document2 = this.n.getNotebookDocument(URI.revive(uri));
    const cells = [];
    for (const cellHandle of handles) {
      const cell = document2.getCell(cellHandle);
      if (cell) {
        cells.push(cell.apiCell);
      }
    }
    try {
      this.q.trace(`NotebookController[${handle}] EXECUTE cells`, document2.uri.toString(), cells.length);
      await obj.controller.executeHandler.call(obj.controller, cells, document2.apiNotebook, obj.controller);
    } catch (err) {
      this.q.error(`NotebookController[${handle}] execute cells FAILED`, err);
      console.error(err);
    }
  }
  async $cancelCells(handle, uri, handles) {
    const obj = this.j.get(handle);
    if (!obj) {
      return;
    }
    const document2 = this.n.getNotebookDocument(URI.revive(uri));
    if (obj.controller.interruptHandler) {
      await obj.controller.interruptHandler.call(obj.controller, document2.apiNotebook);
    } else {
      for (const cellHandle of handles) {
        const cell = document2.getCell(cellHandle);
        if (cell) {
          this.b.get(cell.uri)?.cancel();
        }
      }
    }
    if (obj.controller.interruptHandler) {
      const items = this.c.get(document2.uri);
      this.c.delete(document2.uri);
      if (handles.length && Array.isArray(items) && items.length) {
        items.forEach((d) => d.dispose());
      }
    }
  }
  async $provideVariables(handle, requestId, notebookUri, parentId, kind, start, token) {
    const obj = this.j.get(handle);
    if (!obj) {
      return;
    }
    const document2 = this.n.getNotebookDocument(URI.revive(notebookUri));
    const variableProvider = obj.controller.variableProvider;
    if (!variableProvider) {
      return;
    }
    let parent = void 0;
    if (parentId !== void 0) {
      parent = this.s[parentId];
      if (!parent) {
        return;
      }
    } else {
      this.s = {};
    }
    const requestKind = kind === "named" ? NotebookVariablesRequestKind.Named : NotebookVariablesRequestKind.Indexed;
    const variableResults = variableProvider.provideVariables(document2.apiNotebook, parent, requestKind, start, token);
    let resultCount = 0;
    for await (const result of variableResults) {
      if (token.isCancellationRequested) {
        return;
      }
      const variable = {
        id: this.r++,
        name: result.variable.name,
        value: result.variable.value,
        type: result.variable.type,
        interfaces: result.variable.interfaces,
        language: result.variable.language,
        expression: result.variable.expression,
        hasNamedChildren: result.hasNamedChildren,
        indexedChildrenCount: result.indexedChildrenCount,
        extensionId: obj.extensionId.value
      };
      this.s[variable.id] = result.variable;
      this.a.$receiveVariable(requestId, variable);
      if (resultCount++ >= $BL) {
        return;
      }
    }
  }
  $acceptKernelMessageFromRenderer(handle, editorId, message) {
    const obj = this.j.get(handle);
    if (!obj) {
      return;
    }
    const editor = this.n.getEditorById(editorId);
    obj.onDidReceiveMessage.fire(Object.freeze({ editor: editor.apiEditor, message }));
  }
  $cellExecutionChanged(uri, cellHandle, state) {
    const document2 = this.n.getNotebookDocument(URI.revive(uri));
    const cell = document2.getCell(cellHandle);
    if (cell) {
      const newState = state ? NotebookCellExecutionState3.to(state) : NotebookCellExecutionState2.Idle;
      if (newState !== void 0) {
        this.l.fire({
          cell: cell.apiCell,
          state: newState
        });
      }
    }
  }
  // ---
  _createNotebookCellExecution(cell, controllerId) {
    if (cell.index < 0) {
      throw new Error("CANNOT execute cell that has been REMOVED from notebook");
    }
    const notebook = this.n.getNotebookDocument(cell.notebook.uri);
    const cellObj = notebook.getCellFromApiCell(cell);
    if (!cellObj) {
      throw new Error("invalid cell");
    }
    if (this.b.has(cellObj.uri)) {
      throw new Error(`duplicate execution for ${cellObj.uri}`);
    }
    const execution = new NotebookCellExecutionTask(controllerId, cellObj, this.a);
    this.b.set(cellObj.uri, execution);
    const listener = execution.onDidChangeState(() => {
      if (execution.state === NotebookCellExecutionTaskState.Resolved) {
        execution.dispose();
        listener.dispose();
        this.b.delete(cellObj.uri);
      }
    });
    return execution.asApiObject();
  }
  // ---
  _createNotebookExecution(nb, controllerId) {
    const notebook = this.n.getNotebookDocument(nb.uri);
    const runningCell = nb.getCells().find((cell) => {
      const apiCell = notebook.getCellFromApiCell(cell);
      return apiCell && this.b.has(apiCell.uri);
    });
    if (runningCell) {
      throw new Error(`duplicate cell execution for ${runningCell.document.uri}`);
    }
    if (this.c.has(notebook.uri)) {
      throw new Error(`duplicate notebook execution for ${notebook.uri}`);
    }
    const execution = new NotebookExecutionTask(controllerId, notebook, this.a);
    const listener = execution.onDidChangeState(() => {
      if (execution.state === NotebookExecutionTaskState.Resolved) {
        execution.dispose();
        listener.dispose();
        this.c.delete(notebook.uri);
      }
    });
    this.c.set(notebook.uri, [execution, listener]);
    return execution.asApiObject();
  }
};
$wyc = __decorate([
  __param(4, $wn)
], $wyc);
var NotebookCellExecutionTaskState;
(function(NotebookCellExecutionTaskState2) {
  NotebookCellExecutionTaskState2[NotebookCellExecutionTaskState2["Init"] = 0] = "Init";
  NotebookCellExecutionTaskState2[NotebookCellExecutionTaskState2["Started"] = 1] = "Started";
  NotebookCellExecutionTaskState2[NotebookCellExecutionTaskState2["Resolved"] = 2] = "Resolved";
})(NotebookCellExecutionTaskState || (NotebookCellExecutionTaskState = {}));
var NotebookCellExecutionTask = class _NotebookCellExecutionTask extends $3c {
  static {
    this.a = 0;
  }
  get state() {
    return this.f;
  }
  constructor(controllerId, m, n) {
    super();
    this.m = m;
    this.n = n;
    this.b = _NotebookCellExecutionTask.a++;
    this.c = new $ze();
    this.onDidChangeState = this.c.event;
    this.f = NotebookCellExecutionTaskState.Init;
    this.g = this.B(new $ad());
    this.h = new TimeoutBasedCollector(10, (updates) => this.s(updates));
    this.j = m.internalMetadata.executionOrder;
    this.n.$createExecution(this.b, controllerId, this.m.notebook.uri, this.m.handle);
  }
  cancel() {
    this.g.cancel();
  }
  async r(update) {
    await this.h.addItem(update);
  }
  async s(update) {
    const updates = Array.isArray(update) ? update : [update];
    return this.n.$updateExecution(this.b, new $ES(updates));
  }
  t() {
    if (this.f === NotebookCellExecutionTaskState.Init) {
      throw new Error("Must call start before modifying cell output");
    }
    if (this.f === NotebookCellExecutionTaskState.Resolved) {
      throw new Error("Cannot modify cell output after calling resolve");
    }
  }
  w(cellOrCellIndex) {
    let cell = this.m;
    if (cellOrCellIndex) {
      cell = this.m.notebook.getCellFromApiCell(cellOrCellIndex);
    }
    if (!cell) {
      throw new Error("INVALID cell");
    }
    return cell.handle;
  }
  y(items) {
    return items.map((output) => {
      const newOutput = $0U.ensureUniqueMimeTypes(output.items, true);
      if (newOutput === output.items) {
        return NotebookCellOutput.from(output);
      }
      return NotebookCellOutput.from({
        items: newOutput,
        id: output.id,
        metadata: output.metadata
      });
    });
  }
  async z(outputs, cell, append) {
    const handle = this.w(cell);
    const outputDtos = this.y($5b(outputs));
    return this.r({
      editType: CellExecutionUpdateType.Output,
      cellHandle: handle,
      append,
      outputs: outputDtos
    });
  }
  async C(items, output, append) {
    items = $0U.ensureUniqueMimeTypes($5b(items), true);
    return this.r({
      editType: CellExecutionUpdateType.OutputItems,
      items: items.map(NotebookCellOutputItem.from),
      outputId: output.id,
      append
    });
  }
  asApiObject() {
    const that = this;
    const result = {
      get token() {
        return that.g.token;
      },
      get cell() {
        return that.m.apiCell;
      },
      get executionOrder() {
        return that.j;
      },
      set executionOrder(v) {
        that.j = v;
        that.s([{
          editType: CellExecutionUpdateType.ExecutionState,
          executionOrder: that.j
        }]);
      },
      start(startTime) {
        if (that.f === NotebookCellExecutionTaskState.Resolved || that.f === NotebookCellExecutionTaskState.Started) {
          throw new Error("Cannot call start again");
        }
        that.f = NotebookCellExecutionTaskState.Started;
        that.c.fire();
        that.s({
          editType: CellExecutionUpdateType.ExecutionState,
          runStartTime: startTime
        });
      },
      end(success, endTime, executionError) {
        if (that.f === NotebookCellExecutionTaskState.Resolved) {
          throw new Error("Cannot call resolve twice");
        }
        that.f = NotebookCellExecutionTaskState.Resolved;
        that.c.fire();
        that.h.flush();
        const error = createSerializeableError(executionError);
        that.n.$completeExecution(that.b, new $ES({
          runEndTime: endTime,
          lastRunSuccess: success,
          error
        }));
      },
      clearOutput(cell) {
        that.t();
        return that.z([], cell, false);
      },
      appendOutput(outputs, cell) {
        that.t();
        return that.z(outputs, cell, true);
      },
      replaceOutput(outputs, cell) {
        that.t();
        return that.z(outputs, cell, false);
      },
      appendOutputItems(items, output) {
        that.t();
        return that.C(items, output, true);
      },
      replaceOutputItems(items, output) {
        that.t();
        return that.C(items, output, false);
      }
    };
    return Object.freeze(result);
  }
};
function createSerializeableError(executionError) {
  const convertRange = (range) => range ? {
    startLineNumber: range.start.line,
    startColumn: range.start.character,
    endLineNumber: range.end.line,
    endColumn: range.end.character
  } : void 0;
  const convertStackFrame = (frame) => ({
    uri: frame.uri,
    position: frame.position,
    label: frame.label
  });
  const error = executionError ? {
    name: executionError.name,
    message: executionError.message,
    stack: executionError.stack instanceof Array ? executionError.stack.map((frame) => convertStackFrame(frame)) : executionError.stack,
    location: convertRange(executionError.location),
    uri: executionError.uri
  } : void 0;
  return error;
}
var NotebookExecutionTaskState;
(function(NotebookExecutionTaskState2) {
  NotebookExecutionTaskState2[NotebookExecutionTaskState2["Init"] = 0] = "Init";
  NotebookExecutionTaskState2[NotebookExecutionTaskState2["Started"] = 1] = "Started";
  NotebookExecutionTaskState2[NotebookExecutionTaskState2["Resolved"] = 2] = "Resolved";
})(NotebookExecutionTaskState || (NotebookExecutionTaskState = {}));
var NotebookExecutionTask = class _NotebookExecutionTask extends $3c {
  static {
    this.a = 0;
  }
  get state() {
    return this.f;
  }
  constructor(controllerId, h, j) {
    super();
    this.h = h;
    this.j = j;
    this.b = _NotebookExecutionTask.a++;
    this.c = new $ze();
    this.onDidChangeState = this.c.event;
    this.f = NotebookExecutionTaskState.Init;
    this.g = this.B(new $ad());
    this.j.$createNotebookExecution(this.b, controllerId, this.h.uri);
  }
  cancel() {
    this.g.cancel();
  }
  asApiObject() {
    const result = {
      start: () => {
        if (this.f === NotebookExecutionTaskState.Resolved || this.f === NotebookExecutionTaskState.Started) {
          throw new Error("Cannot call start again");
        }
        this.f = NotebookExecutionTaskState.Started;
        this.c.fire();
        this.j.$beginNotebookExecution(this.b);
      },
      end: () => {
        if (this.f === NotebookExecutionTaskState.Resolved) {
          throw new Error("Cannot call resolve twice");
        }
        this.f = NotebookExecutionTaskState.Resolved;
        this.c.fire();
        this.j.$completeNotebookExecution(this.b);
      }
    };
    return Object.freeze(result);
  }
};
var TimeoutBasedCollector = class {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.a = [];
    this.b = Date.now();
  }
  addItem(item) {
    this.a.push(item);
    if (!this.c) {
      this.c = new $gi();
      this.b = Date.now();
      $Wh(this.f).then(() => {
        return this.flush();
      });
    }
    if (Date.now() - this.b > this.f) {
      return this.flush();
    }
    return this.c.p;
  }
  flush() {
    if (this.a.length === 0 || !this.c) {
      return Promise.resolve();
    }
    const deferred = this.c;
    this.c = void 0;
    const batch = this.a;
    this.a = [];
    return this.g(batch).finally(() => deferred.complete());
  }
};
function $xyc(extensionIdentifier, id2) {
  return `${extensionIdentifier.value}/${id2}`;
}

// out-build/vs/workbench/api/common/extHostNotebookRenderers.js
var $yyc = class {
  constructor(mainContext, c) {
    this.c = c;
    this.a = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadNotebookRenderers);
  }
  $postRendererMessage(editorId, rendererId, message) {
    const editor = this.c.getEditorById(editorId);
    this.a.get(rendererId)?.fire({ editor: editor.apiEditor, message });
  }
  createRendererMessaging(manifest, rendererId) {
    if (!manifest.contributes?.notebookRenderer?.some((r) => r.id === rendererId)) {
      throw new Error(`Extensions may only call createRendererMessaging() for renderers they contribute (got ${rendererId})`);
    }
    const messaging = {
      onDidReceiveMessage: (listener, thisArg, disposables) => {
        return this.d(rendererId).event(listener, thisArg, disposables);
      },
      postMessage: (message, editorOrAlias) => {
        if ($_xc.apiEditorsToExtHost.has(message)) {
          [message, editorOrAlias] = [editorOrAlias, message];
        }
        const extHostEditor = editorOrAlias && $_xc.apiEditorsToExtHost.get(editorOrAlias);
        return this.b.$postMessage(extHostEditor?.id, rendererId, message);
      }
    };
    return messaging;
  }
  d(rendererId) {
    let emitter = this.a.get(rendererId);
    if (emitter) {
      return emitter;
    }
    emitter = new $ze({
      onDidRemoveLastListener: () => {
        emitter?.dispose();
        this.a.delete(rendererId);
      }
    });
    this.a.set(rendererId, emitter);
    return emitter;
  }
};

// out-build/vs/workbench/api/common/extHostProfileContentHandler.js
var $Byc = class {
  constructor(mainContext) {
    this.b = /* @__PURE__ */ new Map();
    this.a = mainContext.getProxy($xT.MainThreadProfileContentHandlers);
  }
  registerProfileContentHandler(extension, id2, handler) {
    $AN(extension, "profileContentHandlers");
    if (this.b.has(id2)) {
      throw new Error(`Handler with id '${id2}' already registered`);
    }
    this.b.set(id2, handler);
    this.a.$registerProfileContentHandler(id2, handler.name, handler.description, extension.identifier.value);
    return $1c(() => {
      this.b.delete(id2);
      this.a.$unregisterProfileContentHandler(id2);
    });
  }
  async $saveProfile(id2, name, content, token) {
    const handler = this.b.get(id2);
    if (!handler) {
      throw new Error(`Unknown handler with id: ${id2}`);
    }
    return handler.saveProfile(name, content, token);
  }
  async $readProfile(id2, idOrUri, token) {
    const handler = this.b.get(id2);
    if (!handler) {
      throw new Error(`Unknown handler with id: ${id2}`);
    }
    return handler.readProfile($zg(idOrUri) ? idOrUri : URI.revive(idOrUri), token);
  }
};

// out-build/vs/workbench/api/common/extHostProgress.js
var $Cyc = class {
  constructor(proxy) {
    this.b = 0;
    this.c = /* @__PURE__ */ new Map();
    this.a = proxy;
  }
  async withProgress(extension, options2, task) {
    const handle = this.b++;
    const { title, location: location2, cancellable } = options2;
    const source = { label: extension.displayName || extension.name, id: extension.identifier.value };
    this.a.$startProgress(handle, { location: ProgressLocation2.from(location2), title, source, cancellable }, !extension.isUnderDevelopment ? extension.identifier.value : void 0).catch($hb);
    return this.d(handle, task, !!cancellable);
  }
  d(handle, task, cancellable) {
    let source;
    if (cancellable) {
      source = new $ad();
      this.c.set(handle, source);
    }
    const progressEnd = (handle2) => {
      this.a.$progressEnd(handle2);
      this.c.delete(handle2);
      source?.dispose();
    };
    let p;
    try {
      p = task(new ProgressCallback(this.a, handle), cancellable && source ? source.token : CancellationToken.None);
    } catch (err) {
      progressEnd(handle);
      throw err;
    }
    p.then((result) => progressEnd(handle), (err) => progressEnd(handle));
    return p;
  }
  $acceptProgressCanceled(handle) {
    const source = this.c.get(handle);
    if (source) {
      source.cancel();
      this.c.delete(handle);
    }
  }
};
function mergeProgress(result, currentValue) {
  result.message = currentValue.message;
  if (typeof currentValue.increment === "number") {
    if (typeof result.increment === "number") {
      result.increment += currentValue.increment;
    } else {
      result.increment = currentValue.increment;
    }
  }
  return result;
}
var ProgressCallback = class extends $VJ {
  constructor(c, d) {
    super((p) => this.throttledReport(p));
    this.c = c;
    this.d = d;
  }
  throttledReport(p) {
    this.c.$progressReport(this.d, p);
  }
};
__decorate([
  $_t(100, (result, currentValue) => mergeProgress(result, currentValue), () => /* @__PURE__ */ Object.create(null))
], ProgressCallback.prototype, "throttledReport", null);

// out-build/vs/workbench/api/common/extHostQuickDiff.js
var $Dyc = class _$Dyc {
  static {
    this.a = 0;
  }
  constructor(mainContext, d) {
    this.d = d;
    this.c = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadQuickDiff);
  }
  $provideOriginalResource(handle, uriComponents, token) {
    const uri = URI.revive(uriComponents);
    const provider = this.c.get(handle);
    if (!provider) {
      return Promise.resolve(null);
    }
    return $Nh(() => provider.provideOriginalResource(uri, token)).then((r) => r || null);
  }
  registerQuickDiffProvider(selector, quickDiffProvider, label, rootUri) {
    const handle = _$Dyc.a++;
    this.c.set(handle, quickDiffProvider);
    this.b.$registerQuickDiffProvider(handle, DocumentSelector.from(selector, this.d), label, rootUri, quickDiffProvider.visible ?? true);
    return {
      dispose: () => {
        this.b.$unregisterQuickDiffProvider(handle);
        this.c.delete(handle);
      }
    };
  }
};

// out-build/vs/workbench/api/common/extHostQuickOpen.js
function $Eyc(mainContext, workspace, commands) {
  const proxy = mainContext.getProxy($xT.MainThreadQuickOpen);
  class ExtHostQuickOpenImpl {
    constructor(workspace2, commands2) {
      this.e = /* @__PURE__ */ new Map();
      this.f = 0;
      this.a = workspace2;
      this.b = commands2;
    }
    showQuickPick(extension, itemsOrItemsPromise, options2, token = CancellationToken.None) {
      this.c = void 0;
      const itemsPromise = Promise.resolve(itemsOrItemsPromise);
      const instance = ++this.f;
      const quickPickWidget = proxy.$show(instance, {
        title: options2?.title,
        placeHolder: options2?.placeHolder,
        matchOnDescription: options2?.matchOnDescription,
        matchOnDetail: options2?.matchOnDetail,
        ignoreFocusLost: options2?.ignoreFocusOut,
        canPickMany: options2?.canPickMany
      }, token);
      const widgetClosedMarker = {};
      const widgetClosedPromise = quickPickWidget.then(() => widgetClosedMarker);
      return Promise.race([widgetClosedPromise, itemsPromise]).then((result) => {
        if (result === widgetClosedMarker) {
          return void 0;
        }
        const allowedTooltips = $zN(extension, "quickPickItemTooltip");
        return itemsPromise.then((items) => {
          const pickItems = [];
          for (let handle = 0; handle < items.length; handle++) {
            const item = items[handle];
            if (typeof item === "string") {
              pickItems.push({ label: item, handle });
            } else if (item.kind === QuickPickItemKind.Separator) {
              pickItems.push({ type: "separator", label: item.label });
            } else {
              if (item.tooltip && !allowedTooltips) {
                console.warn(`Extension '${extension.identifier.value}' uses a tooltip which is proposed API that is only available when running out of dev or with the following command line switch: --enable-proposed-api ${extension.identifier.value}`);
              }
              const icon = item.iconPath ? getIconPathOrClass(item.iconPath) : void 0;
              pickItems.push({
                label: item.label,
                iconPath: icon?.iconPath,
                iconClass: icon?.iconClass,
                description: item.description,
                detail: item.detail,
                picked: item.picked,
                alwaysShow: item.alwaysShow,
                tooltip: allowedTooltips ? MarkdownString.fromStrict(item.tooltip) : void 0,
                handle
              });
            }
          }
          if (options2 && typeof options2.onDidSelectItem === "function") {
            this.c = (handle) => {
              options2.onDidSelectItem(items[handle]);
            };
          }
          proxy.$setItems(instance, pickItems);
          return quickPickWidget.then((handle) => {
            if (typeof handle === "number") {
              return items[handle];
            } else if (Array.isArray(handle)) {
              return handle.map((h) => items[h]);
            }
            return void 0;
          });
        });
      }).then(void 0, (err) => {
        if ($kb(err)) {
          return void 0;
        }
        proxy.$setError(instance, err);
        return Promise.reject(err);
      });
    }
    $onItemSelected(handle) {
      this.c?.(handle);
    }
    // ---- input
    showInput(options2, token = CancellationToken.None) {
      this.d = options2?.validateInput;
      return proxy.$input(options2, typeof this.d === "function", token).then(void 0, (err) => {
        if ($kb(err)) {
          return void 0;
        }
        return Promise.reject(err);
      });
    }
    async $validateInput(input) {
      if (!this.d) {
        return;
      }
      const result = await this.d(input);
      if (!result || typeof result === "string") {
        return result;
      }
      let severity;
      switch (result.severity) {
        case InputBoxValidationSeverity.Info:
          severity = severity_default.Info;
          break;
        case InputBoxValidationSeverity.Warning:
          severity = severity_default.Warning;
          break;
        case InputBoxValidationSeverity.Error:
          severity = severity_default.Error;
          break;
        default:
          severity = result.message ? severity_default.Error : severity_default.Ignore;
          break;
      }
      return {
        content: result.message,
        severity
      };
    }
    // ---- workspace folder picker
    async showWorkspaceFolderPick(options2, token = CancellationToken.None) {
      const selectedFolder = await this.b.executeCommand("_workbench.pickWorkspaceFolder", [options2]);
      if (!selectedFolder) {
        return void 0;
      }
      const workspaceFolders = await this.a.getWorkspaceFolders2();
      if (!workspaceFolders) {
        return void 0;
      }
      return workspaceFolders.find((folder) => folder.uri.toString() === selectedFolder.uri.toString());
    }
    // ---- QuickInput
    createQuickPick(extension) {
      const session = new ExtHostQuickPick(extension, () => this.e.delete(session._id));
      this.e.set(session._id, session);
      return session;
    }
    createInputBox(extension) {
      const session = new ExtHostInputBox(extension, () => this.e.delete(session._id));
      this.e.set(session._id, session);
      return session;
    }
    $onDidChangeValue(sessionId, value) {
      const session = this.e.get(sessionId);
      session?._fireDidChangeValue(value);
    }
    $onDidAccept(sessionId) {
      const session = this.e.get(sessionId);
      session?._fireDidAccept();
    }
    $onDidChangeActive(sessionId, handles) {
      const session = this.e.get(sessionId);
      if (session instanceof ExtHostQuickPick) {
        session._fireDidChangeActive(handles);
      }
    }
    $onDidChangeSelection(sessionId, handles) {
      const session = this.e.get(sessionId);
      if (session instanceof ExtHostQuickPick) {
        session._fireDidChangeSelection(handles);
      }
    }
    $onDidTriggerButton(sessionId, handle) {
      const session = this.e.get(sessionId);
      session?._fireDidTriggerButton(handle);
    }
    $onDidTriggerItemButton(sessionId, itemHandle, buttonHandle) {
      const session = this.e.get(sessionId);
      if (session instanceof ExtHostQuickPick) {
        session._fireDidTriggerItemButton(itemHandle, buttonHandle);
      }
    }
    $onDidHide(sessionId) {
      const session = this.e.get(sessionId);
      session?._fireDidHide();
    }
  }
  class ExtHostQuickInput {
    static {
      this.a = 1;
    }
    constructor(y, z) {
      this.y = y;
      this.z = z;
      this._id = ExtHostQuickPick.a++;
      this.e = false;
      this.f = false;
      this.g = true;
      this.j = false;
      this.k = true;
      this.l = "";
      this.m = void 0;
      this.o = [];
      this.p = /* @__PURE__ */ new Map();
      this.q = new $ze();
      this.r = new $ze();
      this.s = new $ze();
      this.t = new $ze();
      this.v = { id: this._id };
      this.w = false;
      this.x = [
        this.s,
        this.t,
        this.q,
        this.r
      ];
      this.onDidChangeValue = this.r.event;
      this.onDidAccept = this.q.event;
      this.onDidTriggerButton = this.s.event;
      this.onDidHide = this.t.event;
    }
    get title() {
      return this.b;
    }
    set title(title) {
      this.b = title;
      this.A({ title });
    }
    get step() {
      return this.c;
    }
    set step(step) {
      this.c = step;
      this.A({ step });
    }
    get totalSteps() {
      return this.d;
    }
    set totalSteps(totalSteps) {
      this.d = totalSteps;
      this.A({ totalSteps });
    }
    get enabled() {
      return this.g;
    }
    set enabled(enabled) {
      this.g = enabled;
      this.A({ enabled });
    }
    get busy() {
      return this.j;
    }
    set busy(busy) {
      this.j = busy;
      this.A({ busy });
    }
    get ignoreFocusOut() {
      return this.k;
    }
    set ignoreFocusOut(ignoreFocusOut) {
      this.k = ignoreFocusOut;
      this.A({ ignoreFocusOut });
    }
    get value() {
      return this.l;
    }
    set value(value) {
      this.l = value;
      this.A({ value });
    }
    get valueSelection() {
      return this.m;
    }
    set valueSelection(valueSelection) {
      this.m = valueSelection;
      this.A({ valueSelection });
    }
    get placeholder() {
      return this.n;
    }
    set placeholder(placeholder) {
      this.n = placeholder;
      this.A({ placeholder });
    }
    get buttons() {
      return this.o;
    }
    set buttons(buttons) {
      const allowedButtonLocation = $zN(this.y, "quickInputButtonLocation");
      if (!allowedButtonLocation && buttons.some((button) => button.location)) {
        console.warn(`Extension '${this.y.identifier.value}' uses a button location which is proposed API that is only available when running out of dev or with the following command line switch: --enable-proposed-api ${this.y.identifier.value}`);
      }
      this.o = buttons.slice();
      this.p.clear();
      buttons.forEach((button, i) => {
        const handle = button === $3U.Back ? -1 : i;
        this.p.set(handle, button);
      });
      this.A({
        buttons: buttons.map((button, i) => {
          return {
            ...getIconPathOrClass(button.iconPath),
            tooltip: button.tooltip,
            handle: button === $3U.Back ? -1 : i,
            location: allowedButtonLocation ? button.location : void 0
          };
        })
      });
    }
    show() {
      this.e = true;
      this.f = true;
      this.A({ visible: true });
    }
    hide() {
      this.e = false;
      this.A({ visible: false });
    }
    _fireDidAccept() {
      this.q.fire();
    }
    _fireDidChangeValue(value) {
      this.l = value;
      this.r.fire(value);
    }
    _fireDidTriggerButton(handle) {
      const button = this.p.get(handle);
      if (button) {
        this.s.fire(button);
      }
    }
    _fireDidHide() {
      if (this.f) {
        this.f = this.e;
        this.t.fire();
      }
    }
    dispose() {
      if (this.w) {
        return;
      }
      this.w = true;
      this._fireDidHide();
      this.x = $Xc(this.x);
      if (this.u) {
        clearTimeout(this.u);
        this.u = void 0;
      }
      this.z();
      proxy.$dispose(this._id);
    }
    A(properties) {
      if (this.w) {
        return;
      }
      for (const key of Object.keys(properties)) {
        const value = properties[key];
        this.v[key] = value === void 0 ? null : value;
      }
      if ("visible" in this.v) {
        if (this.u) {
          clearTimeout(this.u);
          this.u = void 0;
        }
        this.B();
      } else if (this.e && !this.u) {
        this.u = setTimeout(() => {
          this.u = void 0;
          this.B();
        }, 0);
      }
    }
    B() {
      proxy.$createOrUpdate(this.v);
      this.v = { id: this._id };
    }
  }
  function getIconUris(iconPath) {
    if (iconPath instanceof $AU) {
      return { id: iconPath.id };
    }
    const dark = getDarkIconUri(iconPath);
    const light = getLightIconUri(iconPath);
    return {
      dark: typeof dark === "string" ? URI.file(dark) : dark,
      light: typeof light === "string" ? URI.file(light) : light
    };
  }
  function getLightIconUri(iconPath) {
    return typeof iconPath === "object" && "light" in iconPath ? iconPath.light : iconPath;
  }
  function getDarkIconUri(iconPath) {
    return typeof iconPath === "object" && "dark" in iconPath ? iconPath.dark : iconPath;
  }
  function getIconPathOrClass(icon) {
    const iconPathOrIconClass = getIconUris(icon);
    let iconPath;
    let iconClass;
    if ("id" in iconPathOrIconClass) {
      iconClass = ThemeIcon.asClassName(iconPathOrIconClass);
    } else {
      iconPath = iconPathOrIconClass;
    }
    return {
      iconPath,
      iconClass
    };
  }
  class ExtHostQuickPick extends ExtHostQuickInput {
    constructor(extension, onDispose) {
      super(extension, onDispose);
      this.C = [];
      this.D = /* @__PURE__ */ new Map();
      this.E = /* @__PURE__ */ new Map();
      this.F = false;
      this.G = true;
      this.H = true;
      this.I = true;
      this.J = false;
      this.K = [];
      this.L = new $ze();
      this.M = [];
      this.N = new $ze();
      this.O = new $ze();
      this.onDidChangeActive = this.L.event;
      this.onDidChangeSelection = this.N.event;
      this.onDidTriggerItemButton = this.O.event;
      this.x.push(this.L, this.N, this.O);
      this.A({ type: "quickPick" });
    }
    get items() {
      return this.C;
    }
    set items(items) {
      this.C = items.slice();
      this.D.clear();
      this.E.clear();
      items.forEach((item, i) => {
        this.D.set(i, item);
        this.E.set(item, i);
      });
      const allowedTooltips = $zN(this.y, "quickPickItemTooltip");
      const pickItems = [];
      for (let handle = 0; handle < items.length; handle++) {
        const item = items[handle];
        if (item.kind === QuickPickItemKind.Separator) {
          pickItems.push({ type: "separator", label: item.label });
        } else {
          if (item.tooltip && !allowedTooltips) {
            console.warn(`Extension '${this.y.identifier.value}' uses a tooltip which is proposed API that is only available when running out of dev or with the following command line switch: --enable-proposed-api ${this.y.identifier.value}`);
          }
          const icon = item.iconPath ? getIconPathOrClass(item.iconPath) : void 0;
          pickItems.push({
            handle,
            label: item.label,
            iconPath: icon?.iconPath,
            iconClass: icon?.iconClass,
            description: item.description,
            detail: item.detail,
            picked: item.picked,
            alwaysShow: item.alwaysShow,
            tooltip: allowedTooltips ? MarkdownString.fromStrict(item.tooltip) : void 0,
            buttons: item.buttons?.map((button, i) => {
              return {
                ...getIconPathOrClass(button.iconPath),
                tooltip: button.tooltip,
                handle: i
              };
            })
          });
        }
      }
      this.A({
        items: pickItems
      });
    }
    get canSelectMany() {
      return this.F;
    }
    set canSelectMany(canSelectMany) {
      this.F = canSelectMany;
      this.A({ canSelectMany });
    }
    get matchOnDescription() {
      return this.G;
    }
    set matchOnDescription(matchOnDescription) {
      this.G = matchOnDescription;
      this.A({ matchOnDescription });
    }
    get matchOnDetail() {
      return this.H;
    }
    set matchOnDetail(matchOnDetail) {
      this.H = matchOnDetail;
      this.A({ matchOnDetail });
    }
    get sortByLabel() {
      return this.I;
    }
    set sortByLabel(sortByLabel) {
      this.I = sortByLabel;
      this.A({ sortByLabel });
    }
    get keepScrollPosition() {
      return this.J;
    }
    set keepScrollPosition(keepScrollPosition) {
      this.J = keepScrollPosition;
      this.A({ keepScrollPosition });
    }
    get activeItems() {
      return this.K;
    }
    set activeItems(activeItems) {
      this.K = activeItems.filter((item) => this.E.has(item));
      this.A({ activeItems: this.K.map((item) => this.E.get(item)) });
    }
    get selectedItems() {
      return this.M;
    }
    set selectedItems(selectedItems) {
      this.M = selectedItems.filter((item) => this.E.has(item));
      this.A({ selectedItems: this.M.map((item) => this.E.get(item)) });
    }
    _fireDidChangeActive(handles) {
      const items = $Mb(handles.map((handle) => this.D.get(handle)));
      this.K = items;
      this.L.fire(items);
    }
    _fireDidChangeSelection(handles) {
      const items = $Mb(handles.map((handle) => this.D.get(handle)));
      this.M = items;
      this.N.fire(items);
    }
    _fireDidTriggerItemButton(itemHandle, buttonHandle) {
      const item = this.D.get(itemHandle);
      if (!item || !item.buttons || !item.buttons.length) {
        return;
      }
      const button = item.buttons[buttonHandle];
      if (button) {
        this.O.fire({
          button,
          item
        });
      }
    }
  }
  class ExtHostInputBox extends ExtHostQuickInput {
    constructor(extension, onDispose) {
      super(extension, onDispose);
      this.C = false;
      this.A({ type: "inputBox" });
    }
    get password() {
      return this.C;
    }
    set password(password) {
      this.C = password;
      this.A({ password });
    }
    get prompt() {
      return this.D;
    }
    set prompt(prompt) {
      this.D = prompt;
      this.A({ prompt });
    }
    get validationMessage() {
      return this.E;
    }
    set validationMessage(validationMessage) {
      this.E = validationMessage;
      if (!validationMessage) {
        this.A({ validationMessage: void 0, severity: severity_default.Ignore });
      } else if (typeof validationMessage === "string") {
        this.A({ validationMessage, severity: severity_default.Error });
      } else {
        this.A({ validationMessage: validationMessage.message, severity: validationMessage.severity ?? severity_default.Error });
      }
    }
  }
  return new ExtHostQuickOpenImpl(workspace, commands);
}

// out-build/vs/workbench/api/common/extHostSCM.js
var $Gyc_1;
function isUri2(thing) {
  return thing instanceof URI;
}
function uriEquals(a, b) {
  if (a.scheme === Schemas.file && b.scheme === Schemas.file && $n) {
    return a.toString() === b.toString();
  }
  return a.toString().toLowerCase() === b.toString().toLowerCase();
}
function getIconResource(decorations) {
  if (!decorations) {
    return void 0;
  } else if (typeof decorations.iconPath === "string") {
    return URI.file(decorations.iconPath);
  } else if (URI.isUri(decorations.iconPath)) {
    return decorations.iconPath;
  } else if (ThemeIcon.isThemeIcon(decorations.iconPath)) {
    return decorations.iconPath;
  } else {
    return void 0;
  }
}
function getHistoryItemIconDto(icon) {
  if (!icon) {
    return void 0;
  } else if (URI.isUri(icon)) {
    return icon;
  } else if (ThemeIcon.isThemeIcon(icon)) {
    return icon;
  } else {
    const iconDto = icon;
    return { light: iconDto.light, dark: iconDto.dark };
  }
}
function toSCMHistoryItemDto(historyItem) {
  const references = historyItem.references?.map((r) => ({
    ...r,
    icon: getHistoryItemIconDto(r.icon)
  }));
  return { ...historyItem, references };
}
function toSCMHistoryItemRefDto(historyItemRef) {
  return historyItemRef ? { ...historyItemRef, icon: getHistoryItemIconDto(historyItemRef.icon) } : void 0;
}
function compareResourceThemableDecorations(a, b) {
  if (!a.iconPath && !b.iconPath) {
    return 0;
  } else if (!a.iconPath) {
    return -1;
  } else if (!b.iconPath) {
    return 1;
  }
  const aPath = typeof a.iconPath === "string" ? a.iconPath : URI.isUri(a.iconPath) ? a.iconPath.fsPath : a.iconPath.id;
  const bPath = typeof b.iconPath === "string" ? b.iconPath : URI.isUri(b.iconPath) ? b.iconPath.fsPath : b.iconPath.id;
  return $OM(aPath, bPath);
}
function compareResourceStatesDecorations(a, b) {
  let result = 0;
  if (a.strikeThrough !== b.strikeThrough) {
    return a.strikeThrough ? 1 : -1;
  }
  if (a.faded !== b.faded) {
    return a.faded ? 1 : -1;
  }
  if (a.tooltip !== b.tooltip) {
    return (a.tooltip || "").localeCompare(b.tooltip || "");
  }
  result = compareResourceThemableDecorations(a, b);
  if (result !== 0) {
    return result;
  }
  if (a.light && b.light) {
    result = compareResourceThemableDecorations(a.light, b.light);
  } else if (a.light) {
    return 1;
  } else if (b.light) {
    return -1;
  }
  if (result !== 0) {
    return result;
  }
  if (a.dark && b.dark) {
    result = compareResourceThemableDecorations(a.dark, b.dark);
  } else if (a.dark) {
    return 1;
  } else if (b.dark) {
    return -1;
  }
  return result;
}
function compareCommands(a, b) {
  if (a.command !== b.command) {
    return a.command < b.command ? -1 : 1;
  }
  if (a.title !== b.title) {
    return a.title < b.title ? -1 : 1;
  }
  if (a.tooltip !== b.tooltip) {
    if (a.tooltip !== void 0 && b.tooltip !== void 0) {
      return a.tooltip < b.tooltip ? -1 : 1;
    } else if (a.tooltip !== void 0) {
      return 1;
    } else if (b.tooltip !== void 0) {
      return -1;
    }
  }
  if (a.arguments === b.arguments) {
    return 0;
  } else if (!a.arguments) {
    return -1;
  } else if (!b.arguments) {
    return 1;
  } else if (a.arguments.length !== b.arguments.length) {
    return a.arguments.length - b.arguments.length;
  }
  for (let i = 0; i < a.arguments.length; i++) {
    const aArg = a.arguments[i];
    const bArg = b.arguments[i];
    if (aArg === bArg) {
      continue;
    }
    if (isUri2(aArg) && isUri2(bArg) && uriEquals(aArg, bArg)) {
      continue;
    }
    return aArg < bArg ? -1 : 1;
  }
  return 0;
}
function compareResourceStates(a, b) {
  let result = $OM(a.resourceUri.fsPath, b.resourceUri.fsPath, true);
  if (result !== 0) {
    return result;
  }
  if (a.command && b.command) {
    result = compareCommands(a.command, b.command);
  } else if (a.command) {
    return 1;
  } else if (b.command) {
    return -1;
  }
  if (result !== 0) {
    return result;
  }
  if (a.decorations && b.decorations) {
    result = compareResourceStatesDecorations(a.decorations, b.decorations);
  } else if (a.decorations) {
    return 1;
  } else if (b.decorations) {
    return -1;
  }
  if (result !== 0) {
    return result;
  }
  if (a.multiFileDiffEditorModifiedUri && b.multiFileDiffEditorModifiedUri) {
    result = $OM(a.multiFileDiffEditorModifiedUri.fsPath, b.multiFileDiffEditorModifiedUri.fsPath, true);
  } else if (a.multiFileDiffEditorModifiedUri) {
    return 1;
  } else if (b.multiFileDiffEditorModifiedUri) {
    return -1;
  }
  if (result !== 0) {
    return result;
  }
  if (a.multiDiffEditorOriginalUri && b.multiDiffEditorOriginalUri) {
    result = $OM(a.multiDiffEditorOriginalUri.fsPath, b.multiDiffEditorOriginalUri.fsPath, true);
  } else if (a.multiDiffEditorOriginalUri) {
    return 1;
  } else if (b.multiDiffEditorOriginalUri) {
    return -1;
  }
  return result;
}
function compareArgs(a, b) {
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}
function commandEquals(a, b) {
  return a.command === b.command && a.title === b.title && a.tooltip === b.tooltip && (a.arguments && b.arguments ? compareArgs(a.arguments, b.arguments) : a.arguments === b.arguments);
}
function commandListEquals(a, b) {
  return $zb(a, b, commandEquals);
}
var $Fyc = class {
  #proxy;
  #extHostDocuments;
  get value() {
    return this.d;
  }
  set value(value) {
    value = value ?? "";
    this.#proxy.$setInputBoxValue(this.m, value);
    this.o(value);
  }
  get onDidChange() {
    return this.f.event;
  }
  get placeholder() {
    return this.g;
  }
  set placeholder(placeholder) {
    this.#proxy.$setInputBoxPlaceholder(this.m, placeholder);
    this.g = placeholder;
  }
  get validateInput() {
    $AN(this.l, "scmValidation");
    return this.h;
  }
  set validateInput(fn) {
    $AN(this.l, "scmValidation");
    if (fn && typeof fn !== "function") {
      throw new Error(`[${this.l.identifier.value}]: Invalid SCM input box validation function`);
    }
    this.h = fn;
    this.#proxy.$setValidationProviderIsEnabled(this.m, !!fn);
  }
  get enabled() {
    return this.j;
  }
  set enabled(enabled) {
    enabled = !!enabled;
    if (this.j === enabled) {
      return;
    }
    this.j = enabled;
    this.#proxy.$setInputBoxEnablement(this.m, enabled);
  }
  get visible() {
    return this.k;
  }
  set visible(visible) {
    visible = !!visible;
    if (this.k === visible) {
      return;
    }
    this.k = visible;
    this.#proxy.$setInputBoxVisibility(this.m, visible);
  }
  get document() {
    $AN(this.l, "scmTextDocument");
    return this.#extHostDocuments.getDocument(this.n);
  }
  constructor(l, _extHostDocuments, proxy, m, n) {
    this.l = l;
    this.m = m;
    this.n = n;
    this.d = "";
    this.f = new $ze();
    this.g = "";
    this.j = true;
    this.k = true;
    this.#extHostDocuments = _extHostDocuments;
    this.#proxy = proxy;
  }
  showValidationMessage(message, type) {
    $AN(this.l, "scmValidation");
    this.#proxy.$showValidationMessage(this.m, message, type);
  }
  $onInputBoxValueChange(value) {
    this.o(value);
  }
  o(value) {
    this.d = value;
    this.f.fire(value);
  }
};
var ExtHostSourceControlResourceGroup = class _ExtHostSourceControlResourceGroup {
  static {
    this.d = 0;
  }
  get disposed() {
    return this.m;
  }
  get id() {
    return this.v;
  }
  get label() {
    return this.w;
  }
  set label(label) {
    this.w = label;
    this.s.$updateGroupLabel(this.u, this.handle, label);
  }
  get hideWhenEmpty() {
    return this.q;
  }
  set hideWhenEmpty(hideWhenEmpty) {
    this.q = hideWhenEmpty;
    this.s.$updateGroup(this.u, this.handle, this.features);
  }
  get features() {
    return {
      hideWhenEmpty: this.hideWhenEmpty
    };
  }
  get resourceStates() {
    return [...this.g];
  }
  set resourceStates(resources) {
    this.g = [...resources];
    this.l.fire();
  }
  constructor(s, t, u, v, w, multiDiffEditorEnableViewChanges, x) {
    this.s = s;
    this.t = t;
    this.u = u;
    this.v = v;
    this.w = w;
    this.multiDiffEditorEnableViewChanges = multiDiffEditorEnableViewChanges;
    this.x = x;
    this.f = 0;
    this.g = [];
    this.h = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.k = /* @__PURE__ */ new Map();
    this.l = new $ze();
    this.onDidUpdateResourceStates = this.l.event;
    this.m = false;
    this.n = new $ze();
    this.onDidDispose = this.n.event;
    this.o = [];
    this.p = [];
    this.q = void 0;
    this.handle = _ExtHostSourceControlResourceGroup.d++;
  }
  getResourceState(handle) {
    return this.h.get(handle);
  }
  $executeResourceCommand(handle, preserveFocus) {
    const command = this.j.get(handle);
    if (!command) {
      return Promise.resolve(void 0);
    }
    return $Nh(() => this.t.executeCommand(command.command, ...command.arguments || [], preserveFocus));
  }
  _takeResourceStateSnapshot() {
    const snapshot = [...this.g].sort(compareResourceStates);
    const diffs = $Ib(this.p, snapshot, compareResourceStates);
    const splices = diffs.map((diff2) => {
      const toInsert = diff2.toInsert.map((r) => {
        const handle = this.f++;
        this.h.set(handle, r);
        const sourceUri = r.resourceUri;
        let command;
        if (r.command) {
          if (r.command.command === "vscode.open" || r.command.command === "vscode.diff" || r.command.command === "vscode.changes") {
            const disposables = new $2c();
            command = this.t.converter.toInternal(r.command, disposables);
            this.k.set(handle, disposables);
          } else {
            this.j.set(handle, r.command);
          }
        }
        const hasScmMultiDiffEditorProposalEnabled = $zN(this.x, "scmMultiDiffEditor");
        const multiFileDiffEditorOriginalUri = hasScmMultiDiffEditorProposalEnabled ? r.multiDiffEditorOriginalUri : void 0;
        const multiFileDiffEditorModifiedUri = hasScmMultiDiffEditorProposalEnabled ? r.multiFileDiffEditorModifiedUri : void 0;
        const icon = getIconResource(r.decorations);
        const lightIcon = r.decorations && getIconResource(r.decorations.light) || icon;
        const darkIcon = r.decorations && getIconResource(r.decorations.dark) || icon;
        const icons = [lightIcon, darkIcon];
        const tooltip = r.decorations && r.decorations.tooltip || "";
        const strikeThrough = r.decorations && !!r.decorations.strikeThrough;
        const faded = r.decorations && !!r.decorations.faded;
        const contextValue = r.contextValue || "";
        const rawResource = [handle, sourceUri, icons, tooltip, strikeThrough, faded, contextValue, command, multiFileDiffEditorOriginalUri, multiFileDiffEditorModifiedUri];
        return { rawResource, handle };
      });
      return { start: diff2.start, deleteCount: diff2.deleteCount, toInsert };
    });
    const rawResourceSplices = splices.map(({ start, deleteCount, toInsert }) => [start, deleteCount, toInsert.map((i) => i.rawResource)]);
    const reverseSplices = splices.reverse();
    for (const { start, deleteCount, toInsert } of reverseSplices) {
      const handles = toInsert.map((i) => i.handle);
      const handlesToDelete = this.o.splice(start, deleteCount, ...handles);
      for (const handle of handlesToDelete) {
        this.h.delete(handle);
        this.j.delete(handle);
        this.k.get(handle)?.dispose();
        this.k.delete(handle);
      }
    }
    this.p = snapshot;
    return rawResourceSplices;
  }
  dispose() {
    this.m = true;
    this.n.fire();
  }
};
var ExtHostSourceControl = class _ExtHostSourceControl {
  static {
    this.d = 0;
  }
  #proxy;
  get id() {
    return this.z;
  }
  get label() {
    return this.A;
  }
  get rootUri() {
    return this.B;
  }
  get inputBox() {
    return this.g;
  }
  get count() {
    return this.h;
  }
  set count(count) {
    if (this.h === count) {
      return;
    }
    this.h = count;
    this.#proxy.$updateSourceControl(this.w, { count });
  }
  get quickDiffProvider() {
    return this.j;
  }
  set quickDiffProvider(quickDiffProvider) {
    this.j = quickDiffProvider;
    let quickDiffLabel = void 0;
    if ($zN(this.x, "quickDiffProvider")) {
      quickDiffLabel = quickDiffProvider?.label;
    }
    this.#proxy.$updateSourceControl(this.w, { hasQuickDiffProvider: !!quickDiffProvider, quickDiffLabel });
  }
  get historyProvider() {
    $AN(this.x, "scmHistoryProvider");
    return this.k;
  }
  set historyProvider(historyProvider) {
    $AN(this.x, "scmHistoryProvider");
    this.k = historyProvider;
    this.l.value = new $2c();
    this.#proxy.$updateSourceControl(this.w, { hasHistoryProvider: !!historyProvider });
    if (historyProvider) {
      this.l.value.add(historyProvider.onDidChangeCurrentHistoryItemRefs(() => {
        const historyItemRef = toSCMHistoryItemRefDto(historyProvider?.currentHistoryItemRef);
        const historyItemRemoteRef = toSCMHistoryItemRefDto(historyProvider?.currentHistoryItemRemoteRef);
        const historyItemBaseRef = toSCMHistoryItemRefDto(historyProvider?.currentHistoryItemBaseRef);
        this.#proxy.$onDidChangeHistoryProviderCurrentHistoryItemRefs(this.w, historyItemRef, historyItemRemoteRef, historyItemBaseRef);
      }));
      this.l.value.add(historyProvider.onDidChangeHistoryItemRefs((e) => {
        if (e.added.length === 0 && e.modified.length === 0 && e.removed.length === 0) {
          return;
        }
        const added = e.added.map((ref) => ({ ...ref, icon: getHistoryItemIconDto(ref.icon) }));
        const modified = e.modified.map((ref) => ({ ...ref, icon: getHistoryItemIconDto(ref.icon) }));
        const removed = e.removed.map((ref) => ({ ...ref, icon: getHistoryItemIconDto(ref.icon) }));
        this.#proxy.$onDidChangeHistoryProviderHistoryItemRefs(this.w, { added, modified, removed, silent: e.silent });
      }));
    }
  }
  get commitTemplate() {
    return this.m;
  }
  set commitTemplate(commitTemplate) {
    if (commitTemplate === this.m) {
      return;
    }
    this.m = commitTemplate;
    this.#proxy.$updateSourceControl(this.w, { commitTemplate });
  }
  get acceptInputCommand() {
    return this.o;
  }
  set acceptInputCommand(acceptInputCommand) {
    this.n.value = new $2c();
    this.o = acceptInputCommand;
    const internal = this.y.converter.toInternal(acceptInputCommand, this.n.value);
    this.#proxy.$updateSourceControl(this.w, { acceptInputCommand: internal });
  }
  get actionButton() {
    $AN(this.x, "scmActionButton");
    return this.q;
  }
  set actionButton(actionButton) {
    $AN(this.x, "scmActionButton");
    if ($rd(this.q, actionButton)) {
      return;
    }
    this.q = actionButton;
    this.p.value = new $2c();
    const actionButtonDto = actionButton !== void 0 ? {
      command: {
        ...this.y.converter.toInternal(actionButton.command, this.p.value),
        shortTitle: actionButton.command.shortTitle
      },
      secondaryCommands: actionButton.secondaryCommands?.map((commandGroup) => {
        return commandGroup.map((command) => this.y.converter.toInternal(command, this.p.value));
      }),
      enabled: actionButton.enabled
    } : void 0;
    this.#proxy.$updateSourceControl(this.w, { actionButton: actionButtonDto ?? null });
  }
  get statusBarCommands() {
    return this.t;
  }
  set statusBarCommands(statusBarCommands) {
    if (this.t && statusBarCommands && commandListEquals(this.t, statusBarCommands)) {
      return;
    }
    this.s.value = new $2c();
    this.t = statusBarCommands;
    const internal = (statusBarCommands || []).map((c) => this.y.converter.toInternal(c, this.s.value));
    this.#proxy.$updateSourceControl(this.w, { statusBarCommands: internal });
  }
  get selected() {
    return this.u;
  }
  constructor(x, _extHostDocuments, proxy, y, z, A, B) {
    this.x = x;
    this.y = y;
    this.z = z;
    this.A = A;
    this.B = B;
    this.f = /* @__PURE__ */ new Map();
    this.h = void 0;
    this.j = void 0;
    this.l = new $4c();
    this.m = void 0;
    this.n = new $4c();
    this.o = void 0;
    this.p = new $4c();
    this.s = new $4c();
    this.t = void 0;
    this.u = false;
    this.v = new $ze();
    this.onDidChangeSelection = this.v.event;
    this.w = _ExtHostSourceControl.d++;
    this.C = /* @__PURE__ */ new Map();
    this.D = /* @__PURE__ */ new Set();
    this.#proxy = proxy;
    const inputBoxDocumentUri = URI.from({
      scheme: Schemas.vscodeSourceControl,
      path: `${z}/scm${this.w}/input`,
      query: B ? `rootUri=${encodeURIComponent(B.toString())}` : void 0
    });
    this.g = new $Fyc(x, _extHostDocuments, this.#proxy, this.w, inputBoxDocumentUri);
    this.#proxy.$registerSourceControl(this.w, z, A, B, inputBoxDocumentUri);
  }
  createResourceGroup(id2, label, options2) {
    const multiDiffEditorEnableViewChanges = $zN(this.x, "scmMultiDiffEditor") && options2?.multiDiffEditorEnableViewChanges === true;
    const group = new ExtHostSourceControlResourceGroup(this.#proxy, this.y, this.w, id2, label, multiDiffEditorEnableViewChanges, this.x);
    const disposable = Event.once(group.onDidDispose)(() => this.C.delete(group));
    this.C.set(group, disposable);
    this.eventuallyAddResourceGroups();
    return group;
  }
  eventuallyAddResourceGroups() {
    const groups = [];
    const splices = [];
    for (const [group, disposable] of this.C) {
      disposable.dispose();
      const updateListener = group.onDidUpdateResourceStates(() => {
        this.D.add(group);
        this.eventuallyUpdateResourceStates();
      });
      Event.once(group.onDidDispose)(() => {
        this.D.delete(group);
        updateListener.dispose();
        this.f.delete(group.handle);
        this.#proxy.$unregisterGroup(this.w, group.handle);
      });
      groups.push([group.handle, group.id, group.label, group.features, group.multiDiffEditorEnableViewChanges]);
      const snapshot = group._takeResourceStateSnapshot();
      if (snapshot.length > 0) {
        splices.push([group.handle, snapshot]);
      }
      this.f.set(group.handle, group);
    }
    this.#proxy.$registerGroups(this.w, groups, splices);
    this.C.clear();
  }
  eventuallyUpdateResourceStates() {
    const splices = [];
    this.D.forEach((group) => {
      const snapshot = group._takeResourceStateSnapshot();
      if (snapshot.length === 0) {
        return;
      }
      splices.push([group.handle, snapshot]);
    });
    if (splices.length > 0) {
      this.#proxy.$spliceResourceStates(this.w, splices);
    }
    this.D.clear();
  }
  getResourceGroup(handle) {
    return this.f.get(handle);
  }
  setSelectionState(selected) {
    this.u = selected;
    this.v.fire(selected);
  }
  dispose() {
    this.n.dispose();
    this.p.dispose();
    this.s.dispose();
    this.f.forEach((group) => group.dispose());
    this.#proxy.$unregisterSourceControl(this.w);
  }
};
__decorate([
  $$t(100)
], ExtHostSourceControl.prototype, "eventuallyAddResourceGroups", null);
__decorate([
  $$t(100)
], ExtHostSourceControl.prototype, "eventuallyUpdateResourceStates", null);
var $Gyc = class $Gyc2 {
  static {
    $Gyc_1 = this;
  }
  static {
    this.d = 0;
  }
  get onDidChangeActiveProvider() {
    return this.k.event;
  }
  constructor(mainContext, m, n, o) {
    this.m = m;
    this.n = n;
    this.o = o;
    this.h = /* @__PURE__ */ new Map();
    this.j = new $7z();
    this.k = new $ze();
    this.f = mainContext.getProxy($xT.MainThreadSCM);
    this.g = mainContext.getProxy($xT.MainThreadTelemetry);
    m.registerArgumentProcessor({
      processArgument: (arg) => {
        if (arg && arg.$mid === 3) {
          const sourceControl = this.h.get(arg.sourceControlHandle);
          if (!sourceControl) {
            return arg;
          }
          const group = sourceControl.getResourceGroup(arg.groupHandle);
          if (!group) {
            return arg;
          }
          return group.getResourceState(arg.handle);
        } else if (arg && arg.$mid === 4) {
          const sourceControl = this.h.get(arg.sourceControlHandle);
          if (!sourceControl) {
            return arg;
          }
          return sourceControl.getResourceGroup(arg.groupHandle);
        } else if (arg && arg.$mid === 5) {
          const sourceControl = this.h.get(arg.handle);
          if (!sourceControl) {
            return arg;
          }
          return sourceControl;
        }
        return arg;
      }
    });
  }
  createSourceControl(extension, id2, label, rootUri) {
    this.o.trace("ExtHostSCM#createSourceControl", extension.identifier.value, id2, label, rootUri);
    this.g.$publicLog2("api/scm/createSourceControl", {
      extensionId: extension.identifier.value
    });
    const handle = $Gyc_1.d++;
    const sourceControl = new ExtHostSourceControl(extension, this.n, this.f, this.m, id2, label, rootUri);
    this.h.set(handle, sourceControl);
    const sourceControls = this.j.get(extension.identifier) || [];
    sourceControls.push(sourceControl);
    this.j.set(extension.identifier, sourceControls);
    return sourceControl;
  }
  // Deprecated
  getLastInputBox(extension) {
    this.o.trace("ExtHostSCM#getLastInputBox", extension.identifier.value);
    const sourceControls = this.j.get(extension.identifier);
    const sourceControl = sourceControls && sourceControls[sourceControls.length - 1];
    return sourceControl && sourceControl.inputBox;
  }
  $provideOriginalResource(sourceControlHandle, uriComponents, token) {
    const uri = URI.revive(uriComponents);
    this.o.trace("ExtHostSCM#$provideOriginalResource", sourceControlHandle, uri.toString());
    const sourceControl = this.h.get(sourceControlHandle);
    if (!sourceControl || !sourceControl.quickDiffProvider || !sourceControl.quickDiffProvider.provideOriginalResource) {
      return Promise.resolve(null);
    }
    return $Nh(() => sourceControl.quickDiffProvider.provideOriginalResource(uri, token)).then((r) => r || null);
  }
  $onInputBoxValueChange(sourceControlHandle, value) {
    this.o.trace("ExtHostSCM#$onInputBoxValueChange", sourceControlHandle);
    const sourceControl = this.h.get(sourceControlHandle);
    if (!sourceControl) {
      return Promise.resolve(void 0);
    }
    sourceControl.inputBox.$onInputBoxValueChange(value);
    return Promise.resolve(void 0);
  }
  $executeResourceCommand(sourceControlHandle, groupHandle, handle, preserveFocus) {
    this.o.trace("ExtHostSCM#$executeResourceCommand", sourceControlHandle, groupHandle, handle);
    const sourceControl = this.h.get(sourceControlHandle);
    if (!sourceControl) {
      return Promise.resolve(void 0);
    }
    const group = sourceControl.getResourceGroup(groupHandle);
    if (!group) {
      return Promise.resolve(void 0);
    }
    return group.$executeResourceCommand(handle, preserveFocus);
  }
  $validateInput(sourceControlHandle, value, cursorPosition) {
    this.o.trace("ExtHostSCM#$validateInput", sourceControlHandle);
    const sourceControl = this.h.get(sourceControlHandle);
    if (!sourceControl) {
      return Promise.resolve(void 0);
    }
    if (!sourceControl.inputBox.validateInput) {
      return Promise.resolve(void 0);
    }
    return $Nh(() => sourceControl.inputBox.validateInput(value, cursorPosition)).then((result) => {
      if (!result) {
        return Promise.resolve(void 0);
      }
      const message = MarkdownString.fromStrict(result.message);
      if (!message) {
        return Promise.resolve(void 0);
      }
      return Promise.resolve([message, result.type]);
    });
  }
  $setSelectedSourceControl(selectedSourceControlHandle) {
    this.o.trace("ExtHostSCM#$setSelectedSourceControl", selectedSourceControlHandle);
    if (selectedSourceControlHandle !== void 0) {
      this.h.get(selectedSourceControlHandle)?.setSelectionState(true);
    }
    if (this.l !== void 0) {
      this.h.get(this.l)?.setSelectionState(false);
    }
    this.l = selectedSourceControlHandle;
    return Promise.resolve(void 0);
  }
  async $resolveHistoryItemRefsCommonAncestor(sourceControlHandle, historyItemRefs, token) {
    try {
      const historyProvider = this.h.get(sourceControlHandle)?.historyProvider;
      const ancestor = await historyProvider?.resolveHistoryItemRefsCommonAncestor(historyItemRefs, token);
      return ancestor ?? void 0;
    } catch (err) {
      this.o.error("ExtHostSCM#$resolveHistoryItemRefsCommonAncestor", err);
      return void 0;
    }
  }
  async $provideHistoryItemRefs(sourceControlHandle, historyItemRefs, token) {
    try {
      const historyProvider = this.h.get(sourceControlHandle)?.historyProvider;
      const refs = await historyProvider?.provideHistoryItemRefs(historyItemRefs, token);
      return refs?.map((ref) => ({ ...ref, icon: getHistoryItemIconDto(ref.icon) })) ?? void 0;
    } catch (err) {
      this.o.error("ExtHostSCM#$provideHistoryItemRefs", err);
      return void 0;
    }
  }
  async $provideHistoryItems(sourceControlHandle, options2, token) {
    try {
      const historyProvider = this.h.get(sourceControlHandle)?.historyProvider;
      const historyItems = await historyProvider?.provideHistoryItems(options2, token);
      return historyItems?.map((item) => toSCMHistoryItemDto(item)) ?? void 0;
    } catch (err) {
      this.o.error("ExtHostSCM#$provideHistoryItems", err);
      return void 0;
    }
  }
  async $provideHistoryItemChanges(sourceControlHandle, historyItemId, historyItemParentId, token) {
    try {
      const historyProvider = this.h.get(sourceControlHandle)?.historyProvider;
      const changes = await historyProvider?.provideHistoryItemChanges(historyItemId, historyItemParentId, token);
      return changes ?? void 0;
    } catch (err) {
      this.o.error("ExtHostSCM#$provideHistoryItemChanges", err);
      return void 0;
    }
  }
};
$Gyc = $Gyc_1 = __decorate([
  __param(3, $wn)
], $Gyc);

// out-build/vs/workbench/api/common/extHostShare.js
var $Hyc = class _$Hyc {
  static {
    this.a = 0;
  }
  constructor(mainContext, d) {
    this.d = d;
    this.c = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadShare);
  }
  async $provideShare(handle, shareableItem, token) {
    const provider = this.c.get(handle);
    const result = await provider?.provideShare({ selection: Range.to(shareableItem.selection), resourceUri: URI.revive(shareableItem.resourceUri) }, token);
    return result ?? void 0;
  }
  registerShareProvider(selector, provider) {
    const handle = _$Hyc.a++;
    this.c.set(handle, provider);
    this.b.$registerShareProvider(handle, DocumentSelector.from(selector, this.d), provider.id, provider.label, provider.priority);
    return {
      dispose: () => {
        this.b.$unregisterShareProvider(handle);
        this.c.delete(handle);
      }
    };
  }
};

// out-build/vs/workbench/api/common/extHostSpeech.js
var $Iyc = class _$Iyc {
  static {
    this.a = 1;
  }
  constructor(mainContext) {
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadSpeech);
  }
  async $createSpeechToTextSession(handle, session, language) {
    const provider = this.c.get(handle);
    if (!provider) {
      return;
    }
    const disposables = new $2c();
    const cts = new $ad();
    this.d.set(session, cts);
    const speechToTextSession = await provider.provideSpeechToTextSession(cts.token, language ? { language } : void 0);
    if (!speechToTextSession) {
      return;
    }
    disposables.add(speechToTextSession.onDidChange((e) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      this.b.$emitSpeechToTextEvent(session, e);
    }));
    disposables.add(cts.token.onCancellationRequested(() => disposables.dispose()));
  }
  async $cancelSpeechToTextSession(session) {
    this.d.get(session)?.dispose(true);
    this.d.delete(session);
  }
  async $createTextToSpeechSession(handle, session, language) {
    const provider = this.c.get(handle);
    if (!provider) {
      return;
    }
    const disposables = new $2c();
    const cts = new $ad();
    this.d.set(session, cts);
    const textToSpeech = await provider.provideTextToSpeechSession(cts.token, language ? { language } : void 0);
    if (!textToSpeech) {
      return;
    }
    this.f.set(session, textToSpeech);
    disposables.add(textToSpeech.onDidChange((e) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      this.b.$emitTextToSpeechEvent(session, e);
    }));
    disposables.add(cts.token.onCancellationRequested(() => disposables.dispose()));
  }
  async $synthesizeSpeech(session, text) {
    this.f.get(session)?.synthesize(text);
  }
  async $cancelTextToSpeechSession(session) {
    this.d.get(session)?.dispose(true);
    this.d.delete(session);
    this.f.delete(session);
  }
  async $createKeywordRecognitionSession(handle, session) {
    const provider = this.c.get(handle);
    if (!provider) {
      return;
    }
    const disposables = new $2c();
    const cts = new $ad();
    this.d.set(session, cts);
    const keywordRecognitionSession = await provider.provideKeywordRecognitionSession(cts.token);
    if (!keywordRecognitionSession) {
      return;
    }
    disposables.add(keywordRecognitionSession.onDidChange((e) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      this.b.$emitKeywordRecognitionEvent(session, e);
    }));
    disposables.add(cts.token.onCancellationRequested(() => disposables.dispose()));
  }
  async $cancelKeywordRecognitionSession(session) {
    this.d.get(session)?.dispose(true);
    this.d.delete(session);
  }
  registerProvider(extension, identifier, provider) {
    const handle = _$Iyc.a++;
    this.c.set(handle, provider);
    this.b.$registerProvider(handle, identifier, { extension, displayName: extension.value });
    return $1c(() => {
      this.b.$unregisterProvider(handle);
      this.c.delete(handle);
    });
  }
};

// out-build/vs/workbench/api/common/extHostStatusBar.js
var $Jyc = class _$Jyc {
  static {
    this.a = 0;
  }
  static {
    this.b = /* @__PURE__ */ new Map([
      ["statusBarItem.errorBackground", new $BU("statusBarItem.errorForeground")],
      ["statusBarItem.warningBackground", new $BU("statusBarItem.warningForeground")]
    ]);
  }
  #proxy;
  #commands;
  constructor(proxy, commands, staticItems, extension, id2, alignment = StatusBarAlignment.Left, priority) {
    this.i = false;
    this.k = "";
    this.q = new $2c();
    this.#proxy = proxy;
    this.#commands = commands;
    if (id2 && extension) {
      this.c = $bU(extension.identifier, id2);
      const item = staticItems.get(this.c);
      if (item) {
        alignment = item.alignLeft ? StatusBarAlignment.Left : StatusBarAlignment.Right;
        priority = item.priority;
        this.j = true;
        this.name = item.name;
        this.text = item.text;
        this.tooltip = item.tooltip;
        this.command = item.command;
        this.accessibilityInformation = item.accessibilityInformation;
      }
    } else {
      this.c = String(_$Jyc.a++);
    }
    this.e = extension;
    this.f = id2;
    this.g = alignment;
    this.h = this.u(priority);
  }
  u(priority) {
    if (!$Dg(priority)) {
      return void 0;
    }
    if (priority === Number.POSITIVE_INFINITY) {
      return Number.MAX_VALUE;
    }
    if (priority === Number.NEGATIVE_INFINITY) {
      return -Number.MAX_VALUE;
    }
    return priority;
  }
  get id() {
    return this.f ?? this.e.identifier.value;
  }
  get alignment() {
    return this.g;
  }
  get priority() {
    return this.h;
  }
  get text() {
    return this.k;
  }
  get name() {
    return this.m;
  }
  get tooltip() {
    return this.l;
  }
  get color() {
    return this.n;
  }
  get backgroundColor() {
    return this.o;
  }
  get command() {
    return this.r?.fromApi;
  }
  get accessibilityInformation() {
    return this.t;
  }
  set text(text) {
    this.k = text;
    this.v();
  }
  set name(name) {
    this.m = name;
    this.v();
  }
  set tooltip(tooltip) {
    this.l = tooltip;
    this.v();
  }
  set color(color2) {
    this.n = color2;
    this.v();
  }
  set backgroundColor(color2) {
    if (color2 && !_$Jyc.b.has(color2.id)) {
      color2 = void 0;
    }
    this.o = color2;
    this.v();
  }
  set command(command) {
    if (this.r?.fromApi === command) {
      return;
    }
    if (this.p) {
      this.q.add(this.p);
    }
    this.p = new $2c();
    if (typeof command === "string") {
      this.r = {
        fromApi: command,
        internal: this.#commands.toInternal({ title: "", command }, this.p)
      };
    } else if (command) {
      this.r = {
        fromApi: command,
        internal: this.#commands.toInternal(command, this.p)
      };
    } else {
      this.r = void 0;
    }
    this.v();
  }
  set accessibilityInformation(accessibilityInformation) {
    this.t = accessibilityInformation;
    this.v();
  }
  show() {
    this.j = true;
    this.v();
  }
  hide() {
    clearTimeout(this.s);
    this.j = false;
    this.#proxy.$disposeEntry(this.c);
  }
  v() {
    if (this.i || !this.j) {
      return;
    }
    clearTimeout(this.s);
    this.s = setTimeout(() => {
      this.s = void 0;
      let id2;
      if (this.e) {
        if (this.f) {
          id2 = `${this.e.identifier.value}.${this.f}`;
        } else {
          id2 = this.e.identifier.value;
        }
      } else {
        id2 = this.f;
      }
      let name;
      if (this.m) {
        name = this.m;
      } else {
        name = localize(2765, null, this.e.displayName || this.e.name);
      }
      let color2 = this.n;
      if (this.o) {
        color2 = _$Jyc.b.get(this.o.id);
      }
      const tooltip = MarkdownString.fromStrict(this.l);
      this.#proxy.$setEntry(this.c, id2, this.e?.identifier.value, name, this.k, tooltip, this.r?.internal, color2, this.o, this.g === StatusBarAlignment.Left, this.h, this.t);
      this.q.clear();
    }, 0);
  }
  dispose() {
    this.hide();
    this.i = true;
  }
};
var StatusBarMessage = class {
  constructor(statusBar) {
    this.b = [];
    this.a = statusBar.createStatusBarEntry(void 0, "status.extensionMessage", StatusBarAlignment.Left, Number.MIN_VALUE);
    this.a.name = localize(2766, null);
  }
  dispose() {
    this.b.length = 0;
    this.a.dispose();
  }
  setMessage(message) {
    const data = { message };
    this.b.unshift(data);
    this.c();
    return new $zT(() => {
      const idx = this.b.indexOf(data);
      if (idx >= 0) {
        this.b.splice(idx, 1);
        this.c();
      }
    });
  }
  c() {
    if (this.b.length > 0) {
      this.a.text = this.b[0].message;
      this.a.show();
    } else {
      this.a.hide();
    }
  }
};
var $Kyc = class {
  constructor(mainContext, commands) {
    this.e = /* @__PURE__ */ new Map();
    this.a = mainContext.getProxy($xT.MainThreadStatusBar);
    this.b = commands;
    this.c = new StatusBarMessage(this);
  }
  $acceptStaticEntries(added) {
    for (const item of added) {
      this.e.set(item.entryId, item);
    }
  }
  createStatusBarEntry(extension, id2, alignment, priority) {
    return new $Jyc(this.a, this.b, this.e, extension, id2, alignment, priority);
  }
  setStatusBarMessage(text, timeoutOrThenable) {
    const d = this.c.setMessage(text);
    let handle;
    if (typeof timeoutOrThenable === "number") {
      handle = setTimeout(() => d.dispose(), timeoutOrThenable);
    } else if (typeof timeoutOrThenable !== "undefined") {
      timeoutOrThenable.then(() => d.dispose(), () => d.dispose());
    }
    return new $zT(() => {
      d.dispose();
      clearTimeout(handle);
    });
  }
};

// out-build/vs/workbench/api/common/extHostTextEditors.js
var $4wc = class extends $3c {
  constructor(mainContext, n) {
    super();
    this.n = n;
    this.a = new $ze();
    this.b = new $ze();
    this.c = new $ze();
    this.f = new $ze();
    this.g = new $ze();
    this.h = new $ze();
    this.j = new $ze();
    this.onDidChangeTextEditorSelection = this.a.event;
    this.onDidChangeTextEditorOptions = this.b.event;
    this.onDidChangeTextEditorVisibleRanges = this.c.event;
    this.onDidChangeTextEditorViewColumn = this.f.event;
    this.onDidChangeTextEditorDiffInformation = this.g.event;
    this.onDidChangeActiveTextEditor = this.h.event;
    this.onDidChangeVisibleTextEditors = this.j.event;
    this.m = mainContext.getProxy($xT.MainThreadTextEditors);
    this.B(this.n.onDidChangeVisibleTextEditors((e) => this.j.fire(e)));
    this.B(this.n.onDidChangeActiveTextEditor((e) => this.h.fire(e)));
  }
  getActiveTextEditor() {
    return this.n.activeEditor();
  }
  getVisibleTextEditors(internal) {
    const editors = this.n.allEditors();
    return internal ? editors : editors.map((editor) => editor.value);
  }
  async showTextDocument(document2, columnOrOptions, preserveFocus) {
    let options2;
    if (typeof columnOrOptions === "number") {
      options2 = {
        position: ViewColumn2.from(columnOrOptions),
        preserveFocus
      };
    } else if (typeof columnOrOptions === "object") {
      options2 = {
        position: ViewColumn2.from(columnOrOptions.viewColumn),
        preserveFocus: columnOrOptions.preserveFocus,
        selection: typeof columnOrOptions.selection === "object" ? Range.from(columnOrOptions.selection) : void 0,
        pinned: typeof columnOrOptions.preview === "boolean" ? !columnOrOptions.preview : void 0
      };
    } else {
      options2 = {
        preserveFocus: false
      };
    }
    const editorId = await this.m.$tryShowTextDocument(document2.uri, options2);
    const editor = editorId && this.n.getEditor(editorId);
    if (editor) {
      return editor.value;
    }
    if (editorId) {
      throw new Error(`Could NOT open editor for "${document2.uri.toString()}" because another editor opened in the meantime.`);
    } else {
      throw new Error(`Could NOT open editor for "${document2.uri.toString()}".`);
    }
  }
  createTextEditorDecorationType(extension, options2) {
    return new $nW(this.m, extension, options2).value;
  }
  // --- called from main thread
  $acceptEditorPropertiesChanged(id2, data) {
    const textEditor = this.n.getEditor(id2);
    if (!textEditor) {
      throw new Error("unknown text editor");
    }
    if (data.options) {
      textEditor._acceptOptions(data.options);
    }
    if (data.selections) {
      const selections = data.selections.selections.map(Selection.to);
      textEditor._acceptSelections(selections);
    }
    if (data.visibleRanges) {
      const visibleRanges = $Mb(data.visibleRanges.map(Range.to));
      textEditor._acceptVisibleRanges(visibleRanges);
    }
    if (data.options) {
      this.b.fire({
        textEditor: textEditor.value,
        options: { ...data.options, lineNumbers: TextEditorLineNumbersStyle2.to(data.options.lineNumbers) }
      });
    }
    if (data.selections) {
      const kind = TextEditorSelectionChangeKind.fromValue(data.selections.source);
      const selections = data.selections.selections.map(Selection.to);
      this.a.fire({
        textEditor: textEditor.value,
        selections,
        kind
      });
    }
    if (data.visibleRanges) {
      const visibleRanges = $Mb(data.visibleRanges.map(Range.to));
      this.c.fire({
        textEditor: textEditor.value,
        visibleRanges
      });
    }
  }
  $acceptEditorPositionData(data) {
    for (const id2 in data) {
      const textEditor = this.n.getEditor(id2);
      if (!textEditor) {
        throw new Error("Unknown text editor");
      }
      const viewColumn = ViewColumn2.to(data[id2]);
      if (textEditor.value.viewColumn !== viewColumn) {
        textEditor._acceptViewColumn(viewColumn);
        this.f.fire({ textEditor: textEditor.value, viewColumn });
      }
    }
  }
  $acceptEditorDiffInformation(id2, diffInformation) {
    const textEditor = this.n.getEditor(id2);
    if (!textEditor) {
      throw new Error("unknown text editor");
    }
    if (!diffInformation) {
      textEditor._acceptDiffInformation(void 0);
      this.g.fire({
        textEditor: textEditor.value,
        diffInformation: void 0
      });
      return;
    }
    const that = this;
    const result = diffInformation.map((diff2) => {
      const original = URI.revive(diff2.original);
      const modified = URI.revive(diff2.modified);
      const changes = diff2.changes.map((change) => {
        const [originalStartLineNumber, originalEndLineNumberExclusive, modifiedStartLineNumber, modifiedEndLineNumberExclusive] = change;
        let kind;
        if (originalStartLineNumber === originalEndLineNumberExclusive) {
          kind = TextEditorChangeKind.Addition;
        } else if (modifiedStartLineNumber === modifiedEndLineNumberExclusive) {
          kind = TextEditorChangeKind.Deletion;
        } else {
          kind = TextEditorChangeKind.Modification;
        }
        return {
          original: {
            startLineNumber: originalStartLineNumber,
            endLineNumberExclusive: originalEndLineNumberExclusive
          },
          modified: {
            startLineNumber: modifiedStartLineNumber,
            endLineNumberExclusive: modifiedEndLineNumberExclusive
          },
          kind
        };
      });
      return Object.freeze({
        documentVersion: diff2.documentVersion,
        original,
        modified,
        changes,
        get isStale() {
          const document2 = that.n.getDocument(modified);
          return document2?.version !== diff2.documentVersion;
        }
      });
    });
    textEditor._acceptDiffInformation(result);
    this.g.fire({
      textEditor: textEditor.value,
      diffInformation: result
    });
  }
  getDiffInformation(id2) {
    return Promise.resolve(this.m.$getDiffInformation(id2));
  }
};

// out-build/vs/workbench/api/common/extHostTheming.js
var $Qyc = class $Qyc2 {
  constructor(_extHostRpc) {
    this.a = new $5U(ColorThemeKind.Dark);
    this.b = new $ze();
  }
  get activeColorTheme() {
    return this.a;
  }
  $onColorThemeChange(type) {
    let kind;
    switch (type) {
      case "light":
        kind = ColorThemeKind.Light;
        break;
      case "hcDark":
        kind = ColorThemeKind.HighContrast;
        break;
      case "hcLight":
        kind = ColorThemeKind.HighContrastLight;
        break;
      default:
        kind = ColorThemeKind.Dark;
    }
    this.a = new $5U(kind);
    this.b.fire(this.a);
  }
  get onDidChangeActiveColorTheme() {
    return this.b.event;
  }
};
$Qyc = __decorate([
  __param(0, $gW)
], $Qyc);

// out-build/vs/workbench/api/common/extHostTimeline.js
var $Ryc = $Qk("IExtHostTimeline");
var $Syc = class {
  constructor(mainContext, commands) {
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.a = mainContext.getProxy($xT.MainThreadTimeline);
    commands.registerArgumentProcessor({
      processArgument: (arg, extension) => {
        if (arg && arg.$mid === 12) {
          if (this.b.get(arg.source) && $5z.equals(extension, this.b.get(arg.source)?.extension)) {
            const uri = arg.uri === void 0 ? void 0 : URI.revive(arg.uri);
            return this.c.get(arg.source)?.get(getUriKey(uri))?.get(arg.handle);
          } else {
            return void 0;
          }
        }
        return arg;
      }
    });
  }
  async $getTimeline(id2, uri, options2, token) {
    const item = this.b.get(id2);
    return item?.provider.provideTimeline(URI.revive(uri), options2, token);
  }
  registerTimelineProvider(scheme, provider, extensionId, commandConverter) {
    const timelineDisposables = new $2c();
    const convertTimelineItem = this.d(provider.id, commandConverter, timelineDisposables).bind(this);
    let disposable;
    if (provider.onDidChange) {
      disposable = provider.onDidChange((e) => this.a.$emitTimelineChangeEvent({ uri: void 0, reset: true, ...e, id: provider.id }), this);
    }
    const itemsBySourceAndUriMap = this.c;
    return this.f({
      ...provider,
      scheme,
      onDidChange: void 0,
      async provideTimeline(uri, options2, token) {
        if (options2?.resetCache) {
          timelineDisposables.clear();
          itemsBySourceAndUriMap.get(provider.id)?.clear();
        }
        const result = await provider.provideTimeline(uri, options2, token);
        if (result === void 0 || result === null) {
          return void 0;
        }
        const convertItem = convertTimelineItem(uri, options2);
        return {
          ...result,
          source: provider.id,
          items: result.items.map(convertItem)
        };
      },
      dispose() {
        for (const sourceMap of itemsBySourceAndUriMap.values()) {
          sourceMap.get(provider.id)?.clear();
        }
        disposable?.dispose();
        timelineDisposables.dispose();
      }
    }, extensionId);
  }
  d(source, commandConverter, disposables) {
    return (uri, options2) => {
      let items;
      if (options2?.cacheResults) {
        let itemsByUri = this.c.get(source);
        if (itemsByUri === void 0) {
          itemsByUri = /* @__PURE__ */ new Map();
          this.c.set(source, itemsByUri);
        }
        const uriKey = getUriKey(uri);
        items = itemsByUri.get(uriKey);
        if (items === void 0) {
          items = /* @__PURE__ */ new Map();
          itemsByUri.set(uriKey, items);
        }
      }
      return (item) => {
        const { iconPath, ...props } = item;
        const handle = `${source}|${item.id ?? item.timestamp}`;
        items?.set(handle, item);
        let icon;
        let iconDark;
        let themeIcon;
        if (item.iconPath) {
          if (iconPath instanceof $AU) {
            themeIcon = { id: iconPath.id, color: iconPath.color };
          } else if (URI.isUri(iconPath)) {
            icon = iconPath;
            iconDark = iconPath;
          } else {
            ({ light: icon, dark: iconDark } = iconPath);
          }
        }
        let tooltip;
        if ($4T.isMarkdownString(props.tooltip)) {
          tooltip = MarkdownString.from(props.tooltip);
        } else if ($zg(props.tooltip)) {
          tooltip = props.tooltip;
        } else if ($4T.isMarkdownString(props.detail)) {
          console.warn("Using deprecated TimelineItem.detail, migrate to TimelineItem.tooltip");
          tooltip = MarkdownString.from(props.detail);
        } else if ($zg(props.detail)) {
          console.warn("Using deprecated TimelineItem.detail, migrate to TimelineItem.tooltip");
          tooltip = props.detail;
        }
        return {
          ...props,
          id: props.id ?? void 0,
          handle,
          source,
          command: item.command ? commandConverter.toInternal(item.command, disposables) : void 0,
          icon,
          iconDark,
          themeIcon,
          tooltip,
          accessibilityInformation: item.accessibilityInformation
        };
      };
    };
  }
  f(provider, extension) {
    const existing = this.b.get(provider.id);
    if (existing) {
      throw new Error(`Timeline Provider ${provider.id} already exists.`);
    }
    this.a.$registerTimelineProvider({
      id: provider.id,
      label: provider.label,
      scheme: provider.scheme
    });
    this.b.set(provider.id, { provider, extension });
    return $1c(() => {
      for (const sourceMap of this.c.values()) {
        sourceMap.get(provider.id)?.clear();
      }
      this.b.delete(provider.id);
      this.a.$unregisterTimelineProvider(provider.id);
      provider.dispose();
    });
  }
};
function getUriKey(uri) {
  return uri?.toString();
}

// out-build/vs/platform/theme/common/iconRegistry.js
var $8r = {
  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) => $zg(s) ? s : void 0;
    if (json && Array.isArray(json.src) && json.src.every((s) => $zg(s.format) && $zg(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 = {}));
var IconRegistry = class {
  constructor() {
    this.a = new $ze();
    this.onDidChange = this.a.event;
    this.d = {
      definitions: {
        icons: {
          type: "object",
          properties: {
            fontId: { type: "string", description: localize(2411, null) },
            fontCharacter: { type: "string", description: localize(2412, null) }
          },
          additionalProperties: false,
          defaultSnippets: [{ body: { fontCharacter: "\\\\e030" } }]
        }
      },
      type: "object",
      properties: {}
    };
    this.e = { type: "string", pattern: `^${ThemeIcon.iconNameExpression}$`, enum: [], enumDescriptions: [] };
    this.b = {};
    this.f = {};
  }
  registerIcon(id2, defaults, description, deprecationMessage) {
    const existing = this.b[id2];
    if (existing) {
      if (description && !existing.description) {
        existing.description = description;
        this.d.properties[id2].markdownDescription = `${description} $(${id2})`;
        const enumIndex = this.e.enum.indexOf(id2);
        if (enumIndex !== -1) {
          this.e.enumDescriptions[enumIndex] = description;
        }
        this.a.fire();
      }
      return existing;
    }
    const iconContribution = { id: id2, description, defaults, deprecationMessage };
    this.b[id2] = iconContribution;
    const propertySchema = { $ref: "#/definitions/icons" };
    if (deprecationMessage) {
      propertySchema.deprecationMessage = deprecationMessage;
    }
    if (description) {
      propertySchema.markdownDescription = `${description}: $(${id2})`;
    }
    this.d.properties[id2] = propertySchema;
    this.e.enum.push(id2);
    this.e.enumDescriptions.push(description || "");
    this.a.fire();
    return { id: id2 };
  }
  deregisterIcon(id2) {
    delete this.b[id2];
    delete this.d.properties[id2];
    const index = this.e.enum.indexOf(id2);
    if (index !== -1) {
      this.e.enum.splice(index, 1);
      this.e.enumDescriptions.splice(index, 1);
    }
    this.a.fire();
  }
  getIcons() {
    return Object.keys(this.b).map((id2) => this.b[id2]);
  }
  getIcon(id2) {
    return this.b[id2];
  }
  getIconSchema() {
    return this.d;
  }
  getIconReferenceSchema() {
    return this.e;
  }
  registerIconFont(id2, definition) {
    const existing = this.f[id2];
    if (existing) {
      return existing;
    }
    this.f[id2] = definition;
    this.a.fire();
    return definition;
  }
  deregisterIconFont(id2) {
    delete this.f[id2];
  }
  getIconFont(id2) {
    return this.f[id2];
  }
  toString() {
    const sorter = (i1, i2) => {
      return i1.id.localeCompare(i2.id);
    };
    const classNames = (i) => {
      while (ThemeIcon.isThemeIcon(i.defaults)) {
        i = this.b[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.b).map((key) => this.b[key]);
    for (const i of contributions.filter((i2) => !!i2.description).sort(sorter)) {
      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(sorter)) {
      reference.push(`|<i class="${classNames(i)}"></i>|${i.id}|`);
    }
    return reference.join("\n");
  }
};
var iconRegistry = new IconRegistry();
$Wn.add($8r.IconContribution, iconRegistry);
function $9r(id2, defaults, description, deprecationMessage) {
  return iconRegistry.registerIcon(id2, defaults, description, deprecationMessage);
}
function initialize() {
  const codiconFontCharacters = $2l();
  for (const icon in codiconFontCharacters) {
    const fontCharacter = "\\" + codiconFontCharacters[icon].toString(16);
    iconRegistry.registerIcon(icon, { fontCharacter });
  }
}
initialize();
var $$r = "vscode://schemas/icons";
var schemaRegistry2 = $Wn.as($Xn.JSONContribution);
schemaRegistry2.registerSchema($$r, iconRegistry.getIconSchema());
var delayer = new $8h(() => schemaRegistry2.notifySchemaChanged($$r), 200);
iconRegistry.onDidChange(() => {
  if (!delayer.isScheduled()) {
    delayer.schedule();
  }
});
var $_r = $9r("widget-close", $6l.close, localize(2413, null));
var $as = $9r("goto-previous-location", $6l.arrowUp, localize(2414, null));
var $bs = $9r("goto-next-location", $6l.arrowDown, localize(2415, null));
var $cs = ThemeIcon.modify($6l.sync, "spin");
var $ds = ThemeIcon.modify($6l.loading, "spin");

// out-build/vs/workbench/common/views.js
var $7M = localize(4298, null);
var $8M = $9r("default-view-icon", $6l.window, localize(4299, null));
var Extensions;
(function(Extensions2) {
  Extensions2.ViewContainersRegistry = "workbench.registry.view.containers";
  Extensions2.ViewsRegistry = "workbench.registry.view";
})(Extensions || (Extensions = {}));
var ViewContainerLocation;
(function(ViewContainerLocation2) {
  ViewContainerLocation2[ViewContainerLocation2["Sidebar"] = 0] = "Sidebar";
  ViewContainerLocation2[ViewContainerLocation2["Panel"] = 1] = "Panel";
  ViewContainerLocation2[ViewContainerLocation2["AuxiliaryBar"] = 2] = "AuxiliaryBar";
})(ViewContainerLocation || (ViewContainerLocation = {}));
var ViewContainersRegistryImpl = class extends $3c {
  constructor() {
    super(...arguments);
    this.c = this.B(new $ze());
    this.onDidRegister = this.c.event;
    this.f = this.B(new $ze());
    this.onDidDeregister = this.f.event;
    this.g = /* @__PURE__ */ new Map();
    this.h = [];
  }
  get all() {
    return [...this.g.values()].flat();
  }
  registerViewContainer(viewContainerDescriptor, viewContainerLocation, options2) {
    const existing = this.get(viewContainerDescriptor.id);
    if (existing) {
      return existing;
    }
    const viewContainer = viewContainerDescriptor;
    viewContainer.openCommandActionDescriptor = options2?.doNotRegisterOpenCommand ? void 0 : viewContainer.openCommandActionDescriptor ?? { id: viewContainer.id };
    const viewContainers = $Bc(this.g, viewContainerLocation, []);
    viewContainers.push(viewContainer);
    if (options2?.isDefault) {
      this.h.push(viewContainer);
    }
    this.c.fire({ viewContainer, viewContainerLocation });
    return viewContainer;
  }
  deregisterViewContainer(viewContainer) {
    for (const viewContainerLocation of this.g.keys()) {
      const viewContainers = this.g.get(viewContainerLocation);
      const index = viewContainers?.indexOf(viewContainer);
      if (index !== -1) {
        viewContainers?.splice(index, 1);
        if (viewContainers.length === 0) {
          this.g.delete(viewContainerLocation);
        }
        this.f.fire({ viewContainer, viewContainerLocation });
        return;
      }
    }
  }
  get(id2) {
    return this.all.filter((viewContainer) => viewContainer.id === id2)[0];
  }
  getViewContainers(location2) {
    return [...this.g.get(location2) || []];
  }
  getViewContainerLocation(container) {
    return [...this.g.keys()].filter((location2) => this.getViewContainers(location2).filter((viewContainer) => viewContainer?.id === container.id).length > 0)[0];
  }
  getDefaultViewContainer(location2) {
    return this.h.find((viewContainer) => this.getViewContainerLocation(viewContainer) === location2);
  }
};
$Wn.add(Extensions.ViewContainersRegistry, new ViewContainersRegistryImpl());
var ViewContentGroups;
(function(ViewContentGroups2) {
  ViewContentGroups2["Open"] = "2_open";
  ViewContentGroups2["Debug"] = "4_debug";
  ViewContentGroups2["SCM"] = "5_scm";
  ViewContentGroups2["More"] = "9_more";
})(ViewContentGroups || (ViewContentGroups = {}));
function compareViewContentDescriptors(a, b) {
  const aGroup = a.group ?? ViewContentGroups.More;
  const bGroup = b.group ?? ViewContentGroups.More;
  if (aGroup !== bGroup) {
    return aGroup.localeCompare(bGroup);
  }
  return (a.order ?? 5) - (b.order ?? 5);
}
var ViewsRegistry = class extends $3c {
  constructor() {
    super(...arguments);
    this.c = this.B(new $ze());
    this.onViewsRegistered = this.c.event;
    this.f = this.B(new $ze());
    this.onViewsDeregistered = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeContainer = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeViewWelcomeContent = this.h.event;
    this.j = [];
    this.m = /* @__PURE__ */ new Map();
    this.n = new $Lc();
  }
  registerViews(views, viewContainer) {
    this.registerViews2([{ views, viewContainer }]);
  }
  registerViews2(views) {
    views.forEach(({ views: views2, viewContainer }) => this.r(views2, viewContainer));
    this.c.fire(views);
  }
  deregisterViews(viewDescriptors, viewContainer) {
    const views = this.s(viewDescriptors, viewContainer);
    if (views.length) {
      this.f.fire({ views, viewContainer });
    }
  }
  moveViews(viewsToMove, viewContainer) {
    for (const container of this.m.keys()) {
      if (container !== viewContainer) {
        const views = this.s(viewsToMove, container);
        if (views.length) {
          this.r(views, viewContainer);
          this.g.fire({ views, from: container, to: viewContainer });
        }
      }
    }
  }
  getViews(loc) {
    return this.m.get(loc) || [];
  }
  getView(id2) {
    for (const viewContainer of this.j) {
      const viewDescriptor = (this.m.get(viewContainer) || []).filter((v) => v.id === id2)[0];
      if (viewDescriptor) {
        return viewDescriptor;
      }
    }
    return null;
  }
  getViewContainer(viewId) {
    for (const viewContainer of this.j) {
      const viewDescriptor = (this.m.get(viewContainer) || []).filter((v) => v.id === viewId)[0];
      if (viewDescriptor) {
        return viewContainer;
      }
    }
    return null;
  }
  registerViewWelcomeContent(id2, viewContent) {
    this.n.add(id2, viewContent);
    this.h.fire(id2);
    return $1c(() => {
      this.n.delete(id2, viewContent);
      this.h.fire(id2);
    });
  }
  registerViewWelcomeContent2(id2, viewContentMap) {
    const disposables = /* @__PURE__ */ new Map();
    for (const [key, content] of viewContentMap) {
      this.n.add(id2, content);
      disposables.set(key, $1c(() => {
        this.n.delete(id2, content);
        this.h.fire(id2);
      }));
    }
    this.h.fire(id2);
    return disposables;
  }
  getViewWelcomeContent(id2) {
    const result = [];
    this.n.forEach(id2, (descriptor) => result.push(descriptor));
    return result.sort(compareViewContentDescriptors);
  }
  r(viewDescriptors, viewContainer) {
    let views = this.m.get(viewContainer);
    if (!views) {
      views = [];
      this.m.set(viewContainer, views);
      this.j.push(viewContainer);
    }
    for (const viewDescriptor of viewDescriptors) {
      if (this.getView(viewDescriptor.id) !== null) {
        throw new Error(localize(4300, null, viewDescriptor.id));
      }
      views.push(viewDescriptor);
    }
  }
  s(viewDescriptors, viewContainer) {
    const views = this.m.get(viewContainer);
    if (!views) {
      return [];
    }
    const viewsToDeregister = [];
    const remaningViews = [];
    for (const view of views) {
      if (!viewDescriptors.includes(view)) {
        remaningViews.push(view);
      } else {
        viewsToDeregister.push(view);
      }
    }
    if (viewsToDeregister.length) {
      if (remaningViews.length) {
        this.m.set(viewContainer, remaningViews);
      } else {
        this.m.delete(viewContainer);
        this.j.splice(this.j.indexOf(viewContainer), 1);
      }
    }
    return viewsToDeregister;
  }
};
$Wn.add(Extensions.ViewsRegistry, new ViewsRegistry());
var $$M = $Qk("viewDescriptorService");
var ViewVisibilityState;
(function(ViewVisibilityState2) {
  ViewVisibilityState2[ViewVisibilityState2["Default"] = 0] = "Default";
  ViewVisibilityState2[ViewVisibilityState2["Expand"] = 1] = "Expand";
})(ViewVisibilityState || (ViewVisibilityState = {}));
var TreeItemCollapsibleState2;
(function(TreeItemCollapsibleState3) {
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["None"] = 0] = "None";
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["Collapsed"] = 1] = "Collapsed";
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["Expanded"] = 2] = "Expanded";
})(TreeItemCollapsibleState2 || (TreeItemCollapsibleState2 = {}));
var $aN = class extends Error {
  constructor(treeViewId) {
    super(localize(4301, null, treeViewId));
    this.name = "NoTreeViewError";
  }
  static is(err) {
    return !!err && err.name === "NoTreeViewError";
  }
};

// out-build/vs/editor/common/services/treeViewsDnd.js
var $Sfb = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  removeDragOperationTransfer(uuid) {
    if (uuid && this.a.has(uuid)) {
      const operation = this.a.get(uuid);
      this.a.delete(uuid);
      return operation;
    }
    return void 0;
  }
  addDragOperationTransfer(uuid, transferPromise) {
    this.a.set(uuid, transferPromise);
  }
};

// out-build/vs/workbench/api/common/extHostTreeViews.js
function toTreeItemLabel(label, extension) {
  if ($zg(label)) {
    return { label };
  }
  if (label && typeof label === "object" && typeof label.label === "string") {
    let highlights = void 0;
    if (Array.isArray(label.highlights)) {
      highlights = label.highlights.filter((highlight) => highlight.length === 2 && typeof highlight[0] === "number" && typeof highlight[1] === "number");
      highlights = highlights.length ? highlights : void 0;
    }
    return { label: label.label, highlights };
  }
  return void 0;
}
var $Tyc = class extends $3c {
  constructor(f, g, h) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.a = /* @__PURE__ */ new Map();
    this.b = new $Sfb();
    function isTreeViewConvertableItem(arg) {
      return arg && arg.$treeViewId && (arg.$treeItemHandle || arg.$selectedTreeItems || arg.$focusedTreeItem);
    }
    g.registerArgumentProcessor({
      processArgument: (arg) => {
        if (isTreeViewConvertableItem(arg)) {
          return this.r(arg);
        } else if (Array.isArray(arg) && arg.length > 0) {
          return arg.map((item) => {
            if (isTreeViewConvertableItem(item)) {
              return this.r(item);
            }
            return item;
          });
        }
        return arg;
      }
    });
  }
  registerTreeDataProvider(id2, treeDataProvider, extension) {
    const treeView = this.createTreeView(id2, { treeDataProvider }, extension);
    return { dispose: () => treeView.dispose() };
  }
  createTreeView(viewId, options2, extension) {
    if (!options2 || !options2.treeDataProvider) {
      throw new Error("Options with treeDataProvider is mandatory");
    }
    const dropMimeTypes = options2.dragAndDropController?.dropMimeTypes ?? [];
    const dragMimeTypes = options2.dragAndDropController?.dragMimeTypes ?? [];
    const hasHandleDrag = !!options2.dragAndDropController?.handleDrag;
    const hasHandleDrop = !!options2.dragAndDropController?.handleDrop;
    const treeView = this.m(viewId, options2, extension);
    const proxyOptions = { showCollapseAll: !!options2.showCollapseAll, canSelectMany: !!options2.canSelectMany, dropMimeTypes, dragMimeTypes, hasHandleDrag, hasHandleDrop, manuallyManageCheckboxes: !!options2.manageCheckboxStateManually };
    const registerPromise = this.f.$registerTreeViewDataProvider(viewId, proxyOptions);
    const view = {
      get onDidCollapseElement() {
        return treeView.onDidCollapseElement;
      },
      get onDidExpandElement() {
        return treeView.onDidExpandElement;
      },
      get selection() {
        return treeView.selectedElements;
      },
      get onDidChangeSelection() {
        return treeView.onDidChangeSelection;
      },
      get activeItem() {
        $AN(extension, "treeViewActiveItem");
        return treeView.focusedElement;
      },
      get onDidChangeActiveItem() {
        $AN(extension, "treeViewActiveItem");
        return treeView.onDidChangeActiveItem;
      },
      get visible() {
        return treeView.visible;
      },
      get onDidChangeVisibility() {
        return treeView.onDidChangeVisibility;
      },
      get onDidChangeCheckboxState() {
        return treeView.onDidChangeCheckboxState;
      },
      get message() {
        return treeView.message;
      },
      set message(message) {
        if ($dm(message)) {
          $AN(extension, "treeViewMarkdownMessage");
        }
        treeView.message = message;
      },
      get title() {
        return treeView.title;
      },
      set title(title) {
        treeView.title = title;
      },
      get description() {
        return treeView.description;
      },
      set description(description) {
        treeView.description = description;
      },
      get badge() {
        return treeView.badge;
      },
      set badge(badge) {
        if (badge !== void 0 && ViewBadge.isViewBadge(badge)) {
          treeView.badge = {
            value: Math.floor(Math.abs(badge.value)),
            tooltip: badge.tooltip
          };
        } else if (badge === void 0) {
          treeView.badge = void 0;
        }
      },
      reveal: (element, options3) => {
        return treeView.reveal(element, options3);
      },
      dispose: async () => {
        await registerPromise;
        this.a.delete(viewId);
        treeView.dispose();
      }
    };
    this.B(view);
    return view;
  }
  async $getChildren(treeViewId, treeItemHandles) {
    const treeView = this.a.get(treeViewId);
    if (!treeView) {
      return Promise.reject(new $aN(treeViewId));
    }
    if (!treeItemHandles) {
      const children = await treeView.getChildren();
      return children ? [[0, ...children]] : void 0;
    }
    const result = [];
    for (let i = 0; i < treeItemHandles.length; i++) {
      const treeItemHandle = treeItemHandles[i];
      const children = await treeView.getChildren(treeItemHandle);
      if (children) {
        result.push([i, ...children]);
      }
    }
    return result;
  }
  async $handleDrop(destinationViewId, requestId, treeDataTransferDTO, targetItemHandle, token, operationUuid, sourceViewId, sourceTreeItemHandles) {
    const treeView = this.a.get(destinationViewId);
    if (!treeView) {
      return Promise.reject(new $aN(destinationViewId));
    }
    const treeDataTransfer = DataTransfer.toDataTransfer(treeDataTransferDTO, async (dataItemIndex) => {
      return (await this.f.$resolveDropFileData(destinationViewId, requestId, dataItemIndex)).buffer;
    });
    if (sourceViewId === destinationViewId && sourceTreeItemHandles) {
      await this.j(treeDataTransfer, treeView, sourceTreeItemHandles, token, operationUuid);
    }
    return treeView.onDrop(treeDataTransfer, targetItemHandle, token);
  }
  async j(treeDataTransfer, treeView, sourceTreeItemHandles, token, operationUuid) {
    const existingTransferOperation = this.b.removeDragOperationTransfer(operationUuid);
    if (existingTransferOperation) {
      (await existingTransferOperation)?.forEach((value, key) => {
        if (value) {
          treeDataTransfer.set(key, value);
        }
      });
    } else if (operationUuid && treeView.handleDrag) {
      const willDropPromise = treeView.handleDrag(sourceTreeItemHandles, treeDataTransfer, token);
      this.b.addDragOperationTransfer(operationUuid, willDropPromise);
      await willDropPromise;
    }
    return treeDataTransfer;
  }
  async $handleDrag(sourceViewId, sourceTreeItemHandles, operationUuid, token) {
    const treeView = this.a.get(sourceViewId);
    if (!treeView) {
      return Promise.reject(new $aN(sourceViewId));
    }
    const treeDataTransfer = await this.j(new $wU(), treeView, sourceTreeItemHandles, token, operationUuid);
    if (!treeDataTransfer || token.isCancellationRequested) {
      return;
    }
    return DataTransfer.from(treeDataTransfer);
  }
  async $hasResolve(treeViewId) {
    const treeView = this.a.get(treeViewId);
    if (!treeView) {
      throw new $aN(treeViewId);
    }
    return treeView.hasResolve;
  }
  $resolve(treeViewId, treeItemHandle, token) {
    const treeView = this.a.get(treeViewId);
    if (!treeView) {
      throw new $aN(treeViewId);
    }
    return treeView.resolveTreeItem(treeItemHandle, token);
  }
  $setExpanded(treeViewId, treeItemHandle, expanded) {
    const treeView = this.a.get(treeViewId);
    if (!treeView) {
      throw new $aN(treeViewId);
    }
    treeView.setExpanded(treeItemHandle, expanded);
  }
  $setSelectionAndFocus(treeViewId, selectedHandles, focusedHandle) {
    const treeView = this.a.get(treeViewId);
    if (!treeView) {
      throw new $aN(treeViewId);
    }
    treeView.setSelectionAndFocus(selectedHandles, focusedHandle);
  }
  $setVisible(treeViewId, isVisible) {
    const treeView = this.a.get(treeViewId);
    if (!treeView) {
      if (!isVisible) {
        return;
      }
      throw new $aN(treeViewId);
    }
    treeView.setVisible(isVisible);
  }
  $changeCheckboxState(treeViewId, checkboxUpdate) {
    const treeView = this.a.get(treeViewId);
    if (!treeView) {
      throw new $aN(treeViewId);
    }
    treeView.setCheckboxState(checkboxUpdate);
  }
  m(id2, options2, extension) {
    const treeView = this.B(new ExtHostTreeView(id2, options2, this.f, this.g.converter, this.h, extension));
    this.a.set(id2, treeView);
    return treeView;
  }
  r(arg) {
    const treeView = this.a.get(arg.$treeViewId);
    if (treeView && "$treeItemHandle" in arg) {
      return treeView.getExtensionElement(arg.$treeItemHandle);
    }
    if (treeView && "$focusedTreeItem" in arg && arg.$focusedTreeItem) {
      return treeView.focusedElement;
    }
    return null;
  }
};
var ExtHostTreeView = class _ExtHostTreeView extends $3c {
  static {
    this.a = "0";
  }
  static {
    this.b = "1";
  }
  get visible() {
    return this.r;
  }
  get selectedElements() {
    return this.s.map((handle) => this.getExtensionElement(handle)).filter((element) => !$Ig(element));
  }
  get focusedElement() {
    return this.t ? this.getExtensionElement(this.t) : void 0;
  }
  constructor(I, options2, J, L, M, N) {
    super();
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.h = void 0;
    this.j = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    this.r = false;
    this.s = [];
    this.t = void 0;
    this.u = this.B(new $ze());
    this.onDidExpandElement = this.u.event;
    this.w = this.B(new $ze());
    this.onDidCollapseElement = this.w.event;
    this.y = this.B(new $ze());
    this.onDidChangeSelection = this.y.event;
    this.z = this.B(new $ze());
    this.onDidChangeActiveItem = this.z.event;
    this.C = this.B(new $ze());
    this.onDidChangeVisibility = this.C.event;
    this.D = this.B(new $ze());
    this.onDidChangeCheckboxState = this.D.event;
    this.F = this.B(new $ze());
    this.G = Promise.resolve();
    this.H = Promise.resolve();
    this.O = "";
    this.P = "";
    this.Z = new $ad();
    if (N.contributes && N.contributes.views) {
      for (const location2 in N.contributes.views) {
        for (const view of N.contributes.views[location2]) {
          if (view.id === I) {
            this.P = view.name;
          }
        }
      }
    }
    this.f = options2.treeDataProvider;
    this.g = options2.dragAndDropController;
    if (this.f.onDidChangeTreeData) {
      this.B(this.f.onDidChangeTreeData((elementOrElements) => {
        if (Array.isArray(elementOrElements) && elementOrElements.length === 0) {
          return;
        }
        this.F.fire({ message: false, element: elementOrElements });
      }));
    }
    let refreshingPromise;
    let promiseCallback;
    const onDidChangeData = Event.debounce(this.F.event, (result, current) => {
      if (!result) {
        result = { message: false, elements: [] };
      }
      if (current.element !== false) {
        if (!refreshingPromise) {
          refreshingPromise = new Promise((c) => promiseCallback = c);
          this.G = this.G.then(() => refreshingPromise);
        }
        if (Array.isArray(current.element)) {
          result.elements.push(...current.element);
        } else {
          result.elements.push(current.element);
        }
      }
      if (current.message) {
        result.message = true;
      }
      return result;
    }, 200, true);
    this.B(onDidChangeData(({ message, elements }) => {
      if (elements.length) {
        this.H = this.H.then(() => {
          const _promiseCallback = promiseCallback;
          refreshingPromise = null;
          return this.$(elements).then(() => _promiseCallback());
        });
      }
      if (message) {
        this.J.$setMessage(this.I, MarkdownString.fromStrict(this.O) ?? "");
      }
    }));
  }
  async getChildren(parentHandle) {
    const parentElement = parentHandle ? this.getExtensionElement(parentHandle) : void 0;
    if (parentHandle && !parentElement) {
      this.M.error(`No tree item with id '${parentHandle}' found.`);
      return Promise.resolve([]);
    }
    let childrenNodes = this.X(parentHandle);
    if (!childrenNodes) {
      childrenNodes = await this.Y(parentElement);
    }
    return childrenNodes ? childrenNodes.map((n) => n.item) : void 0;
  }
  getExtensionElement(treeItemHandle) {
    return this.j.get(treeItemHandle);
  }
  reveal(element, options2) {
    options2 = options2 ? options2 : { select: true, focus: false };
    const select = $Ig(options2.select) ? true : options2.select;
    const focus = $Ig(options2.focus) ? false : options2.focus;
    const expand = $Ig(options2.expand) ? false : options2.expand;
    if (typeof this.f.getParent !== "function") {
      return Promise.reject(new Error(`Required registered TreeDataProvider to implement 'getParent' method to access 'reveal' method`));
    }
    if (element) {
      return this.G.then(() => this.S(element)).then((parentChain) => this.W(element, parentChain[parentChain.length - 1]).then((treeNode) => this.J.$reveal(this.I, { item: treeNode.item, parentChain: parentChain.map((p) => p.item) }, { select, focus, expand })), (error) => this.M.error(error));
    } else {
      return this.J.$reveal(this.I, void 0, { select, focus, expand });
    }
  }
  get message() {
    return this.O;
  }
  set message(message) {
    this.O = message;
    this.F.fire({ message: true, element: false });
  }
  get title() {
    return this.P;
  }
  set title(title) {
    this.P = title;
    this.J.$setTitle(this.I, title, this.Q);
  }
  get description() {
    return this.Q;
  }
  set description(description) {
    this.Q = description;
    this.J.$setTitle(this.I, this.P, description);
  }
  get badge() {
    return this.R;
  }
  set badge(badge) {
    if (this.R?.value === badge?.value && this.R?.tooltip === badge?.tooltip) {
      return;
    }
    this.R = ViewBadge2.from(badge);
    this.J.$setBadge(this.I, badge);
  }
  setExpanded(treeItemHandle, expanded) {
    const element = this.getExtensionElement(treeItemHandle);
    if (element) {
      if (expanded) {
        this.u.fire(Object.freeze({ element }));
      } else {
        this.w.fire(Object.freeze({ element }));
      }
    }
  }
  setSelectionAndFocus(selectedHandles, focusedHandle) {
    const changedSelection = !$zb(this.s, selectedHandles);
    this.s = selectedHandles;
    const changedFocus = this.t !== focusedHandle;
    this.t = focusedHandle;
    if (changedSelection) {
      this.y.fire(Object.freeze({ selection: this.selectedElements }));
    }
    if (changedFocus) {
      this.z.fire(Object.freeze({ activeItem: this.focusedElement }));
    }
  }
  setVisible(visible) {
    if (visible !== this.r) {
      this.r = visible;
      this.C.fire(Object.freeze({ visible: this.r }));
    }
  }
  async setCheckboxState(checkboxUpdates) {
    const items = (await Promise.all(checkboxUpdates.map(async (checkboxUpdate) => {
      const extensionItem = this.getExtensionElement(checkboxUpdate.treeItemHandle);
      if (extensionItem) {
        return {
          extensionItem,
          treeItem: await this.f.getTreeItem(extensionItem),
          newState: checkboxUpdate.newState ? TreeItemCheckboxState.Checked : TreeItemCheckboxState.Unchecked
        };
      }
      return Promise.resolve(void 0);
    }))).filter((item) => item !== void 0);
    items.forEach((item) => {
      item.treeItem.checkboxState = item.newState ? TreeItemCheckboxState.Checked : TreeItemCheckboxState.Unchecked;
    });
    this.D.fire({ items: items.map((item) => [item.extensionItem, item.newState]) });
  }
  async handleDrag(sourceTreeItemHandles, treeDataTransfer, token) {
    const extensionTreeItems = [];
    for (const sourceHandle of sourceTreeItemHandles) {
      const extensionItem = this.getExtensionElement(sourceHandle);
      if (extensionItem) {
        extensionTreeItems.push(extensionItem);
      }
    }
    if (!this.g?.handleDrag || extensionTreeItems.length === 0) {
      return;
    }
    await this.g.handleDrag(extensionTreeItems, treeDataTransfer, token);
    return treeDataTransfer;
  }
  get hasHandleDrag() {
    return !!this.g?.handleDrag;
  }
  async onDrop(treeDataTransfer, targetHandleOrNode, token) {
    const target = targetHandleOrNode ? this.getExtensionElement(targetHandleOrNode) : void 0;
    if (!target && targetHandleOrNode || !this.g?.handleDrop) {
      return;
    }
    return $Nh(() => this.g?.handleDrop ? this.g.handleDrop(target, treeDataTransfer, token) : void 0);
  }
  get hasResolve() {
    return !!this.f.resolveTreeItem;
  }
  async resolveTreeItem(treeItemHandle, token) {
    if (!this.f.resolveTreeItem) {
      return;
    }
    const element = this.j.get(treeItemHandle);
    if (element) {
      const node = this.m.get(element);
      if (node) {
        const resolve = await this.f.resolveTreeItem(node.extensionItem, element, token) ?? node.extensionItem;
        this.hb(resolve);
        node.item.tooltip = this.eb(resolve.tooltip);
        node.item.command = this.fb(node.disposableStore, resolve.command);
        return node.item;
      }
    }
    return;
  }
  S(element) {
    return this.U(element).then((parent) => {
      if (!parent) {
        return Promise.resolve([]);
      }
      return this.S(parent).then((result) => this.W(parent, result[result.length - 1]).then((parentNode) => {
        result.push(parentNode);
        return result;
      }));
    });
  }
  U(element) {
    const node = this.m.get(element);
    if (node) {
      return Promise.resolve(node.parent ? this.j.get(node.parent.item.handle) : void 0);
    }
    return $Nh(() => this.f.getParent(element));
  }
  W(element, parent) {
    const node = this.m.get(element);
    if (node) {
      return Promise.resolve(node);
    }
    return $Nh(() => this.f.getTreeItem(element)).then((extTreeItem) => this.kb(element, extTreeItem, parent, true)).then((handle) => this.getChildren(parent ? parent.item.handle : void 0).then(() => {
      const cachedElement = this.getExtensionElement(handle);
      if (cachedElement) {
        const node2 = this.m.get(cachedElement);
        if (node2) {
          return Promise.resolve(node2);
        }
      }
      throw new Error(`Cannot resolve tree item for element ${handle} from extension ${this.N.identifier.value}`);
    }));
  }
  X(parentNodeOrHandle) {
    if (parentNodeOrHandle) {
      let parentNode;
      if (typeof parentNodeOrHandle === "string") {
        const parentElement = this.getExtensionElement(parentNodeOrHandle);
        parentNode = parentElement ? this.m.get(parentElement) : void 0;
      } else {
        parentNode = parentNodeOrHandle;
      }
      return parentNode ? parentNode.children || void 0 : void 0;
    }
    return this.h;
  }
  async Y(parentElement) {
    this.rb(parentElement);
    const cts = new $ad(this.Z.token);
    try {
      const parentNode = parentElement ? this.m.get(parentElement) : void 0;
      const elements = await this.f.getChildren(parentElement);
      if (cts.token.isCancellationRequested) {
        return void 0;
      }
      const coalescedElements = $Mb(elements || []);
      const treeItems = await Promise.all($Mb(coalescedElements).map((element) => {
        return this.f.getTreeItem(element);
      }));
      if (cts.token.isCancellationRequested) {
        return void 0;
      }
      const items = treeItems.map((item, index) => item ? this.db(coalescedElements[index], item, parentNode) : null);
      return $Mb(items);
    } finally {
      cts.dispose();
    }
  }
  $(elements) {
    const hasRoot = elements.some((element) => !element);
    if (hasRoot) {
      this.Z.dispose(true);
      this.Z = new $ad();
      this.tb();
      return this.J.$refresh(this.I);
    } else {
      const handlesToRefresh = this.ab(elements);
      if (handlesToRefresh.length) {
        return this.bb(handlesToRefresh);
      }
    }
    return Promise.resolve(void 0);
  }
  ab(elements) {
    const elementsToUpdate = /* @__PURE__ */ new Set();
    const elementNodes = elements.map((element) => this.m.get(element));
    for (const elementNode of elementNodes) {
      if (elementNode && !elementsToUpdate.has(elementNode.item.handle)) {
        let currentNode = elementNode;
        while (currentNode && currentNode.parent && elementNodes.findIndex((node) => currentNode && currentNode.parent && node && node.item.handle === currentNode.parent.item.handle) === -1) {
          const parentElement = this.j.get(currentNode.parent.item.handle);
          currentNode = parentElement ? this.m.get(parentElement) : void 0;
        }
        if (currentNode && !currentNode.parent) {
          elementsToUpdate.add(elementNode.item.handle);
        }
      }
    }
    const handlesToUpdate = [];
    elementsToUpdate.forEach((handle) => {
      const element = this.j.get(handle);
      if (element) {
        const node = this.m.get(element);
        if (node && (!node.parent || !elementsToUpdate.has(node.parent.item.handle))) {
          handlesToUpdate.push(handle);
        }
      }
    });
    return handlesToUpdate;
  }
  bb(itemHandles) {
    const itemsToRefresh = {};
    return Promise.all(itemHandles.map((treeItemHandle) => this.cb(treeItemHandle).then((node) => {
      if (node) {
        itemsToRefresh[treeItemHandle] = node.item;
      }
    }))).then(() => Object.keys(itemsToRefresh).length ? this.J.$refresh(this.I, itemsToRefresh) : void 0);
  }
  cb(treeItemHandle) {
    const extElement = this.getExtensionElement(treeItemHandle);
    if (extElement) {
      const existing = this.m.get(extElement);
      if (existing) {
        this.rb(extElement);
        return $Nh(() => this.f.getTreeItem(extElement)).then((extTreeItem) => {
          if (extTreeItem) {
            const newNode = this.ib(extElement, extTreeItem, existing.parent);
            this.pb(extElement, newNode, existing, existing.parent);
            existing.dispose();
            return newNode;
          }
          return null;
        });
      }
    }
    return Promise.resolve(null);
  }
  db(element, extTreeItem, parentNode) {
    const node = this.ib(element, extTreeItem, parentNode);
    if (extTreeItem.id && this.j.has(node.item.handle)) {
      throw new Error(localize(2769, null, extTreeItem.id));
    }
    this.ob(element, node);
    this.qb(node, parentNode);
    return node;
  }
  eb(tooltip) {
    if ($4T.isMarkdownString(tooltip)) {
      return MarkdownString.from(tooltip);
    }
    return tooltip;
  }
  fb(disposable, command) {
    return command ? { ...this.L.toInternal(command, disposable), originalId: command.command } : void 0;
  }
  gb(extensionTreeItem) {
    if (extensionTreeItem.checkboxState === void 0) {
      return void 0;
    }
    let checkboxState;
    let tooltip = void 0;
    let accessibilityInformation = void 0;
    if (typeof extensionTreeItem.checkboxState === "number") {
      checkboxState = extensionTreeItem.checkboxState;
    } else {
      checkboxState = extensionTreeItem.checkboxState.state;
      tooltip = extensionTreeItem.checkboxState.tooltip;
      accessibilityInformation = extensionTreeItem.checkboxState.accessibilityInformation;
    }
    return { isChecked: checkboxState === TreeItemCheckboxState.Checked, tooltip, accessibilityInformation };
  }
  hb(extensionTreeItem) {
    if (!$rU.isTreeItem(extensionTreeItem, this.N)) {
      throw new Error(`Extension ${this.N.identifier.value} has provided an invalid tree item.`);
    }
  }
  ib(element, extensionTreeItem, parent) {
    this.hb(extensionTreeItem);
    const disposableStore = this.B(new $2c());
    const handle = this.kb(element, extensionTreeItem, parent);
    const icon = this.lb(extensionTreeItem);
    const item = {
      handle,
      parentHandle: parent ? parent.item.handle : void 0,
      label: toTreeItemLabel(extensionTreeItem.label, this.N),
      description: extensionTreeItem.description,
      resourceUri: extensionTreeItem.resourceUri,
      tooltip: this.eb(extensionTreeItem.tooltip),
      command: this.fb(disposableStore, extensionTreeItem.command),
      contextValue: extensionTreeItem.contextValue,
      icon,
      iconDark: this.mb(extensionTreeItem) || icon,
      themeIcon: this.jb(extensionTreeItem),
      collapsibleState: $Ig(extensionTreeItem.collapsibleState) ? TreeItemCollapsibleState.None : extensionTreeItem.collapsibleState,
      accessibilityInformation: extensionTreeItem.accessibilityInformation,
      checkbox: this.gb(extensionTreeItem)
    };
    return {
      item,
      extensionItem: extensionTreeItem,
      parent,
      children: void 0,
      disposableStore,
      dispose() {
        disposableStore.dispose();
      }
    };
  }
  jb(extensionTreeItem) {
    return extensionTreeItem.iconPath instanceof $AU ? extensionTreeItem.iconPath : void 0;
  }
  kb(element, { id: id2, label, resourceUri }, parent, returnFirst) {
    if (id2) {
      return `${_ExtHostTreeView.b}/${id2}`;
    }
    const treeItemLabel = toTreeItemLabel(label, this.N);
    const prefix = parent ? parent.item.handle : _ExtHostTreeView.a;
    let elementId = treeItemLabel ? treeItemLabel.label : resourceUri ? $sh(resourceUri) : "";
    elementId = elementId.indexOf("/") !== -1 ? elementId.replace("/", "//") : elementId;
    const existingHandle = this.m.has(element) ? this.m.get(element).item.handle : void 0;
    const childrenNodes = this.X(parent) || [];
    let handle;
    let counter = 0;
    do {
      handle = `${prefix}/${counter}:${elementId}`;
      if (returnFirst || !this.j.has(handle) || existingHandle === handle) {
        break;
      }
      counter++;
    } while (counter <= childrenNodes.length);
    return handle;
  }
  lb(extensionTreeItem) {
    if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof $AU)) {
      if (typeof extensionTreeItem.iconPath === "string" || URI.isUri(extensionTreeItem.iconPath)) {
        return this.nb(extensionTreeItem.iconPath);
      }
      return this.nb(extensionTreeItem.iconPath.light);
    }
    return void 0;
  }
  mb(extensionTreeItem) {
    if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof $AU) && extensionTreeItem.iconPath.dark) {
      return this.nb(extensionTreeItem.iconPath.dark);
    }
    return void 0;
  }
  nb(iconPath) {
    if (URI.isUri(iconPath)) {
      return iconPath;
    }
    return URI.file(iconPath);
  }
  ob(element, node) {
    this.j.set(node.item.handle, element);
    this.m.set(element, node);
  }
  pb(element, newNode, existing, parentNode) {
    this.j.delete(newNode.item.handle);
    this.m.delete(element);
    if (newNode.item.handle !== existing.item.handle) {
      this.j.delete(existing.item.handle);
    }
    this.ob(element, newNode);
    const childrenNodes = this.X(parentNode) || [];
    const childNode = childrenNodes.filter((c) => c.item.handle === existing.item.handle)[0];
    if (childNode) {
      childrenNodes.splice(childrenNodes.indexOf(childNode), 1, newNode);
    }
  }
  qb(node, parentNode) {
    if (parentNode) {
      if (!parentNode.children) {
        parentNode.children = [];
      }
      parentNode.children.push(node);
    } else {
      if (!this.h) {
        this.h = [];
      }
      this.h.push(node);
    }
  }
  rb(parentElement) {
    if (parentElement) {
      const node = this.m.get(parentElement);
      if (node) {
        if (node.children) {
          for (const child of node.children) {
            const childElement = this.j.get(child.item.handle);
            if (childElement) {
              this.sb(childElement);
            }
          }
        }
        node.children = void 0;
      }
    } else {
      this.tb();
    }
  }
  sb(element) {
    const node = this.m.get(element);
    if (node) {
      if (node.children) {
        for (const child of node.children) {
          const childElement = this.j.get(child.item.handle);
          if (childElement) {
            this.sb(childElement);
          }
        }
      }
      this.m.delete(element);
      this.j.delete(node.item.handle);
      node.dispose();
    }
  }
  tb() {
    this.h = void 0;
    this.j.clear();
    this.m.forEach((node) => node.dispose());
    this.m.clear();
  }
  dispose() {
    super.dispose();
    this.Z.dispose();
    this.tb();
    this.J.$disposeTree(this.I);
  }
};

// out-build/vs/workbench/api/common/extHostUriOpener.js
var $Uyc = class _$Uyc {
  static {
    this.a = /* @__PURE__ */ new Set([Schemas.http, Schemas.https]);
  }
  constructor(mainContext) {
    this.c = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadUriOpeners);
  }
  registerExternalUriOpener(extensionId, id2, opener, metadata) {
    if (this.c.has(id2)) {
      throw new Error(`Opener with id '${id2}' already registered`);
    }
    const invalidScheme = metadata.schemes.find((scheme) => !_$Uyc.a.has(scheme));
    if (invalidScheme) {
      throw new Error(`Scheme '${invalidScheme}' is not supported. Only http and https are currently supported.`);
    }
    this.c.set(id2, opener);
    this.b.$registerUriOpener(id2, metadata.schemes, extensionId, metadata.label);
    return $1c(() => {
      this.c.delete(id2);
      this.b.$unregisterUriOpener(id2);
    });
  }
  async $canOpenUri(id2, uriComponents, token) {
    const opener = this.c.get(id2);
    if (!opener) {
      throw new Error(`Unknown opener with id: ${id2}`);
    }
    const uri = URI.revive(uriComponents);
    return opener.canOpenExternalUri(uri, token);
  }
  async $openUri(id2, context, token) {
    const opener = this.c.get(id2);
    if (!opener) {
      throw new Error(`Unknown opener id: '${id2}'`);
    }
    return opener.openExternalUri(URI.revive(context.resolvedUri), {
      sourceUri: URI.revive(context.sourceUri)
    }, token);
  }
};

// out-build/vs/workbench/api/common/extHostUrls.js
var $Vyc = class _$Vyc {
  static {
    this.a = 0;
  }
  constructor(mainContext) {
    this.c = new $6z();
    this.d = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadUrls);
  }
  registerUriHandler(extension, handler) {
    const extensionId = extension.identifier;
    if (this.c.has(extensionId)) {
      throw new Error(`Protocol handler already registered for extension ${extensionId}`);
    }
    const handle = _$Vyc.a++;
    this.c.add(extensionId);
    this.d.set(handle, handler);
    this.b.$registerUriHandler(handle, extensionId, extension.displayName || extension.name);
    return $1c(() => {
      this.c.delete(extensionId);
      this.d.delete(handle);
      this.b.$unregisterUriHandler(handle);
    });
  }
  $handleExternalUri(handle, uri) {
    const handler = this.d.get(handle);
    if (!handler) {
      return Promise.resolve(void 0);
    }
    try {
      handler.handleUri(URI.revive(uri));
    } catch (err) {
      $gb(err);
    }
    return Promise.resolve(void 0);
  }
  async createAppUri(uri) {
    return URI.revive(await this.b.$createAppUri(uri));
  }
};

// out-build/vs/workbench/api/common/extHostWebviewPanels.js
var ExtHostWebviewPanel = class extends $3c {
  #handle;
  #proxy;
  #viewType;
  #webview;
  #options;
  #title;
  #iconPath;
  #viewColumn;
  #visible;
  #active;
  #isDisposed;
  #onDidDispose;
  #onDidChangeViewState;
  constructor(handle, proxy, webview, params) {
    super();
    this.#viewColumn = void 0;
    this.#visible = true;
    this.#isDisposed = false;
    this.#onDidDispose = this.B(new $ze());
    this.onDidDispose = this.#onDidDispose.event;
    this.#onDidChangeViewState = this.B(new $ze());
    this.onDidChangeViewState = this.#onDidChangeViewState.event;
    this.#handle = handle;
    this.#proxy = proxy;
    this.#webview = webview;
    this.#viewType = params.viewType;
    this.#options = params.panelOptions;
    this.#viewColumn = params.viewColumn;
    this.#title = params.title;
    this.#active = params.active;
  }
  dispose() {
    if (this.#isDisposed) {
      return;
    }
    this.#isDisposed = true;
    this.#onDidDispose.fire();
    this.#proxy.$disposeWebview(this.#handle);
    this.#webview.dispose();
    super.dispose();
  }
  get webview() {
    this.c();
    return this.#webview;
  }
  get viewType() {
    this.c();
    return this.#viewType;
  }
  get title() {
    this.c();
    return this.#title;
  }
  set title(value) {
    this.c();
    if (this.#title !== value) {
      this.#title = value;
      this.#proxy.$setTitle(this.#handle, value);
    }
  }
  get iconPath() {
    this.c();
    return this.#iconPath;
  }
  set iconPath(value) {
    this.c();
    if (this.#iconPath !== value) {
      this.#iconPath = value;
      this.#proxy.$setIconPath(this.#handle, URI.isUri(value) ? { light: value, dark: value } : value);
    }
  }
  get options() {
    return this.#options;
  }
  get viewColumn() {
    this.c();
    if (typeof this.#viewColumn === "number" && this.#viewColumn < 0) {
      return void 0;
    }
    return this.#viewColumn;
  }
  get active() {
    this.c();
    return this.#active;
  }
  get visible() {
    this.c();
    return this.#visible;
  }
  _updateViewState(newState) {
    if (this.#isDisposed) {
      return;
    }
    if (this.active !== newState.active || this.visible !== newState.visible || this.viewColumn !== newState.viewColumn) {
      this.#active = newState.active;
      this.#visible = newState.visible;
      this.#viewColumn = newState.viewColumn;
      this.#onDidChangeViewState.fire({ webviewPanel: this });
    }
  }
  reveal(viewColumn, preserveFocus) {
    this.c();
    this.#proxy.$reveal(this.#handle, {
      viewColumn: typeof viewColumn === "undefined" ? void 0 : ViewColumn2.from(viewColumn),
      preserveFocus: !!preserveFocus
    });
  }
  c() {
    if (this.#isDisposed) {
      throw new Error("Webview is disposed");
    }
  }
};
var $kxc = class _$kxc extends $3c {
  static c() {
    return $ps();
  }
  constructor(mainContext, j, m) {
    super();
    this.j = j;
    this.m = m;
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.f = mainContext.getProxy($xT.MainThreadWebviewPanels);
  }
  dispose() {
    super.dispose();
    this.g.forEach((value) => value.dispose());
    this.g.clear();
  }
  createWebviewPanel(extension, viewType, title, showOptions, options2 = {}) {
    const viewColumn = typeof showOptions === "object" ? showOptions.viewColumn : showOptions;
    const webviewShowOptions = {
      viewColumn: ViewColumn2.from(viewColumn),
      preserveFocus: typeof showOptions === "object" && !!showOptions.preserveFocus
    };
    const serializeBuffersForPostMessage = $gxc(extension);
    const handle = _$kxc.c();
    this.f.$createWebviewPanel($ixc(extension), handle, viewType, {
      title,
      panelOptions: serializeWebviewPanelOptions(options2),
      webviewOptions: $jxc(extension, this.m, options2),
      serializeBuffersForPostMessage
    }, webviewShowOptions);
    const webview = this.j.createNewWebview(handle, options2, extension);
    const panel = this.createNewWebviewPanel(handle, viewType, title, viewColumn, options2, webview, true);
    return panel;
  }
  $onDidChangeWebviewPanelViewStates(newStates) {
    const handles = Object.keys(newStates);
    handles.sort((a, b) => {
      const stateA = newStates[a];
      const stateB = newStates[b];
      if (stateA.active) {
        return 1;
      }
      if (stateB.active) {
        return -1;
      }
      return +stateA.visible - +stateB.visible;
    });
    for (const handle of handles) {
      const panel = this.getWebviewPanel(handle);
      if (!panel) {
        continue;
      }
      const newState = newStates[handle];
      panel._updateViewState({
        active: newState.active,
        visible: newState.visible,
        viewColumn: ViewColumn2.to(newState.position)
      });
    }
  }
  async $onDidDisposeWebviewPanel(handle) {
    const panel = this.getWebviewPanel(handle);
    panel?.dispose();
    this.g.delete(handle);
    this.j.deleteWebview(handle);
  }
  registerWebviewPanelSerializer(extension, viewType, serializer) {
    if (this.h.has(viewType)) {
      throw new Error(`Serializer for '${viewType}' already registered`);
    }
    this.h.set(viewType, { serializer, extension });
    this.f.$registerSerializer(viewType, {
      serializeBuffersForPostMessage: $gxc(extension)
    });
    return new $zT(() => {
      this.h.delete(viewType);
      this.f.$unregisterSerializer(viewType);
    });
  }
  async $deserializeWebviewPanel(webviewHandle, viewType, initData, position) {
    const entry = this.h.get(viewType);
    if (!entry) {
      throw new Error(`No serializer found for '${viewType}'`);
    }
    const { serializer, extension } = entry;
    const webview = this.j.createNewWebview(webviewHandle, initData.webviewOptions, extension);
    const revivedPanel = this.createNewWebviewPanel(webviewHandle, viewType, initData.title, position, initData.panelOptions, webview, initData.active);
    await serializer.deserializeWebviewPanel(revivedPanel, initData.state);
  }
  createNewWebviewPanel(webviewHandle, viewType, title, position, options2, webview, active) {
    const panel = new ExtHostWebviewPanel(webviewHandle, this.f, webview, { viewType, title, viewColumn: position, panelOptions: options2, active });
    this.g.set(webviewHandle, panel);
    return panel;
  }
  getWebviewPanel(handle) {
    return this.g.get(handle);
  }
};
function serializeWebviewPanelOptions(options2) {
  return {
    enableFindWidget: options2.enableFindWidget,
    retainContextWhenHidden: options2.retainContextWhenHidden
  };
}

// out-build/vs/workbench/api/common/extHostWebviewView.js
var ExtHostWebviewView = class extends $3c {
  #handle;
  #proxy;
  #viewType;
  #webview;
  #isDisposed;
  #isVisible;
  #title;
  #description;
  #badge;
  constructor(handle, proxy, viewType, title, webview, isVisible) {
    super();
    this.#isDisposed = false;
    this.#onDidChangeVisibility = this.B(new $ze());
    this.onDidChangeVisibility = this.#onDidChangeVisibility.event;
    this.#onDidDispose = this.B(new $ze());
    this.onDidDispose = this.#onDidDispose.event;
    this.#viewType = viewType;
    this.#title = title;
    this.#handle = handle;
    this.#proxy = proxy;
    this.#webview = webview;
    this.#isVisible = isVisible;
  }
  dispose() {
    if (this.#isDisposed) {
      return;
    }
    this.#isDisposed = true;
    this.#onDidDispose.fire();
    this.#webview.dispose();
    super.dispose();
  }
  #onDidChangeVisibility;
  #onDidDispose;
  get title() {
    this.a();
    return this.#title;
  }
  set title(value) {
    this.a();
    if (this.#title !== value) {
      this.#title = value;
      this.#proxy.$setWebviewViewTitle(this.#handle, value);
    }
  }
  get description() {
    this.a();
    return this.#description;
  }
  set description(value) {
    this.a();
    if (this.#description !== value) {
      this.#description = value;
      this.#proxy.$setWebviewViewDescription(this.#handle, value);
    }
  }
  get visible() {
    return this.#isVisible;
  }
  get webview() {
    return this.#webview;
  }
  get viewType() {
    return this.#viewType;
  }
  /* internal */
  _setVisible(visible) {
    if (visible === this.#isVisible || this.#isDisposed) {
      return;
    }
    this.#isVisible = visible;
    this.#onDidChangeVisibility.fire();
  }
  get badge() {
    this.a();
    return this.#badge;
  }
  set badge(badge) {
    this.a();
    if (badge?.value === this.#badge?.value && badge?.tooltip === this.#badge?.tooltip) {
      return;
    }
    this.#badge = ViewBadge2.from(badge);
    this.#proxy.$setWebviewViewBadge(this.#handle, badge);
  }
  show(preserveFocus) {
    this.a();
    this.#proxy.$show(this.#handle, !!preserveFocus);
  }
  a() {
    if (this.#isDisposed) {
      throw new Error("Webview is disposed");
    }
  }
};
var $Wyc = class {
  constructor(mainContext, d) {
    this.d = d;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.a = mainContext.getProxy($xT.MainThreadWebviewViews);
  }
  registerWebviewViewProvider(extension, viewType, provider, webviewOptions) {
    if (this.b.has(viewType)) {
      throw new Error(`View provider for '${viewType}' already registered`);
    }
    this.b.set(viewType, { provider, extension });
    this.a.$registerWebviewViewProvider($ixc(extension), viewType, {
      retainContextWhenHidden: webviewOptions?.retainContextWhenHidden,
      serializeBuffersForPostMessage: $gxc(extension)
    });
    return new $zT(() => {
      this.b.delete(viewType);
      this.a.$unregisterWebviewViewProvider(viewType);
    });
  }
  async $resolveWebviewView(webviewHandle, viewType, title, state, cancellation) {
    const entry = this.b.get(viewType);
    if (!entry) {
      throw new Error(`No view provider found for '${viewType}'`);
    }
    const { provider, extension } = entry;
    const webview = this.d.createNewWebview(webviewHandle, {
      /* todo */
    }, extension);
    const revivedView = new ExtHostWebviewView(webviewHandle, this.a, viewType, title, webview, true);
    this.c.set(webviewHandle, revivedView);
    await provider.resolveWebviewView(revivedView, { state }, cancellation);
  }
  async $onDidChangeWebviewViewVisibility(webviewHandle, visible) {
    const webviewView = this.e(webviewHandle);
    webviewView._setVisible(visible);
  }
  async $disposeWebviewView(webviewHandle) {
    const webviewView = this.e(webviewHandle);
    this.c.delete(webviewHandle);
    webviewView.dispose();
    this.d.deleteWebview(webviewHandle);
  }
  e(handle) {
    const entry = this.c.get(handle);
    if (!entry) {
      throw new Error("No webview found");
    }
    return entry;
  }
};

// out-build/vs/workbench/contrib/debug/common/debug.js
var $3Q = new $nn("debugType", void 0, { type: "string", description: localize(6103, null) });
var $4Q = new $nn("debugConfigurationType", void 0, { type: "string", description: localize(6104, null) });
var $5Q = new $nn("debugState", "inactive", { type: "string", description: localize(6105, null) });
var $6Q = "debugUx";
var $7Q = new $nn($6Q, "default", { type: "string", description: localize(6106, null) });
var $8Q = new $nn("hasDebugged", false, { type: "boolean", description: localize(6107, null) });
var $9Q = new $nn("inDebugMode", false, { type: "boolean", description: localize(6108, null) });
var $0Q = new $nn("inDebugRepl", false, { type: "boolean", description: localize(6109, null) });
var $$Q = new $nn("breakpointWidgetVisible", false, { type: "boolean", description: localize(6110, null) });
var $_Q = new $nn("inBreakpointWidget", false, { type: "boolean", description: localize(6111, null) });
var $aR = new $nn("breakpointsFocused", true, { type: "boolean", description: localize(6112, null) });
var $bR = new $nn("watchExpressionsFocused", true, { type: "boolean", description: localize(6113, null) });
var $cR = new $nn("watchExpressionsExist", false, { type: "boolean", description: localize(6114, null) });
var $dR = new $nn("variablesFocused", true, { type: "boolean", description: localize(6115, null) });
var $eR = new $nn("expressionSelected", false, { type: "boolean", description: localize(6116, null) });
var $fR = new $nn("breakpointInputFocused", false, { type: "boolean", description: localize(6117, null) });
var $gR = new $nn("callStackItemType", void 0, { type: "string", description: localize(6118, null) });
var $hR = new $nn("callStackSessionIsAttach", false, { type: "boolean", description: localize(6119, null) });
var $iR = new $nn("callStackItemStopped", false, { type: "boolean", description: localize(6120, null) });
var $jR = new $nn("callStackSessionHasOneThread", false, { type: "boolean", description: localize(6121, null) });
var $kR = new $nn("callStackFocused", true, { type: "boolean", description: localize(6122, null) });
var $lR = new $nn("watchItemType", void 0, { type: "string", description: localize(6123, null) });
var $mR = new $nn("canViewMemory", void 0, { type: "boolean", description: localize(6124, null) });
var $nR = new $nn("breakpointItemType", void 0, { type: "string", description: localize(6125, null) });
var $oR = new $nn("breakpointItemBytes", void 0, { type: "boolean", description: localize(6126, null) });
var $pR = new $nn("breakpointHasModes", false, { type: "boolean", description: localize(6127, null) });
var $qR = new $nn("breakpointSupportsCondition", false, { type: "boolean", description: localize(6128, null) });
var $rR = new $nn("loadedScriptsSupported", false, { type: "boolean", description: localize(6129, null) });
var $sR = new $nn("loadedScriptsItemType", void 0, { type: "string", description: localize(6130, null) });
var $tR = new $nn("focusedSessionIsAttach", false, { type: "boolean", description: localize(6131, null) });
var $uR = new $nn("focusedSessionIsNoDebug", false, { type: "boolean", description: localize(6132, null) });
var $vR = new $nn("stepBackSupported", false, { type: "boolean", description: localize(6133, null) });
var $wR = new $nn("restartFrameSupported", false, { type: "boolean", description: localize(6134, null) });
var $xR = new $nn("stackFrameSupportsRestart", false, { type: "boolean", description: localize(6135, null) });
var $yR = new $nn("jumpToCursorSupported", false, { type: "boolean", description: localize(6136, null) });
var $zR = new $nn("stepIntoTargetsSupported", false, { type: "boolean", description: localize(6137, null) });
var $AR = new $nn("breakpointsExist", false, { type: "boolean", description: localize(6138, null) });
var $BR = new $nn("debuggersAvailable", false, { type: "boolean", description: localize(6139, null) });
var $CR = new $nn("debugExtensionAvailable", true, { type: "boolean", description: localize(6140, null) });
var $DR = new $nn("debugProtocolVariableMenuContext", void 0, { type: "string", description: localize(6141, null) });
var $ER = new $nn("debugSetVariableSupported", false, { type: "boolean", description: localize(6142, null) });
var $FR = new $nn("debugSetDataBreakpointAddressSupported", false, { type: "boolean", description: localize(6143, null) });
var $GR = new $nn("debugSetExpressionSupported", false, { type: "boolean", description: localize(6144, null) });
var $HR = new $nn("breakWhenValueChangesSupported", false, { type: "boolean", description: localize(6145, null) });
var $IR = new $nn("breakWhenValueIsAccessedSupported", false, { type: "boolean", description: localize(6146, null) });
var $JR = new $nn("breakWhenValueIsReadSupported", false, { type: "boolean", description: localize(6147, null) });
var $KR = new $nn("terminateDebuggeeSupported", false, { type: "boolean", description: localize(6148, null) });
var $LR = new $nn("suspendDebuggeeSupported", false, { type: "boolean", description: localize(6149, null) });
var $MR = new $nn("variableEvaluateNamePresent", false, { type: "boolean", description: localize(6150, null) });
var $NR = new $nn("variableIsReadonly", false, { type: "boolean", description: localize(6151, null) });
var $OR = new $nn("variableValue", false, { type: "string", description: localize(6152, null) });
var $PR = new $nn("variableType", false, { type: "string", description: localize(6153, null) });
var $QR = new $nn("variableInterfaces", false, { type: "array", description: localize(6154, null) });
var $RR = new $nn("variableName", false, { type: "string", description: localize(6155, null) });
var $SR = new $nn("variableLanguage", false, { type: "string", description: localize(6156, null) });
var $TR = new $nn("variableExtensionId", false, { type: "string", description: localize(6157, null) });
var $UR = new $nn("exceptionWidgetVisible", false, { type: "boolean", description: localize(6158, null) });
var $VR = new $nn("multiSessionRepl", false, { type: "boolean", description: localize(6159, null) });
var $WR = new $nn("multiSessionDebug", false, { type: "boolean", description: localize(6160, null) });
var $XR = new $nn("disassembleRequestSupported", false, { type: "boolean", description: localize(6161, null) });
var $YR = new $nn("disassemblyViewFocus", false, { type: "boolean", description: localize(6162, null) });
var $ZR = new $nn("languageSupportsDisassembleRequest", false, { type: "boolean", description: localize(6163, null) });
var $1R = new $nn("focusedStackFrameHasInstructionReference", false, { type: "boolean", description: localize(6164, null) });
var $6R = {
  enum: ["neverOpen", "openOnSessionStart", "openOnFirstSessionStart"],
  default: "openOnFirstSessionStart",
  description: localize(6166, null)
};
var State3;
(function(State4) {
  State4[State4["Inactive"] = 0] = "Inactive";
  State4[State4["Initializing"] = 1] = "Initializing";
  State4[State4["Stopped"] = 2] = "Stopped";
  State4[State4["Running"] = 3] = "Running";
})(State3 || (State3 = {}));
var MemoryRangeType;
(function(MemoryRangeType2) {
  MemoryRangeType2[MemoryRangeType2["Valid"] = 0] = "Valid";
  MemoryRangeType2[MemoryRangeType2["Unreadable"] = 1] = "Unreadable";
  MemoryRangeType2[MemoryRangeType2["Error"] = 2] = "Error";
})(MemoryRangeType || (MemoryRangeType = {}));
var DataBreakpointSetType;
(function(DataBreakpointSetType2) {
  DataBreakpointSetType2[DataBreakpointSetType2["Variable"] = 0] = "Variable";
  DataBreakpointSetType2[DataBreakpointSetType2["Address"] = 1] = "Address";
})(DataBreakpointSetType || (DataBreakpointSetType = {}));
var DebugConfigurationProviderTriggerKind;
(function(DebugConfigurationProviderTriggerKind2) {
  DebugConfigurationProviderTriggerKind2[DebugConfigurationProviderTriggerKind2["Initial"] = 1] = "Initial";
  DebugConfigurationProviderTriggerKind2[DebugConfigurationProviderTriggerKind2["Dynamic"] = 2] = "Dynamic";
})(DebugConfigurationProviderTriggerKind || (DebugConfigurationProviderTriggerKind = {}));
var DebuggerString;
(function(DebuggerString2) {
  DebuggerString2["UnverifiedBreakpoints"] = "unverifiedBreakpoints";
})(DebuggerString || (DebuggerString = {}));
var $0R = $Qk("debugService");
var BreakpointWidgetContext;
(function(BreakpointWidgetContext2) {
  BreakpointWidgetContext2[BreakpointWidgetContext2["CONDITION"] = 0] = "CONDITION";
  BreakpointWidgetContext2[BreakpointWidgetContext2["HIT_COUNT"] = 1] = "HIT_COUNT";
  BreakpointWidgetContext2[BreakpointWidgetContext2["LOG_MESSAGE"] = 2] = "LOG_MESSAGE";
  BreakpointWidgetContext2[BreakpointWidgetContext2["TRIGGER_POINT"] = 3] = "TRIGGER_POINT";
})(BreakpointWidgetContext || (BreakpointWidgetContext = {}));
var DebugVisualizationType;
(function(DebugVisualizationType2) {
  DebugVisualizationType2[DebugVisualizationType2["Command"] = 0] = "Command";
  DebugVisualizationType2[DebugVisualizationType2["Tree"] = 1] = "Tree";
})(DebugVisualizationType || (DebugVisualizationType = {}));
var DebugTreeItemCollapsibleState;
(function(DebugTreeItemCollapsibleState2) {
  DebugTreeItemCollapsibleState2[DebugTreeItemCollapsibleState2["None"] = 0] = "None";
  DebugTreeItemCollapsibleState2[DebugTreeItemCollapsibleState2["Collapsed"] = 1] = "Collapsed";
  DebugTreeItemCollapsibleState2[DebugTreeItemCollapsibleState2["Expanded"] = 2] = "Expanded";
})(DebugTreeItemCollapsibleState || (DebugTreeItemCollapsibleState = {}));
var IDebugVisualizationTreeItem;
(function(IDebugVisualizationTreeItem2) {
  IDebugVisualizationTreeItem2.deserialize = (v) => v;
  IDebugVisualizationTreeItem2.serialize = (item) => item;
})(IDebugVisualizationTreeItem || (IDebugVisualizationTreeItem = {}));
var IDebugVisualization;
(function(IDebugVisualization2) {
  IDebugVisualization2.deserialize = (v) => ({
    id: v.id,
    name: v.name,
    iconPath: v.iconPath && { light: URI.revive(v.iconPath.light), dark: URI.revive(v.iconPath.dark) },
    iconClass: v.iconClass,
    visualization: v.visualization
  });
  IDebugVisualization2.serialize = (visualizer) => visualizer;
})(IDebugVisualization || (IDebugVisualization = {}));

// out-build/vs/workbench/api/common/extHostCodeMapper.js
var $Zyc = class _$Zyc {
  static {
    this.a = 0;
  }
  constructor(mainContext) {
    this.c = /* @__PURE__ */ new Map();
    this.b = mainContext.getProxy($xT.MainThreadCodeMapper);
  }
  async $mapCode(handle, internalRequest, token) {
    const provider = this.c.get(handle);
    if (!provider) {
      throw new Error(`Received request to map code for unknown provider handle ${handle}`);
    }
    const stream = {
      textEdit: (target, edits) => {
        edits = Array.isArray(edits) ? edits : [edits];
        this.b.$handleProgress(internalRequest.requestId, {
          uri: target,
          edits: edits.map(TextEdit.from)
        });
      }
    };
    const request = {
      codeBlocks: internalRequest.codeBlocks.map((block2) => {
        return {
          code: block2.code,
          resource: URI.revive(block2.resource),
          markdownBeforeBlock: block2.markdownBeforeBlock
        };
      }),
      conversation: internalRequest.conversation.map((item) => {
        if (item.type === "request") {
          return {
            type: "request",
            message: item.message
          };
        } else {
          return {
            type: "response",
            message: item.message,
            result: item.result ? ChatAgentResult.to(item.result) : void 0,
            references: item.references?.map(DocumentContextItem.to)
          };
        }
      })
    };
    const result = await provider.provideMappedEdits(request, stream, token);
    return result ?? null;
  }
  registerMappedEditsProvider(extension, provider) {
    const handle = _$Zyc.a++;
    this.b.$registerCodeMapperProvider(handle);
    this.c.set(handle, provider);
    return {
      dispose: () => {
        return this.b.$unregisterCodeMapperProvider(handle);
      }
    };
  }
};

// out-build/vs/workbench/api/common/extHost.api.impl.js
function $1yc(accessor) {
  const initData = accessor.get($wW);
  const extHostFileSystemInfo = accessor.get($Pwc);
  const extHostConsumerFileSystem = accessor.get($cxc);
  const extensionService = accessor.get($Lxc);
  const extHostWorkspace = accessor.get($0wc);
  const extHostTelemetry = accessor.get($AW);
  const extHostConfiguration = accessor.get($axc);
  const uriTransformer = accessor.get($7wc);
  const rpcProtocol = accessor.get($gW);
  const extHostStorage = accessor.get($vxc);
  const extensionStoragePaths = accessor.get($dxc);
  const extHostLoggerService = accessor.get($xn);
  const extHostLogService = accessor.get($wn);
  const extHostTunnelService = accessor.get($6Sb);
  const extHostApiDeprecation = accessor.get($Lwc);
  const extHostWindow = accessor.get($Yyc);
  const extHostSecretState = accessor.get($Dxc);
  const extHostEditorTabs = accessor.get($mxc);
  const extHostManagedSockets = accessor.get($Hxc);
  const extHostAuthentication = accessor.get($Vwc);
  const extHostLanguageModels = accessor.get($Ywc);
  rpcProtocol.set($yT.ExtHostFileSystemInfo, extHostFileSystemInfo);
  rpcProtocol.set($yT.ExtHostLogLevelServiceShape, extHostLoggerService);
  rpcProtocol.set($yT.ExtHostWorkspace, extHostWorkspace);
  rpcProtocol.set($yT.ExtHostConfiguration, extHostConfiguration);
  rpcProtocol.set($yT.ExtHostExtensionService, extensionService);
  rpcProtocol.set($yT.ExtHostStorage, extHostStorage);
  rpcProtocol.set($yT.ExtHostTunnelService, extHostTunnelService);
  rpcProtocol.set($yT.ExtHostWindow, extHostWindow);
  rpcProtocol.set($yT.ExtHostSecretState, extHostSecretState);
  rpcProtocol.set($yT.ExtHostTelemetry, extHostTelemetry);
  rpcProtocol.set($yT.ExtHostEditorTabs, extHostEditorTabs);
  rpcProtocol.set($yT.ExtHostManagedSockets, extHostManagedSockets);
  rpcProtocol.set($yT.ExtHostAuthentication, extHostAuthentication);
  rpcProtocol.set($yT.ExtHostChatProvider, extHostLanguageModels);
  const extHostDecorations = rpcProtocol.set($yT.ExtHostDecorations, accessor.get($2xc));
  const extHostDocumentsAndEditors = rpcProtocol.set($yT.ExtHostDocumentsAndEditors, accessor.get($rW));
  const extHostCommands = rpcProtocol.set($yT.ExtHostCommands, accessor.get($CW));
  const extHostTerminalService = rpcProtocol.set($yT.ExtHostTerminalService, accessor.get($yxc));
  const extHostTerminalShellIntegration = rpcProtocol.set($yT.ExtHostTerminalShellIntegration, accessor.get($Oyc));
  const extHostDebugService = rpcProtocol.set($yT.ExtHostDebugService, accessor.get($Vxc));
  const extHostSearch = rpcProtocol.set($yT.ExtHostSearch, accessor.get($kyc));
  const extHostTask = rpcProtocol.set($yT.ExtHostTask, accessor.get($Nyc));
  const extHostOutputService = rpcProtocol.set($yT.ExtHostOutputService, accessor.get($Ayc));
  const extHostLocalization = rpcProtocol.set($yT.ExtHostLocalization, accessor.get($Gxc));
  const extHostUrls = rpcProtocol.set($yT.ExtHostUrls, new $Vyc(rpcProtocol));
  const extHostDocuments = rpcProtocol.set($yT.ExtHostDocuments, new $Swc(rpcProtocol, extHostDocumentsAndEditors));
  const extHostDocumentContentProviders = rpcProtocol.set($yT.ExtHostDocumentContentProviders, new $4xc(rpcProtocol, extHostDocumentsAndEditors, extHostLogService));
  const extHostDocumentSaveParticipant = rpcProtocol.set($yT.ExtHostDocumentSaveParticipant, new $5xc(extHostLogService, extHostDocuments, rpcProtocol.getProxy($xT.MainThreadBulkEdits)));
  const extHostNotebook = rpcProtocol.set($yT.ExtHostNotebook, new $nyc(rpcProtocol, extHostCommands, extHostDocumentsAndEditors, extHostDocuments, extHostConsumerFileSystem, extHostSearch, extHostLogService));
  const extHostNotebookDocuments = rpcProtocol.set($yT.ExtHostNotebookDocuments, new $uyc(extHostNotebook));
  const extHostNotebookEditors = rpcProtocol.set($yT.ExtHostNotebookEditors, new $vyc(extHostLogService, extHostNotebook));
  const extHostNotebookKernels = rpcProtocol.set($yT.ExtHostNotebookKernels, new $wyc(rpcProtocol, initData, extHostNotebook, extHostCommands, extHostLogService));
  const extHostNotebookRenderers = rpcProtocol.set($yT.ExtHostNotebookRenderers, new $yyc(rpcProtocol, extHostNotebook));
  const extHostNotebookDocumentSaveParticipant = rpcProtocol.set($yT.ExtHostNotebookDocumentSaveParticipant, new $tyc(extHostLogService, extHostNotebook, rpcProtocol.getProxy($xT.MainThreadBulkEdits)));
  const extHostEditors = rpcProtocol.set($yT.ExtHostEditors, new $4wc(rpcProtocol, extHostDocumentsAndEditors));
  const extHostTreeViews = rpcProtocol.set($yT.ExtHostTreeViews, new $Tyc(rpcProtocol.getProxy($xT.MainThreadTreeViews), extHostCommands, extHostLogService));
  const extHostEditorInsets = rpcProtocol.set($yT.ExtHostEditorInsets, new $5wc(rpcProtocol.getProxy($xT.MainThreadEditorInsets), extHostEditors, initData.remote));
  const extHostDiagnostics = rpcProtocol.set($yT.ExtHostDiagnostics, new $Rwc(rpcProtocol, extHostLogService, extHostFileSystemInfo, extHostDocumentsAndEditors));
  const extHostLanguages = rpcProtocol.set($yT.ExtHostLanguages, new $ryc(rpcProtocol, extHostDocuments, extHostCommands.converter, uriTransformer));
  const extHostLanguageFeatures = rpcProtocol.set($yT.ExtHostLanguageFeatures, new $Twc(rpcProtocol, uriTransformer, extHostDocuments, extHostCommands, extHostDiagnostics, extHostLogService, extHostApiDeprecation, extHostTelemetry));
  const extHostCodeMapper = rpcProtocol.set($yT.ExtHostCodeMapper, new $Zyc(rpcProtocol));
  const extHostFileSystem = rpcProtocol.set($yT.ExtHostFileSystem, new $8xc(rpcProtocol, extHostLanguageFeatures));
  const extHostFileSystemEvent = rpcProtocol.set($yT.ExtHostFileSystemEventService, new $9xc(rpcProtocol, extHostLogService, extHostDocumentsAndEditors));
  const extHostQuickOpen = rpcProtocol.set($yT.ExtHostQuickOpen, $Eyc(rpcProtocol, extHostWorkspace, extHostCommands));
  const extHostSCM = rpcProtocol.set($yT.ExtHostSCM, new $Gyc(rpcProtocol, extHostCommands, extHostDocuments, extHostLogService));
  const extHostQuickDiff = rpcProtocol.set($yT.ExtHostQuickDiff, new $Dyc(rpcProtocol, uriTransformer));
  const extHostShare = rpcProtocol.set($yT.ExtHostShare, new $Hyc(rpcProtocol, uriTransformer));
  const extHostComment = rpcProtocol.set($yT.ExtHostComments, $6wc(rpcProtocol, extHostCommands, extHostDocuments));
  const extHostProgress = rpcProtocol.set($yT.ExtHostProgress, new $Cyc(rpcProtocol.getProxy($xT.MainThreadProgress)));
  const extHostLabelService = rpcProtocol.set($yT.ExtHostLabelService, new $pyc(rpcProtocol));
  const extHostTheming = rpcProtocol.set($yT.ExtHostTheming, new $Qyc(rpcProtocol));
  const extHostTimeline = rpcProtocol.set($yT.ExtHostTimeline, new $Syc(rpcProtocol, extHostCommands));
  const extHostWebviews = rpcProtocol.set($yT.ExtHostWebviews, new $hxc(rpcProtocol, initData.remote, extHostWorkspace, extHostLogService, extHostApiDeprecation));
  const extHostWebviewPanels = rpcProtocol.set($yT.ExtHostWebviewPanels, new $kxc(rpcProtocol, extHostWebviews, extHostWorkspace));
  const extHostCustomEditors = rpcProtocol.set($yT.ExtHostCustomEditors, new $lxc(rpcProtocol, extHostDocuments, extensionStoragePaths, extHostWebviews, extHostWebviewPanels));
  const extHostWebviewViews = rpcProtocol.set($yT.ExtHostWebviewViews, new $Wyc(rpcProtocol, extHostWebviews));
  const extHostTesting = rpcProtocol.set($yT.ExtHostTesting, accessor.get($Oxc));
  const extHostUriOpeners = rpcProtocol.set($yT.ExtHostUriOpeners, new $Uyc(rpcProtocol));
  const extHostProfileContentHandlers = rpcProtocol.set($yT.ExtHostProfileContentHandlers, new $Byc(rpcProtocol));
  rpcProtocol.set($yT.ExtHostInteractive, new $oyc(rpcProtocol, extHostNotebook, extHostDocumentsAndEditors, extHostCommands, extHostLogService));
  const extHostChatAgents2 = rpcProtocol.set($yT.ExtHostChatAgents2, new $1wc(rpcProtocol, extHostLogService, extHostCommands, extHostDocuments, extHostLanguageModels));
  const extHostChatVariables = rpcProtocol.set($yT.ExtHostChatVariables, new $2wc(rpcProtocol));
  const extHostLanguageModelTools = rpcProtocol.set($yT.ExtHostLanguageModelTools, new $qyc(rpcProtocol));
  const extHostAiRelatedInformation = rpcProtocol.set($yT.ExtHostAiRelatedInformation, new $Kwc(rpcProtocol));
  const extHostAiEmbeddingVector = rpcProtocol.set($yT.ExtHostAiEmbeddingVector, new $7xc(rpcProtocol));
  const extHostStatusBar = rpcProtocol.set($yT.ExtHostStatusBar, new $Kyc(rpcProtocol, extHostCommands.converter));
  const extHostSpeech = rpcProtocol.set($yT.ExtHostSpeech, new $Iyc(rpcProtocol));
  const extHostEmbeddings = rpcProtocol.set($yT.ExtHostEmbeddings, new $6xc(rpcProtocol));
  const expected = Object.values($yT);
  rpcProtocol.assertRegistered(expected);
  const extHostBulkEdits = new $Xwc(rpcProtocol, extHostDocumentsAndEditors);
  const extHostClipboard = new $3wc(rpcProtocol);
  const extHostMessageService = new $syc(rpcProtocol, extHostLogService);
  const extHostDialogs = new $3xc(rpcProtocol);
  $Uwc.register(extHostCommands);
  return function(extension, extensionInfo, configProvider) {
    function _asExtensionEvent(actual) {
      return (listener, thisArgs, disposables) => {
        const handle = actual((e) => {
          try {
            listener.call(thisArgs, e);
          } catch (err) {
            $hb(new Error(`[ExtensionListenerError] Extension '${extension.identifier.value}' FAILED to handle event: ${err.toString()}`, { cause: err }));
            extHostTelemetry.onExtensionError(extension.identifier, err);
          }
        });
        disposables?.push(handle);
        return handle;
      };
    }
    const checkSelector = function() {
      let done = !extension.isUnderDevelopment;
      function informOnce() {
        if (!done) {
          extHostLogService.info(`Extension '${extension.identifier.value}' uses a document selector without scheme. Learn more about this: https://go.microsoft.com/fwlink/?linkid=872305`);
          done = true;
        }
      }
      return function perform(selector) {
        if (Array.isArray(selector)) {
          selector.forEach(perform);
        } else if (typeof selector === "string") {
          informOnce();
        } else {
          const filter = selector;
          if (typeof filter.scheme === "undefined") {
            informOnce();
          }
          if (typeof filter.exclusive === "boolean") {
            $AN(extension, "documentFiltersExclusive");
          }
        }
        return selector;
      };
    }();
    const authentication = {
      getSession(providerId, scopes, options2) {
        if (typeof options2?.forceNewSession === "object" && options2.forceNewSession.learnMore) {
          $AN(extension, "authLearnMore");
        }
        return extHostAuthentication.getSession(extension, providerId, scopes, options2);
      },
      getAccounts(providerId) {
        return extHostAuthentication.getAccounts(providerId);
      },
      // TODO: remove this after GHPR and Codespaces move off of it
      async hasSession(providerId, scopes) {
        $AN(extension, "authSession");
        return !!await extHostAuthentication.getSession(extension, providerId, scopes, { silent: true });
      },
      get onDidChangeSessions() {
        return _asExtensionEvent(extHostAuthentication.getExtensionScopedSessionsEvent(extension.identifier.value));
      },
      registerAuthenticationProvider(id2, label, provider, options2) {
        return extHostAuthentication.registerAuthenticationProvider(id2, label, provider, options2);
      }
    };
    const commands = {
      registerCommand(id2, command, thisArgs) {
        return extHostCommands.registerCommand(true, id2, command, thisArgs, void 0, extension);
      },
      registerTextEditorCommand(id2, callback, thisArg) {
        return extHostCommands.registerCommand(true, id2, (...args2) => {
          const activeTextEditor = extHostEditors.getActiveTextEditor();
          if (!activeTextEditor) {
            extHostLogService.warn("Cannot execute " + id2 + " because there is no active text editor.");
            return void 0;
          }
          return activeTextEditor.edit((edit2) => {
            callback.apply(thisArg, [activeTextEditor, edit2, ...args2]);
          }).then((result) => {
            if (!result) {
              extHostLogService.warn("Edits from command " + id2 + " were not applied.");
            }
          }, (err) => {
            extHostLogService.warn("An error occurred while running command " + id2, err);
          });
        }, void 0, void 0, extension);
      },
      registerDiffInformationCommand: (id2, callback, thisArg) => {
        $AN(extension, "diffCommand");
        return extHostCommands.registerCommand(true, id2, async (...args2) => {
          const activeTextEditor = extHostDocumentsAndEditors.activeEditor(true);
          if (!activeTextEditor) {
            extHostLogService.warn("Cannot execute " + id2 + " because there is no active text editor.");
            return void 0;
          }
          const diff2 = await extHostEditors.getDiffInformation(activeTextEditor.id);
          callback.apply(thisArg, [diff2, ...args2]);
        }, void 0, void 0, extension);
      },
      executeCommand(id2, ...args2) {
        return extHostCommands.executeCommand(id2, ...args2);
      },
      getCommands(filterInternal = false) {
        return extHostCommands.getCommands(filterInternal);
      }
    };
    const env2 = {
      get machineId() {
        return initData.telemetryInfo.machineId;
      },
      get sessionId() {
        return initData.telemetryInfo.sessionId;
      },
      get language() {
        return initData.environment.appLanguage;
      },
      get appName() {
        return initData.environment.appName;
      },
      get appRoot() {
        return initData.environment.appRoot?.fsPath ?? "";
      },
      get appHost() {
        return initData.environment.appHost;
      },
      get uriScheme() {
        return initData.environment.appUriScheme;
      },
      get clipboard() {
        return extHostClipboard.value;
      },
      get shell() {
        return extHostTerminalService.getDefaultShell(false);
      },
      get onDidChangeShell() {
        return _asExtensionEvent(extHostTerminalService.onDidChangeShell);
      },
      get isTelemetryEnabled() {
        return extHostTelemetry.getTelemetryConfiguration();
      },
      get onDidChangeTelemetryEnabled() {
        return _asExtensionEvent(extHostTelemetry.onDidChangeTelemetryEnabled);
      },
      get telemetryConfiguration() {
        $AN(extension, "telemetry");
        return extHostTelemetry.getTelemetryDetails();
      },
      get onDidChangeTelemetryConfiguration() {
        $AN(extension, "telemetry");
        return _asExtensionEvent(extHostTelemetry.onDidChangeTelemetryConfiguration);
      },
      get isNewAppInstall() {
        return $zW(initData.telemetryInfo.firstSessionDate);
      },
      createTelemetryLogger(sender, options2) {
        $yW.validateSender(sender);
        return extHostTelemetry.instantiateLogger(extension, sender, options2);
      },
      openExternal(uri, options2) {
        return extHostWindow.openUri(uri, {
          allowTunneling: !!initData.remote.authority,
          allowContributedOpeners: options2?.allowContributedOpeners
        });
      },
      async asExternalUri(uri) {
        if (uri.scheme === initData.environment.appUriScheme) {
          return extHostUrls.createAppUri(uri);
        }
        try {
          return await extHostWindow.asExternalUri(uri, { allowTunneling: !!initData.remote.authority });
        } catch (err) {
          if ($0g(uri, Schemas.http) || $0g(uri, Schemas.https)) {
            return uri;
          }
          throw err;
        }
      },
      get remoteName() {
        return $9v(initData.remote.authority);
      },
      get remoteAuthority() {
        $AN(extension, "resolvers");
        return initData.remote.authority;
      },
      get uiKind() {
        return initData.uiKind;
      },
      get logLevel() {
        return extHostLogService.getLevel();
      },
      get onDidChangeLogLevel() {
        return _asExtensionEvent(extHostLogService.onDidChangeLogLevel);
      },
      get appQuality() {
        $AN(extension, "resolvers");
        return initData.quality;
      },
      get appCommit() {
        $AN(extension, "resolvers");
        return initData.commit;
      }
    };
    if (!initData.environment.extensionTestsLocationURI) {
      Object.freeze(env2);
    }
    const tests = {
      createTestController(provider, label, refreshHandler) {
        return extHostTesting.createTestController(extension, provider, label, refreshHandler);
      },
      createTestObserver() {
        $AN(extension, "testObserver");
        return extHostTesting.createTestObserver();
      },
      runTests(provider) {
        $AN(extension, "testObserver");
        return extHostTesting.runTests(provider);
      },
      registerTestFollowupProvider(provider) {
        $AN(extension, "testObserver");
        return extHostTesting.registerTestFollowupProvider(provider);
      },
      get onDidChangeTestResults() {
        $AN(extension, "testObserver");
        return _asExtensionEvent(extHostTesting.onResultsChanged);
      },
      get testResults() {
        $AN(extension, "testObserver");
        return extHostTesting.results;
      }
    };
    const extensionKind = initData.remote.isRemote ? ExtensionKind.Workspace : ExtensionKind.UI;
    const extensions = {
      getExtension(extensionId, includeFromDifferentExtensionHosts) {
        if (!$zN(extension, "extensionsAny")) {
          includeFromDifferentExtensionHosts = false;
        }
        const mine = extensionInfo.mine.getExtensionDescription(extensionId);
        if (mine) {
          return new $Mxc(extensionService, extension.identifier, mine, extensionKind, false);
        }
        if (includeFromDifferentExtensionHosts) {
          const foreign = extensionInfo.all.getExtensionDescription(extensionId);
          if (foreign) {
            return new $Mxc(extensionService, extension.identifier, foreign, extensionKind, true);
          }
        }
        return void 0;
      },
      get all() {
        const result = [];
        for (const desc of extensionInfo.mine.getAllExtensionDescriptions()) {
          result.push(new $Mxc(extensionService, extension.identifier, desc, extensionKind, false));
        }
        return result;
      },
      get allAcrossExtensionHosts() {
        $AN(extension, "extensionsAny");
        const local = new $6z(extensionInfo.mine.getAllExtensionDescriptions().map((desc) => desc.identifier));
        const result = [];
        for (const desc of extensionInfo.all.getAllExtensionDescriptions()) {
          const isFromDifferentExtensionHost = !local.has(desc.identifier);
          result.push(new $Mxc(extensionService, extension.identifier, desc, extensionKind, isFromDifferentExtensionHost));
        }
        return result;
      },
      get onDidChange() {
        if ($zN(extension, "extensionsAny")) {
          return _asExtensionEvent(Event.any(extensionInfo.mine.onDidChange, extensionInfo.all.onDidChange));
        }
        return _asExtensionEvent(extensionInfo.mine.onDidChange);
      }
    };
    const languages = {
      createDiagnosticCollection(name) {
        return extHostDiagnostics.createDiagnosticCollection(extension.identifier, name);
      },
      get onDidChangeDiagnostics() {
        return _asExtensionEvent(extHostDiagnostics.onDidChangeDiagnostics);
      },
      getDiagnostics: (resource) => {
        return extHostDiagnostics.getDiagnostics(resource);
      },
      getLanguages() {
        return extHostLanguages.getLanguages();
      },
      setTextDocumentLanguage(document2, languageId) {
        return extHostLanguages.changeLanguage(document2.uri, languageId);
      },
      match(selector, document2) {
        const interalSelector = LanguageSelector.from(selector);
        let notebook;
        if ($rE(interalSelector)) {
          notebook = extHostNotebook.notebookDocuments.find((value) => value.apiNotebook.getCells().find((c) => c.document === document2))?.apiNotebook;
        }
        return $qE(interalSelector, document2.uri, document2.languageId, true, notebook?.uri, notebook?.notebookType);
      },
      registerCodeActionsProvider(selector, provider, metadata) {
        return extHostLanguageFeatures.registerCodeActionProvider(extension, checkSelector(selector), provider, metadata);
      },
      registerDocumentPasteEditProvider(selector, provider, metadata) {
        $AN(extension, "documentPaste");
        return extHostLanguageFeatures.registerDocumentPasteEditProvider(extension, checkSelector(selector), provider, metadata);
      },
      registerCodeLensProvider(selector, provider) {
        return extHostLanguageFeatures.registerCodeLensProvider(extension, checkSelector(selector), provider);
      },
      registerDefinitionProvider(selector, provider) {
        return extHostLanguageFeatures.registerDefinitionProvider(extension, checkSelector(selector), provider);
      },
      registerDeclarationProvider(selector, provider) {
        return extHostLanguageFeatures.registerDeclarationProvider(extension, checkSelector(selector), provider);
      },
      registerImplementationProvider(selector, provider) {
        return extHostLanguageFeatures.registerImplementationProvider(extension, checkSelector(selector), provider);
      },
      registerTypeDefinitionProvider(selector, provider) {
        return extHostLanguageFeatures.registerTypeDefinitionProvider(extension, checkSelector(selector), provider);
      },
      registerHoverProvider(selector, provider) {
        return extHostLanguageFeatures.registerHoverProvider(extension, checkSelector(selector), provider, extension.identifier);
      },
      registerEvaluatableExpressionProvider(selector, provider) {
        return extHostLanguageFeatures.registerEvaluatableExpressionProvider(extension, checkSelector(selector), provider, extension.identifier);
      },
      registerInlineValuesProvider(selector, provider) {
        return extHostLanguageFeatures.registerInlineValuesProvider(extension, checkSelector(selector), provider, extension.identifier);
      },
      registerDocumentHighlightProvider(selector, provider) {
        return extHostLanguageFeatures.registerDocumentHighlightProvider(extension, checkSelector(selector), provider);
      },
      registerMultiDocumentHighlightProvider(selector, provider) {
        return extHostLanguageFeatures.registerMultiDocumentHighlightProvider(extension, checkSelector(selector), provider);
      },
      registerLinkedEditingRangeProvider(selector, provider) {
        return extHostLanguageFeatures.registerLinkedEditingRangeProvider(extension, checkSelector(selector), provider);
      },
      registerReferenceProvider(selector, provider) {
        return extHostLanguageFeatures.registerReferenceProvider(extension, checkSelector(selector), provider);
      },
      registerRenameProvider(selector, provider) {
        return extHostLanguageFeatures.registerRenameProvider(extension, checkSelector(selector), provider);
      },
      registerNewSymbolNamesProvider(selector, provider) {
        $AN(extension, "newSymbolNamesProvider");
        return extHostLanguageFeatures.registerNewSymbolNamesProvider(extension, checkSelector(selector), provider);
      },
      registerDocumentSymbolProvider(selector, provider, metadata) {
        return extHostLanguageFeatures.registerDocumentSymbolProvider(extension, checkSelector(selector), provider, metadata);
      },
      registerWorkspaceSymbolProvider(provider) {
        return extHostLanguageFeatures.registerWorkspaceSymbolProvider(extension, provider);
      },
      registerDocumentFormattingEditProvider(selector, provider) {
        return extHostLanguageFeatures.registerDocumentFormattingEditProvider(extension, checkSelector(selector), provider);
      },
      registerDocumentRangeFormattingEditProvider(selector, provider) {
        return extHostLanguageFeatures.registerDocumentRangeFormattingEditProvider(extension, checkSelector(selector), provider);
      },
      registerOnTypeFormattingEditProvider(selector, provider, firstTriggerCharacter, ...moreTriggerCharacters) {
        return extHostLanguageFeatures.registerOnTypeFormattingEditProvider(extension, checkSelector(selector), provider, [firstTriggerCharacter].concat(moreTriggerCharacters));
      },
      registerDocumentSemanticTokensProvider(selector, provider, legend) {
        return extHostLanguageFeatures.registerDocumentSemanticTokensProvider(extension, checkSelector(selector), provider, legend);
      },
      registerDocumentRangeSemanticTokensProvider(selector, provider, legend) {
        return extHostLanguageFeatures.registerDocumentRangeSemanticTokensProvider(extension, checkSelector(selector), provider, legend);
      },
      registerSignatureHelpProvider(selector, provider, firstItem, ...remaining) {
        if (typeof firstItem === "object") {
          return extHostLanguageFeatures.registerSignatureHelpProvider(extension, checkSelector(selector), provider, firstItem);
        }
        return extHostLanguageFeatures.registerSignatureHelpProvider(extension, checkSelector(selector), provider, typeof firstItem === "undefined" ? [] : [firstItem, ...remaining]);
      },
      registerCompletionItemProvider(selector, provider, ...triggerCharacters) {
        return extHostLanguageFeatures.registerCompletionItemProvider(extension, checkSelector(selector), provider, triggerCharacters);
      },
      registerInlineCompletionItemProvider(selector, provider, metadata) {
        if (provider.handleDidShowCompletionItem) {
          $AN(extension, "inlineCompletionsAdditions");
        }
        if (provider.handleDidPartiallyAcceptCompletionItem) {
          $AN(extension, "inlineCompletionsAdditions");
        }
        if (metadata) {
          $AN(extension, "inlineCompletionsAdditions");
        }
        return extHostLanguageFeatures.registerInlineCompletionsProvider(extension, checkSelector(selector), provider, metadata);
      },
      registerInlineEditProvider(selector, provider) {
        $AN(extension, "inlineEdit");
        return extHostLanguageFeatures.registerInlineEditProvider(extension, checkSelector(selector), provider);
      },
      registerDocumentLinkProvider(selector, provider) {
        return extHostLanguageFeatures.registerDocumentLinkProvider(extension, checkSelector(selector), provider);
      },
      registerColorProvider(selector, provider) {
        return extHostLanguageFeatures.registerColorProvider(extension, checkSelector(selector), provider);
      },
      registerFoldingRangeProvider(selector, provider) {
        return extHostLanguageFeatures.registerFoldingRangeProvider(extension, checkSelector(selector), provider);
      },
      registerSelectionRangeProvider(selector, provider) {
        return extHostLanguageFeatures.registerSelectionRangeProvider(extension, selector, provider);
      },
      registerCallHierarchyProvider(selector, provider) {
        return extHostLanguageFeatures.registerCallHierarchyProvider(extension, selector, provider);
      },
      registerTypeHierarchyProvider(selector, provider) {
        return extHostLanguageFeatures.registerTypeHierarchyProvider(extension, selector, provider);
      },
      setLanguageConfiguration: (language, configuration) => {
        return extHostLanguageFeatures.setLanguageConfiguration(extension, language, configuration);
      },
      getTokenInformationAtPosition(doc, pos) {
        $AN(extension, "tokenInformation");
        return extHostLanguages.tokenAtPosition(doc, pos);
      },
      registerInlayHintsProvider(selector, provider) {
        return extHostLanguageFeatures.registerInlayHintsProvider(extension, selector, provider);
      },
      createLanguageStatusItem(id2, selector) {
        return extHostLanguages.createLanguageStatusItem(extension, id2, selector);
      },
      registerDocumentDropEditProvider(selector, provider, metadata) {
        return extHostLanguageFeatures.registerDocumentOnDropEditProvider(extension, selector, provider, $zN(extension, "documentPaste") ? metadata : void 0);
      }
    };
    const window2 = {
      get activeTextEditor() {
        return extHostEditors.getActiveTextEditor();
      },
      get visibleTextEditors() {
        return extHostEditors.getVisibleTextEditors();
      },
      get activeTerminal() {
        return extHostTerminalService.activeTerminal;
      },
      get terminals() {
        return extHostTerminalService.terminals;
      },
      async showTextDocument(documentOrUri, columnOrOptions, preserveFocus) {
        if (URI.isUri(documentOrUri) && documentOrUri.scheme === Schemas.vscodeRemote && !documentOrUri.authority) {
          extHostApiDeprecation.report("workspace.showTextDocument", extension, `A URI of 'vscode-remote' scheme requires an authority.`);
        }
        const document2 = await (URI.isUri(documentOrUri) ? Promise.resolve(workspace.openTextDocument(documentOrUri)) : Promise.resolve(documentOrUri));
        return extHostEditors.showTextDocument(document2, columnOrOptions, preserveFocus);
      },
      createTextEditorDecorationType(options2) {
        return extHostEditors.createTextEditorDecorationType(extension, options2);
      },
      onDidChangeActiveTextEditor(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostEditors.onDidChangeActiveTextEditor)(listener, thisArg, disposables);
      },
      onDidChangeVisibleTextEditors(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostEditors.onDidChangeVisibleTextEditors)(listener, thisArg, disposables);
      },
      onDidChangeTextEditorSelection(listener, thisArgs, disposables) {
        return _asExtensionEvent(extHostEditors.onDidChangeTextEditorSelection)(listener, thisArgs, disposables);
      },
      onDidChangeTextEditorOptions(listener, thisArgs, disposables) {
        return _asExtensionEvent(extHostEditors.onDidChangeTextEditorOptions)(listener, thisArgs, disposables);
      },
      onDidChangeTextEditorVisibleRanges(listener, thisArgs, disposables) {
        return _asExtensionEvent(extHostEditors.onDidChangeTextEditorVisibleRanges)(listener, thisArgs, disposables);
      },
      onDidChangeTextEditorViewColumn(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostEditors.onDidChangeTextEditorViewColumn)(listener, thisArg, disposables);
      },
      onDidChangeTextEditorDiffInformation(listener, thisArg, disposables) {
        $AN(extension, "textEditorDiffInformation");
        return _asExtensionEvent(extHostEditors.onDidChangeTextEditorDiffInformation)(listener, thisArg, disposables);
      },
      onDidCloseTerminal(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostTerminalService.onDidCloseTerminal)(listener, thisArg, disposables);
      },
      onDidOpenTerminal(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostTerminalService.onDidOpenTerminal)(listener, thisArg, disposables);
      },
      onDidChangeActiveTerminal(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostTerminalService.onDidChangeActiveTerminal)(listener, thisArg, disposables);
      },
      onDidChangeTerminalDimensions(listener, thisArg, disposables) {
        $AN(extension, "terminalDimensions");
        return _asExtensionEvent(extHostTerminalService.onDidChangeTerminalDimensions)(listener, thisArg, disposables);
      },
      onDidChangeTerminalState(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostTerminalService.onDidChangeTerminalState)(listener, thisArg, disposables);
      },
      onDidWriteTerminalData(listener, thisArg, disposables) {
        $AN(extension, "terminalDataWriteEvent");
        return _asExtensionEvent(extHostTerminalService.onDidWriteTerminalData)(listener, thisArg, disposables);
      },
      onDidExecuteTerminalCommand(listener, thisArg, disposables) {
        $AN(extension, "terminalExecuteCommandEvent");
        return _asExtensionEvent(extHostTerminalService.onDidExecuteTerminalCommand)(listener, thisArg, disposables);
      },
      onDidChangeTerminalShellIntegration(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostTerminalShellIntegration.onDidChangeTerminalShellIntegration)(listener, thisArg, disposables);
      },
      onDidStartTerminalShellExecution(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostTerminalShellIntegration.onDidStartTerminalShellExecution)(listener, thisArg, disposables);
      },
      onDidEndTerminalShellExecution(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostTerminalShellIntegration.onDidEndTerminalShellExecution)(listener, thisArg, disposables);
      },
      get state() {
        return extHostWindow.getState();
      },
      onDidChangeWindowState(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostWindow.onDidChangeWindowState)(listener, thisArg, disposables);
      },
      showInformationMessage(message, ...rest) {
        return extHostMessageService.showMessage(extension, severity_default.Info, message, rest[0], rest.slice(1));
      },
      showWarningMessage(message, ...rest) {
        return extHostMessageService.showMessage(extension, severity_default.Warning, message, rest[0], rest.slice(1));
      },
      showErrorMessage(message, ...rest) {
        return extHostMessageService.showMessage(extension, severity_default.Error, message, rest[0], rest.slice(1));
      },
      showQuickPick(items, options2, token) {
        return extHostQuickOpen.showQuickPick(extension, items, options2, token);
      },
      showWorkspaceFolderPick(options2) {
        return extHostQuickOpen.showWorkspaceFolderPick(options2);
      },
      showInputBox(options2, token) {
        return extHostQuickOpen.showInput(options2, token);
      },
      showOpenDialog(options2) {
        return extHostDialogs.showOpenDialog(extension, options2);
      },
      showSaveDialog(options2) {
        return extHostDialogs.showSaveDialog(options2);
      },
      createStatusBarItem(alignmentOrId, priorityOrAlignment, priorityArg) {
        let id2;
        let alignment;
        let priority;
        if (typeof alignmentOrId === "string") {
          id2 = alignmentOrId;
          alignment = priorityOrAlignment;
          priority = priorityArg;
        } else {
          alignment = alignmentOrId;
          priority = priorityOrAlignment;
        }
        return extHostStatusBar.createStatusBarEntry(extension, id2, alignment, priority);
      },
      setStatusBarMessage(text, timeoutOrThenable) {
        return extHostStatusBar.setStatusBarMessage(text, timeoutOrThenable);
      },
      withScmProgress(task) {
        extHostApiDeprecation.report("window.withScmProgress", extension, `Use 'withProgress' instead.`);
        return extHostProgress.withProgress(extension, { location: ProgressLocation.SourceControl }, (progress, token) => task({ report(n) {
        } }));
      },
      withProgress(options2, task) {
        return extHostProgress.withProgress(extension, options2, task);
      },
      createOutputChannel(name, options2) {
        return extHostOutputService.createOutputChannel(name, options2, extension);
      },
      createWebviewPanel(viewType, title, showOptions, options2) {
        return extHostWebviewPanels.createWebviewPanel(extension, viewType, title, showOptions, options2);
      },
      createWebviewTextEditorInset(editor, line, height, options2) {
        $AN(extension, "editorInsets");
        return extHostEditorInsets.createWebviewEditorInset(editor, line, height, options2, extension);
      },
      createTerminal(nameOrOptions, shellPath, shellArgs) {
        if (typeof nameOrOptions === "object") {
          if ("pty" in nameOrOptions) {
            return extHostTerminalService.createExtensionTerminal(nameOrOptions);
          }
          return extHostTerminalService.createTerminalFromOptions(nameOrOptions);
        }
        return extHostTerminalService.createTerminal(nameOrOptions, shellPath, shellArgs);
      },
      registerTerminalLinkProvider(provider) {
        return extHostTerminalService.registerLinkProvider(provider);
      },
      registerTerminalProfileProvider(id2, provider) {
        return extHostTerminalService.registerProfileProvider(extension, id2, provider);
      },
      registerTerminalCompletionProvider(provider, ...triggerCharacters) {
        $AN(extension, "terminalCompletionProvider");
        return extHostTerminalService.registerTerminalCompletionProvider(extension, provider, ...triggerCharacters);
      },
      registerTerminalQuickFixProvider(id2, provider) {
        $AN(extension, "terminalQuickFixProvider");
        return extHostTerminalService.registerTerminalQuickFixProvider(id2, extension.identifier.value, provider);
      },
      registerTreeDataProvider(viewId, treeDataProvider) {
        return extHostTreeViews.registerTreeDataProvider(viewId, treeDataProvider, extension);
      },
      createTreeView(viewId, options2) {
        return extHostTreeViews.createTreeView(viewId, options2, extension);
      },
      registerWebviewPanelSerializer: (viewType, serializer) => {
        return extHostWebviewPanels.registerWebviewPanelSerializer(extension, viewType, serializer);
      },
      registerCustomEditorProvider: (viewType, provider, options2 = {}) => {
        return extHostCustomEditors.registerCustomEditorProvider(extension, viewType, provider, options2);
      },
      registerFileDecorationProvider(provider) {
        return extHostDecorations.registerFileDecorationProvider(provider, extension);
      },
      registerUriHandler(handler) {
        return extHostUrls.registerUriHandler(extension, handler);
      },
      createQuickPick() {
        return extHostQuickOpen.createQuickPick(extension);
      },
      createInputBox() {
        return extHostQuickOpen.createInputBox(extension);
      },
      get activeColorTheme() {
        return extHostTheming.activeColorTheme;
      },
      onDidChangeActiveColorTheme(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostTheming.onDidChangeActiveColorTheme)(listener, thisArg, disposables);
      },
      registerWebviewViewProvider(viewId, provider, options2) {
        return extHostWebviewViews.registerWebviewViewProvider(extension, viewId, provider, options2?.webviewOptions);
      },
      get activeNotebookEditor() {
        return extHostNotebook.activeNotebookEditor;
      },
      onDidChangeActiveNotebookEditor(listener, thisArgs, disposables) {
        return _asExtensionEvent(extHostNotebook.onDidChangeActiveNotebookEditor)(listener, thisArgs, disposables);
      },
      get visibleNotebookEditors() {
        return extHostNotebook.visibleNotebookEditors;
      },
      get onDidChangeVisibleNotebookEditors() {
        return _asExtensionEvent(extHostNotebook.onDidChangeVisibleNotebookEditors);
      },
      onDidChangeNotebookEditorSelection(listener, thisArgs, disposables) {
        return _asExtensionEvent(extHostNotebookEditors.onDidChangeNotebookEditorSelection)(listener, thisArgs, disposables);
      },
      onDidChangeNotebookEditorVisibleRanges(listener, thisArgs, disposables) {
        return _asExtensionEvent(extHostNotebookEditors.onDidChangeNotebookEditorVisibleRanges)(listener, thisArgs, disposables);
      },
      showNotebookDocument(document2, options2) {
        return extHostNotebook.showNotebookDocument(document2, options2);
      },
      registerExternalUriOpener(id2, opener, metadata) {
        $AN(extension, "externalUriOpener");
        return extHostUriOpeners.registerExternalUriOpener(extension.identifier, id2, opener, metadata);
      },
      registerProfileContentHandler(id2, handler) {
        $AN(extension, "profileContentHandlers");
        return extHostProfileContentHandlers.registerProfileContentHandler(extension, id2, handler);
      },
      registerQuickDiffProvider(selector, quickDiffProvider, label, rootUri) {
        $AN(extension, "quickDiffProvider");
        return extHostQuickDiff.registerQuickDiffProvider(checkSelector(selector), quickDiffProvider, label, rootUri);
      },
      get tabGroups() {
        return extHostEditorTabs.tabGroups;
      },
      registerShareProvider(selector, provider) {
        $AN(extension, "shareProvider");
        return extHostShare.registerShareProvider(checkSelector(selector), provider);
      },
      get nativeHandle() {
        $AN(extension, "nativeWindowHandle");
        return extHostWindow.nativeHandle;
      }
    };
    const workspace = {
      get rootPath() {
        extHostApiDeprecation.report("workspace.rootPath", extension, `Please use 'workspace.workspaceFolders' instead. More details: https://aka.ms/vscode-eliminating-rootpath`);
        return extHostWorkspace.getPath();
      },
      set rootPath(value) {
        throw new $pb("rootPath");
      },
      getWorkspaceFolder(resource) {
        return extHostWorkspace.getWorkspaceFolder(resource);
      },
      get workspaceFolders() {
        return extHostWorkspace.getWorkspaceFolders();
      },
      get name() {
        return extHostWorkspace.name;
      },
      set name(value) {
        throw new $pb("name");
      },
      get workspaceFile() {
        return extHostWorkspace.workspaceFile;
      },
      set workspaceFile(value) {
        throw new $pb("workspaceFile");
      },
      updateWorkspaceFolders: (index, deleteCount, ...workspaceFoldersToAdd) => {
        return extHostWorkspace.updateWorkspaceFolders(extension, index, deleteCount || 0, ...workspaceFoldersToAdd);
      },
      onDidChangeWorkspaceFolders: function(listener, thisArgs, disposables) {
        return _asExtensionEvent(extHostWorkspace.onDidChangeWorkspace)(listener, thisArgs, disposables);
      },
      asRelativePath: (pathOrUri, includeWorkspace) => {
        return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
      },
      findFiles: (include, exclude, maxResults, token) => {
        return extHostWorkspace.findFiles(include, exclude, maxResults, extension.identifier, token);
      },
      findFiles2: (filePattern, options2, token) => {
        $AN(extension, "findFiles2");
        return extHostWorkspace.findFiles2(filePattern, options2, extension.identifier, token);
      },
      findTextInFiles: (query, optionsOrCallback, callbackOrToken, token) => {
        $AN(extension, "findTextInFiles");
        let options2;
        let callback;
        if (typeof optionsOrCallback === "object") {
          options2 = optionsOrCallback;
          callback = callbackOrToken;
        } else {
          options2 = {};
          callback = optionsOrCallback;
          token = callbackOrToken;
        }
        return extHostWorkspace.findTextInFiles(query, options2 || {}, callback, extension.identifier, token);
      },
      findTextInFiles2: (query, options2, token) => {
        $AN(extension, "findTextInFiles2");
        $AN(extension, "textSearchProvider2");
        return extHostWorkspace.findTextInFiles2(query, options2, extension.identifier, token);
      },
      save: (uri) => {
        return extHostWorkspace.save(uri);
      },
      saveAs: (uri) => {
        return extHostWorkspace.saveAs(uri);
      },
      saveAll: (includeUntitled) => {
        return extHostWorkspace.saveAll(includeUntitled);
      },
      applyEdit(edit2, metadata) {
        return extHostBulkEdits.applyWorkspaceEdit(edit2, extension, metadata);
      },
      createFileSystemWatcher: (pattern, optionsOrIgnoreCreate, ignoreChange, ignoreDelete) => {
        let options2 = void 0;
        if (optionsOrIgnoreCreate && typeof optionsOrIgnoreCreate !== "boolean") {
          $AN(extension, "createFileSystemWatcher");
          options2 = {
            ...optionsOrIgnoreCreate,
            correlate: true
          };
        } else {
          options2 = {
            ignoreCreateEvents: Boolean(optionsOrIgnoreCreate),
            ignoreChangeEvents: Boolean(ignoreChange),
            ignoreDeleteEvents: Boolean(ignoreDelete),
            correlate: false
          };
        }
        return extHostFileSystemEvent.createFileSystemWatcher(extHostWorkspace, configProvider, extension, pattern, options2);
      },
      get textDocuments() {
        return extHostDocuments.getAllDocumentData().map((data) => data.document);
      },
      set textDocuments(value) {
        throw new $pb("textDocuments");
      },
      openTextDocument(uriOrFileNameOrOptions) {
        let uriPromise;
        const options2 = uriOrFileNameOrOptions;
        if (typeof uriOrFileNameOrOptions === "string") {
          uriPromise = Promise.resolve(URI.file(uriOrFileNameOrOptions));
        } else if (URI.isUri(uriOrFileNameOrOptions)) {
          uriPromise = Promise.resolve(uriOrFileNameOrOptions);
        } else if (!options2 || typeof options2 === "object") {
          uriPromise = extHostDocuments.createDocumentData(options2);
        } else {
          throw new Error("illegal argument - uriOrFileNameOrOptions");
        }
        return uriPromise.then((uri) => {
          extHostLogService.trace(`openTextDocument from ${extension.identifier}`);
          if (uri.scheme === Schemas.vscodeRemote && !uri.authority) {
            extHostApiDeprecation.report("workspace.openTextDocument", extension, `A URI of 'vscode-remote' scheme requires an authority.`);
          }
          return extHostDocuments.ensureDocumentData(uri).then((documentData) => {
            return documentData.document;
          });
        });
      },
      onDidOpenTextDocument: (listener, thisArgs, disposables) => {
        return _asExtensionEvent(extHostDocuments.onDidAddDocument)(listener, thisArgs, disposables);
      },
      onDidCloseTextDocument: (listener, thisArgs, disposables) => {
        return _asExtensionEvent(extHostDocuments.onDidRemoveDocument)(listener, thisArgs, disposables);
      },
      onDidChangeTextDocument: (listener, thisArgs, disposables) => {
        return _asExtensionEvent(extHostDocuments.onDidChangeDocument)(listener, thisArgs, disposables);
      },
      onDidSaveTextDocument: (listener, thisArgs, disposables) => {
        return _asExtensionEvent(extHostDocuments.onDidSaveDocument)(listener, thisArgs, disposables);
      },
      onWillSaveTextDocument: (listener, thisArgs, disposables) => {
        return _asExtensionEvent(extHostDocumentSaveParticipant.getOnWillSaveTextDocumentEvent(extension))(listener, thisArgs, disposables);
      },
      get notebookDocuments() {
        return extHostNotebook.notebookDocuments.map((d) => d.apiNotebook);
      },
      async openNotebookDocument(uriOrType, content) {
        let uri;
        if (URI.isUri(uriOrType)) {
          uri = uriOrType;
          await extHostNotebook.openNotebookDocument(uriOrType);
        } else if (typeof uriOrType === "string") {
          uri = URI.revive(await extHostNotebook.createNotebookDocument({ viewType: uriOrType, content }));
        } else {
          throw new Error("Invalid arguments");
        }
        return extHostNotebook.getNotebookDocument(uri).apiNotebook;
      },
      onDidSaveNotebookDocument(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostNotebookDocuments.onDidSaveNotebookDocument)(listener, thisArg, disposables);
      },
      onDidChangeNotebookDocument(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostNotebookDocuments.onDidChangeNotebookDocument)(listener, thisArg, disposables);
      },
      onWillSaveNotebookDocument(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostNotebookDocumentSaveParticipant.getOnWillSaveNotebookDocumentEvent(extension))(listener, thisArg, disposables);
      },
      get onDidOpenNotebookDocument() {
        return _asExtensionEvent(extHostNotebook.onDidOpenNotebookDocument);
      },
      get onDidCloseNotebookDocument() {
        return _asExtensionEvent(extHostNotebook.onDidCloseNotebookDocument);
      },
      registerNotebookSerializer(viewType, serializer, options2, registration) {
        return extHostNotebook.registerNotebookSerializer(extension, viewType, serializer, options2, $zN(extension, "notebookLiveShare") ? registration : void 0);
      },
      onDidChangeConfiguration: (listener, thisArgs, disposables) => {
        return _asExtensionEvent(configProvider.onDidChangeConfiguration)(listener, thisArgs, disposables);
      },
      getConfiguration(section, scope) {
        scope = arguments.length === 1 ? void 0 : scope;
        return configProvider.getConfiguration(section, scope, extension);
      },
      registerTextDocumentContentProvider(scheme, provider) {
        return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider);
      },
      registerTaskProvider: (type, provider) => {
        extHostApiDeprecation.report("window.registerTaskProvider", extension, `Use the corresponding function on the 'tasks' namespace instead`);
        return extHostTask.registerTaskProvider(extension, type, provider);
      },
      registerFileSystemProvider(scheme, provider, options2) {
        return $Zc(extHostFileSystem.registerFileSystemProvider(extension, scheme, provider, options2), extHostConsumerFileSystem.addFileSystemProvider(scheme, provider, options2));
      },
      get fs() {
        return extHostConsumerFileSystem.value;
      },
      registerFileSearchProvider: (scheme, provider) => {
        $AN(extension, "fileSearchProvider");
        return extHostSearch.registerFileSearchProviderOld(scheme, provider);
      },
      registerTextSearchProvider: (scheme, provider) => {
        $AN(extension, "textSearchProvider");
        return extHostSearch.registerTextSearchProviderOld(scheme, provider);
      },
      registerAITextSearchProvider: (scheme, provider) => {
        $AN(extension, "aiTextSearchProvider");
        $AN(extension, "textSearchProvider2");
        return extHostSearch.registerAITextSearchProvider(scheme, provider);
      },
      registerFileSearchProvider2: (scheme, provider) => {
        $AN(extension, "fileSearchProvider2");
        return extHostSearch.registerFileSearchProvider(scheme, provider);
      },
      registerTextSearchProvider2: (scheme, provider) => {
        $AN(extension, "textSearchProvider2");
        return extHostSearch.registerTextSearchProvider(scheme, provider);
      },
      registerRemoteAuthorityResolver: (authorityPrefix, resolver) => {
        $AN(extension, "resolvers");
        return extensionService.registerRemoteAuthorityResolver(authorityPrefix, resolver);
      },
      registerResourceLabelFormatter: (formatter) => {
        $AN(extension, "resolvers");
        return extHostLabelService.$registerResourceLabelFormatter(formatter);
      },
      getRemoteExecServer: (authority) => {
        $AN(extension, "resolvers");
        return extensionService.getRemoteExecServer(authority);
      },
      onDidCreateFiles: (listener, thisArg, disposables) => {
        return _asExtensionEvent(extHostFileSystemEvent.onDidCreateFile)(listener, thisArg, disposables);
      },
      onDidDeleteFiles: (listener, thisArg, disposables) => {
        return _asExtensionEvent(extHostFileSystemEvent.onDidDeleteFile)(listener, thisArg, disposables);
      },
      onDidRenameFiles: (listener, thisArg, disposables) => {
        return _asExtensionEvent(extHostFileSystemEvent.onDidRenameFile)(listener, thisArg, disposables);
      },
      onWillCreateFiles: (listener, thisArg, disposables) => {
        return _asExtensionEvent(extHostFileSystemEvent.getOnWillCreateFileEvent(extension))(listener, thisArg, disposables);
      },
      onWillDeleteFiles: (listener, thisArg, disposables) => {
        return _asExtensionEvent(extHostFileSystemEvent.getOnWillDeleteFileEvent(extension))(listener, thisArg, disposables);
      },
      onWillRenameFiles: (listener, thisArg, disposables) => {
        return _asExtensionEvent(extHostFileSystemEvent.getOnWillRenameFileEvent(extension))(listener, thisArg, disposables);
      },
      openTunnel: (forward) => {
        $AN(extension, "tunnels");
        return extHostTunnelService.openTunnel(extension, forward).then((value) => {
          if (!value) {
            throw new Error("cannot open tunnel");
          }
          return value;
        });
      },
      get tunnels() {
        $AN(extension, "tunnels");
        return extHostTunnelService.getTunnels();
      },
      onDidChangeTunnels: (listener, thisArg, disposables) => {
        $AN(extension, "tunnels");
        return _asExtensionEvent(extHostTunnelService.onDidChangeTunnels)(listener, thisArg, disposables);
      },
      registerPortAttributesProvider: (portSelector, provider) => {
        $AN(extension, "portsAttributes");
        return extHostTunnelService.registerPortsAttributesProvider(portSelector, provider);
      },
      registerTunnelProvider: (tunnelProvider, information) => {
        $AN(extension, "tunnelFactory");
        return extHostTunnelService.registerTunnelProvider(tunnelProvider, information);
      },
      registerTimelineProvider: (scheme, provider) => {
        $AN(extension, "timeline");
        return extHostTimeline.registerTimelineProvider(scheme, provider, extension.identifier, extHostCommands.converter);
      },
      get isTrusted() {
        return extHostWorkspace.trusted;
      },
      requestWorkspaceTrust: (options2) => {
        $AN(extension, "workspaceTrust");
        return extHostWorkspace.requestWorkspaceTrust(options2);
      },
      onDidGrantWorkspaceTrust: (listener, thisArgs, disposables) => {
        return _asExtensionEvent(extHostWorkspace.onDidGrantWorkspaceTrust)(listener, thisArgs, disposables);
      },
      registerEditSessionIdentityProvider: (scheme, provider) => {
        $AN(extension, "editSessionIdentityProvider");
        return extHostWorkspace.registerEditSessionIdentityProvider(scheme, provider);
      },
      onWillCreateEditSessionIdentity: (listener, thisArgs, disposables) => {
        $AN(extension, "editSessionIdentityProvider");
        return _asExtensionEvent(extHostWorkspace.getOnWillCreateEditSessionIdentityEvent(extension))(listener, thisArgs, disposables);
      },
      registerCanonicalUriProvider: (scheme, provider) => {
        $AN(extension, "canonicalUriProvider");
        return extHostWorkspace.registerCanonicalUriProvider(scheme, provider);
      },
      getCanonicalUri: (uri, options2, token) => {
        $AN(extension, "canonicalUriProvider");
        return extHostWorkspace.provideCanonicalUri(uri, options2, token);
      }
    };
    const scm = {
      get inputBox() {
        extHostApiDeprecation.report("scm.inputBox", extension, `Use 'SourceControl.inputBox' instead`);
        return extHostSCM.getLastInputBox(extension);
      },
      createSourceControl(id2, label, rootUri) {
        return extHostSCM.createSourceControl(extension, id2, label, rootUri);
      }
    };
    const comments = {
      createCommentController(id2, label) {
        return extHostComment.createCommentController(extension, id2, label);
      }
    };
    const debug = {
      get activeDebugSession() {
        return extHostDebugService.activeDebugSession;
      },
      get activeDebugConsole() {
        return extHostDebugService.activeDebugConsole;
      },
      get breakpoints() {
        return extHostDebugService.breakpoints;
      },
      get activeStackItem() {
        return extHostDebugService.activeStackItem;
      },
      registerDebugVisualizationProvider(id2, provider) {
        $AN(extension, "debugVisualization");
        return extHostDebugService.registerDebugVisualizationProvider(extension, id2, provider);
      },
      registerDebugVisualizationTreeProvider(id2, provider) {
        $AN(extension, "debugVisualization");
        return extHostDebugService.registerDebugVisualizationTree(extension, id2, provider);
      },
      onDidStartDebugSession(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostDebugService.onDidStartDebugSession)(listener, thisArg, disposables);
      },
      onDidTerminateDebugSession(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostDebugService.onDidTerminateDebugSession)(listener, thisArg, disposables);
      },
      onDidChangeActiveDebugSession(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostDebugService.onDidChangeActiveDebugSession)(listener, thisArg, disposables);
      },
      onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostDebugService.onDidReceiveDebugSessionCustomEvent)(listener, thisArg, disposables);
      },
      onDidChangeBreakpoints(listener, thisArgs, disposables) {
        return _asExtensionEvent(extHostDebugService.onDidChangeBreakpoints)(listener, thisArgs, disposables);
      },
      onDidChangeActiveStackItem(listener, thisArg, disposables) {
        return _asExtensionEvent(extHostDebugService.onDidChangeActiveStackItem)(listener, thisArg, disposables);
      },
      registerDebugConfigurationProvider(debugType, provider, triggerKind) {
        return extHostDebugService.registerDebugConfigurationProvider(debugType, provider, triggerKind || DebugConfigurationProviderTriggerKind.Initial);
      },
      registerDebugAdapterDescriptorFactory(debugType, factory) {
        return extHostDebugService.registerDebugAdapterDescriptorFactory(extension, debugType, factory);
      },
      registerDebugAdapterTrackerFactory(debugType, factory) {
        return extHostDebugService.registerDebugAdapterTrackerFactory(debugType, factory);
      },
      startDebugging(folder, nameOrConfig, parentSessionOrOptions) {
        if (!parentSessionOrOptions || typeof parentSessionOrOptions === "object" && "configuration" in parentSessionOrOptions) {
          return extHostDebugService.startDebugging(folder, nameOrConfig, { parentSession: parentSessionOrOptions });
        }
        return extHostDebugService.startDebugging(folder, nameOrConfig, parentSessionOrOptions || {});
      },
      stopDebugging(session) {
        return extHostDebugService.stopDebugging(session);
      },
      addBreakpoints(breakpoints) {
        return extHostDebugService.addBreakpoints(breakpoints);
      },
      removeBreakpoints(breakpoints) {
        return extHostDebugService.removeBreakpoints(breakpoints);
      },
      asDebugSourceUri(source, session) {
        return extHostDebugService.asDebugSourceUri(source, session);
      }
    };
    const tasks = {
      registerTaskProvider: (type, provider) => {
        return extHostTask.registerTaskProvider(extension, type, provider);
      },
      fetchTasks: (filter) => {
        return extHostTask.fetchTasks(filter);
      },
      executeTask: (task) => {
        return extHostTask.executeTask(extension, task);
      },
      get taskExecutions() {
        return extHostTask.taskExecutions;
      },
      onDidStartTask: (listeners, thisArgs, disposables) => {
        return _asExtensionEvent(extHostTask.onDidStartTask)(listeners, thisArgs, disposables);
      },
      onDidEndTask: (listeners, thisArgs, disposables) => {
        return _asExtensionEvent(extHostTask.onDidEndTask)(listeners, thisArgs, disposables);
      },
      onDidStartTaskProcess: (listeners, thisArgs, disposables) => {
        return _asExtensionEvent(extHostTask.onDidStartTaskProcess)(listeners, thisArgs, disposables);
      },
      onDidEndTaskProcess: (listeners, thisArgs, disposables) => {
        return _asExtensionEvent(extHostTask.onDidEndTaskProcess)(listeners, thisArgs, disposables);
      }
    };
    const notebooks = {
      createNotebookController(id2, notebookType, label, handler, rendererScripts) {
        return extHostNotebookKernels.createNotebookController(extension, id2, notebookType, label, handler, $zN(extension, "notebookMessaging") ? rendererScripts : void 0);
      },
      registerNotebookCellStatusBarItemProvider: (notebookType, provider) => {
        return extHostNotebook.registerNotebookCellStatusBarItemProvider(extension, notebookType, provider);
      },
      createRendererMessaging(rendererId) {
        return extHostNotebookRenderers.createRendererMessaging(extension, rendererId);
      },
      createNotebookControllerDetectionTask(notebookType) {
        $AN(extension, "notebookKernelSource");
        return extHostNotebookKernels.createNotebookControllerDetectionTask(extension, notebookType);
      },
      registerKernelSourceActionProvider(notebookType, provider) {
        $AN(extension, "notebookKernelSource");
        return extHostNotebookKernels.registerKernelSourceActionProvider(extension, notebookType, provider);
      },
      onDidChangeNotebookCellExecutionState(listener, thisArgs, disposables) {
        $AN(extension, "notebookCellExecutionState");
        return _asExtensionEvent(extHostNotebookKernels.onDidChangeNotebookCellExecutionState)(listener, thisArgs, disposables);
      }
    };
    const l10n = {
      t(...params) {
        if (typeof params[0] === "string") {
          const key = params.shift();
          const argsFormatted = !params || typeof params[0] !== "object" ? params : params[0];
          return extHostLocalization.getMessage(extension.identifier.value, { message: key, args: argsFormatted });
        }
        return extHostLocalization.getMessage(extension.identifier.value, params[0]);
      },
      get bundle() {
        return extHostLocalization.getBundle(extension.identifier.value);
      },
      get uri() {
        return extHostLocalization.getBundleUri(extension.identifier.value);
      }
    };
    const interactive = {
      transferActiveChat(toWorkspace) {
        $AN(extension, "interactive");
        return extHostChatAgents2.transferActiveChat(toWorkspace);
      }
    };
    const ai = {
      getRelatedInformation(query, types) {
        $AN(extension, "aiRelatedInformation");
        return extHostAiRelatedInformation.getRelatedInformation(extension, query, types);
      },
      registerRelatedInformationProvider(type, provider) {
        $AN(extension, "aiRelatedInformation");
        return extHostAiRelatedInformation.registerRelatedInformationProvider(extension, type, provider);
      },
      registerEmbeddingVectorProvider(model, provider) {
        $AN(extension, "aiRelatedInformation");
        return extHostAiEmbeddingVector.registerEmbeddingVectorProvider(extension, model, provider);
      }
    };
    const chat = {
      registerChatResponseProvider(id2, provider, metadata) {
        $AN(extension, "chatProvider");
        return extHostLanguageModels.registerLanguageModel(extension, id2, provider, metadata);
      },
      registerChatVariableResolver(id2, name, userDescription, modelDescription, isSlow, resolver, fullName, icon) {
        $AN(extension, "chatVariableResolver");
        return extHostChatVariables.registerVariableResolver(extension, id2, name, userDescription, modelDescription, isSlow, resolver, fullName, icon?.id);
      },
      registerMappedEditsProvider(selector, provider) {
        $AN(extension, "mappedEditsProvider");
        return extHostLanguageFeatures.registerMappedEditsProvider(extension, selector, provider);
      },
      registerMappedEditsProvider2(provider) {
        $AN(extension, "mappedEditsProvider");
        return extHostCodeMapper.registerMappedEditsProvider(extension, provider);
      },
      createChatParticipant(id2, handler) {
        return extHostChatAgents2.createChatAgent(extension, id2, handler);
      },
      createDynamicChatParticipant(id2, dynamicProps, handler) {
        $AN(extension, "chatParticipantPrivate");
        return extHostChatAgents2.createDynamicChatAgent(extension, id2, dynamicProps, handler);
      },
      registerChatParticipantDetectionProvider(provider) {
        $AN(extension, "chatParticipantAdditions");
        return extHostChatAgents2.registerChatParticipantDetectionProvider(extension, provider);
      },
      registerRelatedFilesProvider(provider, metadata) {
        $AN(extension, "chatEditing");
        return extHostChatAgents2.registerRelatedFilesProvider(extension, provider, metadata);
      }
    };
    const lm = {
      selectChatModels: (selector) => {
        return extHostLanguageModels.selectLanguageModels(extension, selector ?? {});
      },
      onDidChangeChatModels: (listener, thisArgs, disposables) => {
        return extHostLanguageModels.onDidChangeProviders(listener, thisArgs, disposables);
      },
      registerChatModelProvider: (id2, provider, metadata) => {
        $AN(extension, "chatProvider");
        return extHostLanguageModels.registerLanguageModel(extension, id2, provider, metadata);
      },
      // --- embeddings
      get embeddingModels() {
        $AN(extension, "embeddings");
        return extHostEmbeddings.embeddingsModels;
      },
      onDidChangeEmbeddingModels: (listener, thisArgs, disposables) => {
        $AN(extension, "embeddings");
        return extHostEmbeddings.onDidChange(listener, thisArgs, disposables);
      },
      registerEmbeddingsProvider(embeddingsModel, provider) {
        $AN(extension, "embeddings");
        return extHostEmbeddings.registerEmbeddingsProvider(extension, embeddingsModel, provider);
      },
      async computeEmbeddings(embeddingsModel, input, token) {
        $AN(extension, "embeddings");
        if (typeof input === "string") {
          return extHostEmbeddings.computeEmbeddings(embeddingsModel, input, token);
        } else {
          return extHostEmbeddings.computeEmbeddings(embeddingsModel, input, token);
        }
      },
      registerTool(name, tool) {
        return extHostLanguageModelTools.registerTool(extension, name, tool);
      },
      invokeTool(name, parameters, token) {
        return extHostLanguageModelTools.invokeTool(name, parameters, token);
      },
      get tools() {
        return extHostLanguageModelTools.tools;
      },
      fileIsIgnored(uri, token) {
        return extHostLanguageModels.fileIsIgnored(extension, uri, token);
      },
      registerIgnoredFileProvider(provider) {
        return extHostLanguageModels.registerIgnoredFileProvider(extension, provider);
      }
    };
    const speech = {
      registerSpeechProvider(id2, provider) {
        $AN(extension, "speech");
        return extHostSpeech.registerProvider(extension.identifier, id2, provider);
      }
    };
    return {
      version: initData.version,
      // namespaces
      ai,
      authentication,
      commands,
      comments,
      chat,
      debug,
      env: env2,
      extensions,
      interactive,
      l10n,
      languages,
      lm,
      notebooks,
      scm,
      speech,
      tasks,
      tests,
      window: window2,
      workspace,
      // types
      Breakpoint: $EU,
      TerminalOutputAnchor,
      ChatResultFeedbackKind,
      ChatVariableLevel,
      ChatCompletionItem: $CV,
      CallHierarchyIncomingCall: $1T,
      CallHierarchyItem: $ZT,
      CallHierarchyOutgoingCall: $2T,
      CancellationError: $lb,
      CancellationTokenSource: $ad,
      CandidatePortSource,
      CodeAction: $WT,
      CodeActionKind: $XT,
      CodeActionTriggerKind,
      CodeLens: $3T,
      Color: $dU,
      ColorInformation: $eU,
      ColorPresentation: $fU,
      ColorThemeKind,
      CommentMode: CommentMode2,
      CommentState: CommentState2,
      CommentThreadCollapsibleState: CommentThreadCollapsibleState2,
      CommentThreadState: CommentThreadState2,
      CommentThreadApplicability: CommentThreadApplicability2,
      CommentThreadFocus,
      CompletionItem: $0T,
      CompletionItemKind: CompletionItemKind2,
      CompletionItemTag: CompletionItemTag2,
      CompletionList: $$T,
      CompletionTriggerKind: CompletionTriggerKind2,
      ConfigurationTarget: ConfigurationTarget2,
      CustomExecution: $pU,
      DebugAdapterExecutable: $IU,
      DebugAdapterInlineImplementation: $LU,
      DebugAdapterNamedPipeServer: $KU,
      DebugAdapterServer: $JU,
      DebugConfigurationProviderTriggerKind,
      DebugConsoleMode,
      DebugVisualization: $2U,
      DecorationRangeBehavior,
      Diagnostic: $PT,
      DiagnosticRelatedInformation: $OT,
      DiagnosticSeverity,
      DiagnosticTag,
      Disposable: $zT,
      DocumentHighlight: $ST,
      DocumentHighlightKind: DocumentHighlightKind2,
      MultiDocumentHighlight: $TT,
      DocumentLink: $cU,
      DocumentSymbol: $VT,
      EndOfLine,
      EnvironmentVariableMutatorType,
      EvaluatableExpression: $OU,
      InlineValueText: $PU,
      InlineValueVariableLookup: $QU,
      InlineValueEvaluatableExpression: $RU,
      InlineCompletionTriggerKind: InlineCompletionTriggerKind2,
      EventEmitter: $ze,
      ExtensionKind,
      ExtensionMode,
      ExternalUriOpenerPriority: ExternalUriOpenerPriority2,
      FileChangeType: FileChangeType2,
      FileDecoration: $4U,
      FileDecoration2: $4U,
      FileSystemError: $UU,
      FileType,
      FilePermission,
      FoldingRange: $VU,
      FoldingRangeKind,
      FunctionBreakpoint: $GU,
      InlineCompletionItem: $_T,
      InlineCompletionList: $aU,
      Hover: $QT,
      VerboseHover: $RT,
      HoverVerbosityAction: HoverVerbosityAction2,
      IndentAction,
      Location: $NT,
      MarkdownString: $4T,
      OverviewRulerLane,
      ParameterInformation: $5T,
      PortAutoForwardAction,
      Position: $AT,
      ProcessExecution: $nU,
      ProgressLocation,
      QuickInputButtonLocation,
      QuickInputButtons: $3U,
      Range: $BT,
      RelativePattern: $CU,
      Selection: $CT,
      SelectionRange: $YT,
      SemanticTokens: $YU,
      SemanticTokensBuilder: $XU,
      SemanticTokensEdit: $ZU,
      SemanticTokensEdits: $1U,
      SemanticTokensLegend: $WU,
      ShellExecution: $oU,
      ShellQuoting,
      SignatureHelp: $7T,
      SignatureHelpTriggerKind: SignatureHelpTriggerKind2,
      SignatureInformation: $6T,
      SnippetString: $MT,
      SourceBreakpoint: $FU,
      StandardTokenType,
      StatusBarAlignment,
      SymbolInformation: $UT,
      SymbolKind: SymbolKind2,
      SymbolTag: SymbolTag2,
      Task: $qU,
      TaskGroup: $mU,
      TaskPanelKind,
      TaskRevealKind,
      TaskScope,
      TerminalLink: $gU,
      TerminalQuickFixTerminalCommand: $iU,
      TerminalQuickFixOpener: $hU,
      TerminalLocation,
      TerminalProfile: $jU,
      TerminalExitReason,
      TerminalShellExecutionCommandLineConfidence,
      TerminalCompletionItem: $kU,
      TerminalCompletionItemKind,
      TerminalCompletionList: $lU,
      TextDocumentSaveReason,
      TextEdit: $IT,
      SnippetTextEdit: $KT,
      TextEditorCursorStyle,
      TextEditorChangeKind,
      TextEditorLineNumbersStyle,
      TextEditorRevealType: TextEditorRevealType2,
      TextEditorSelectionChangeKind,
      SyntaxTokenType,
      TextDocumentChangeReason,
      ThemeColor: $BU,
      ThemeIcon: $AU,
      TreeItem: $rU,
      TreeItemCheckboxState,
      TreeItemCollapsibleState,
      TypeHierarchyItem: $qV,
      UIKind,
      Uri: URI,
      ViewColumn,
      WorkspaceEdit: $LT,
      // proposed api types
      DocumentPasteTriggerKind: DocumentPasteTriggerKind2,
      DocumentDropEdit: $xU,
      DocumentDropOrPasteEditKind: $yU,
      DocumentPasteEdit: $zU,
      InlayHint: $9T,
      InlayHintLabelPart: $8T,
      InlayHintKind: InlayHintKind2,
      RemoteAuthorityResolverError: $HT,
      ResolvedAuthority: $FT,
      ManagedResolvedAuthority: $GT,
      SourceControlInputBoxValidationType,
      ExtensionRuntime,
      TimelineItem: $cV,
      NotebookRange: $6U,
      NotebookCellKind,
      NotebookCellExecutionState: NotebookCellExecutionState2,
      NotebookCellData: $7U,
      NotebookData: $8U,
      NotebookRendererScript: $aV,
      NotebookCellStatusBarAlignment,
      NotebookEditorRevealType: NotebookEditorRevealType2,
      NotebookCellOutput: $0U,
      NotebookCellOutputItem: $9U,
      CellErrorStackFrame: $$U,
      NotebookCellStatusBarItem: $_U,
      NotebookControllerAffinity,
      NotebookControllerAffinity2,
      NotebookEdit: $JT,
      NotebookKernelSourceAction: $bV,
      NotebookVariablesRequestKind,
      PortAttributes: $eV,
      LinkedEditingRanges: $dV,
      TestResultState: TestResultState2,
      TestRunRequest: $gV,
      TestMessage: $hV,
      TestMessageStackFrame: $jV,
      TestTag: $iV,
      TestRunProfileKind,
      TextSearchCompleteMessageType,
      DataTransfer: $wU,
      DataTransferItem: $sU,
      TestCoverageCount: $kV,
      FileCoverage: $mV,
      StatementCoverage: $nV,
      BranchCoverage: $oV,
      DeclarationCoverage: $pV,
      WorkspaceTrustState,
      LanguageStatusSeverity,
      QuickPickItemKind,
      InputBoxValidationSeverity,
      TabInputText: $rV,
      TabInputTextDiff: $sV,
      TabInputTextMerge: $tV,
      TabInputCustom: $uV,
      TabInputNotebook: $wV,
      TabInputNotebookDiff: $xV,
      TabInputWebview: $vV,
      TabInputTerminal: $yV,
      TabInputInteractiveWindow: $zV,
      TabInputChat: $AV,
      TabInputTextMultiDiff: $BV,
      TelemetryTrustedValue: $bw,
      LogLevel,
      EditSessionIdentityMatch,
      InteractiveSessionVoteDirection,
      ChatCopyKind,
      ChatEditingSessionActionOutcome,
      InteractiveEditorResponseFeedbackKind,
      DebugStackFrame: $MU,
      DebugThread: $NU,
      RelatedInformationType,
      SpeechToTextStatus,
      TextToSpeechStatus,
      PartialAcceptTriggerKind: PartialAcceptTriggerKind2,
      KeywordRecognitionStatus,
      ChatResponseMarkdownPart: $DV,
      ChatResponseFileTreePart: $HV,
      ChatResponseAnchorPart: $IV,
      ChatResponseProgressPart: $JV,
      ChatResponseProgressPart2: $KV,
      ChatResponseReferencePart: $NV,
      ChatResponseReferencePart2: $NV,
      ChatResponseCodeCitationPart: $PV,
      ChatResponseCodeblockUriPart: $OV,
      ChatResponseWarningPart: $LV,
      ChatResponseTextEditPart: $RV,
      ChatResponseMarkdownWithVulnerabilitiesPart: $EV,
      ChatResponseCommandButtonPart: $MV,
      ChatResponseDetectedParticipantPart: $FV,
      ChatResponseConfirmationPart: $GV,
      ChatResponseMovePart: $QV,
      ChatResponseReferencePartStatusKind,
      ChatRequestTurn: $SV,
      ChatResponseTurn: $TV,
      ChatLocation,
      ChatRequestEditorData: $UV,
      ChatRequestNotebookData: $VV,
      ChatReferenceBinaryData: $WV,
      LanguageModelChatMessageRole,
      LanguageModelChatMessage: $YV,
      LanguageModelToolResultPart: $XV,
      LanguageModelTextPart: $1V,
      LanguageModelToolCallPart: $ZV,
      LanguageModelError: $6V,
      LanguageModelToolResult: $7V,
      LanguageModelChatToolMode,
      LanguageModelPromptTsxPart: $2V,
      NewSymbolName: $TU,
      NewSymbolNameTag: NewSymbolNameTag2,
      NewSymbolNameTriggerKind: NewSymbolNameTriggerKind2,
      InlineEdit: $8V,
      InlineEditTriggerKind: InlineEditTriggerKind2,
      ExcludeSettingOptions,
      TextSearchContext2: $MN,
      TextSearchMatch2: $LN,
      TextSearchCompleteMessageTypeNew: TextSearchCompleteMessageType
    };
  };
}

// out-build/vs/workbench/api/common/extHostRequireInterceptor.js
var NodeModuleAliasingModuleFactory_1;
var $5yc = class $5yc2 {
  constructor(c, d, e, f, g, h, i) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.a = /* @__PURE__ */ new Map();
    this.b = [];
  }
  async install() {
    this.j();
    $S("code/extHost/willWaitForConfig");
    const configProvider = await this.f.getConfigProvider();
    $S("code/extHost/didWaitForConfig");
    const extensionPaths = await this.g.getExtensionPathIndex();
    this.register(new VSCodeNodeModuleFactory(this.c, extensionPaths, this.d, configProvider, this.i));
    this.register(this.e.createInstance(NodeModuleAliasingModuleFactory));
    if (this.h.remote.isRemote) {
      this.register(this.e.createInstance(OpenNodeModuleFactory, extensionPaths, this.h.environment.appUriScheme));
    }
  }
  register(interceptor) {
    if ("nodeModuleName" in interceptor) {
      if (Array.isArray(interceptor.nodeModuleName)) {
        for (const moduleName of interceptor.nodeModuleName) {
          this.a.set(moduleName, interceptor);
        }
      } else {
        this.a.set(interceptor.nodeModuleName, interceptor);
      }
    }
    if (typeof interceptor.alternativeModuleName === "function") {
      this.b.push((moduleName) => {
        return interceptor.alternativeModuleName(moduleName);
      });
    }
  }
};
$5yc = __decorate([
  __param(2, $Pk),
  __param(3, $axc),
  __param(4, $Lxc),
  __param(5, $wW),
  __param(6, $wn)
], $5yc);
var NodeModuleAliasingModuleFactory = class NodeModuleAliasingModuleFactory2 {
  static {
    NodeModuleAliasingModuleFactory_1 = this;
  }
  static {
    this.a = /* @__PURE__ */ new Map([
      ["vscode-ripgrep", "@vscode/ripgrep"],
      ["vscode-windows-registry", "@vscode/windows-registry"]
    ]);
  }
  constructor(initData) {
    if (initData.environment.appRoot && NodeModuleAliasingModuleFactory_1.a.size) {
      const root = $Af(this.c(initData.environment.appRoot.fsPath));
      const npmIdChrs = `[a-z0-9_.-]`;
      const npmModuleName = `@${npmIdChrs}+\\/${npmIdChrs}+|${npmIdChrs}+`;
      const moduleFolders = "node_modules|node_modules\\.asar(?:\\.unpacked)?";
      this.b = new RegExp(`^(${root}/${moduleFolders}\\/)(${npmModuleName})(.*)$`, "i");
    }
  }
  alternativeModuleName(name) {
    if (!this.b) {
      return;
    }
    const result = this.b.exec(this.c(name));
    if (!result) {
      return;
    }
    const [, prefix, moduleName, suffix] = result;
    const dealiased = NodeModuleAliasingModuleFactory_1.a.get(moduleName);
    if (dealiased === void 0) {
      return;
    }
    console.warn(`${moduleName} as been renamed to ${dealiased}, please update your imports`);
    return prefix + dealiased + suffix;
  }
  c(str) {
    return str.replace(/\\/g, "/");
  }
};
NodeModuleAliasingModuleFactory = NodeModuleAliasingModuleFactory_1 = __decorate([
  __param(0, $wW)
], NodeModuleAliasingModuleFactory);
var VSCodeNodeModuleFactory = class {
  constructor(c, d, e, f, g) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.nodeModuleName = "vscode";
    this.a = new $7z();
  }
  load(_request, parent) {
    const ext = this.d.findSubstr(parent);
    if (ext) {
      let apiImpl = this.a.get(ext.identifier);
      if (!apiImpl) {
        apiImpl = this.c(ext, this.e, this.f);
        this.a.set(ext.identifier, apiImpl);
      }
      return apiImpl;
    }
    if (!this.b) {
      let extensionPathsPretty = "";
      this.d.forEach((value, index) => extensionPathsPretty += `	${index} -> ${value.identifier.value}
`);
      this.g.warn(`Could not identify extension for 'vscode' require call from ${parent}. These are the extension path mappings: 
${extensionPathsPretty}`);
      this.b = this.c($uN, this.e, this.f);
    }
    return this.b;
  }
};
var OpenNodeModuleFactory = class OpenNodeModuleFactory2 {
  constructor(e, f, rpcService) {
    this.e = e;
    this.f = f;
    this.nodeModuleName = ["open", "opn"];
    this.d = rpcService.getProxy($xT.MainThreadTelemetry);
    const mainThreadWindow = rpcService.getProxy($xT.MainThreadWindow);
    this.c = (target, options2) => {
      const uri = URI.parse(target);
      if (options2) {
        return this.g(target, options2);
      }
      if (uri.scheme === "http" || uri.scheme === "https") {
        return mainThreadWindow.$openUri(uri, target, { allowTunneling: true });
      } else if (uri.scheme === "mailto" || uri.scheme === this.f) {
        return mainThreadWindow.$openUri(uri, target, {});
      }
      return this.g(target, options2);
    };
  }
  load(request, parent, original) {
    const extension = this.e.findSubstr(parent);
    if (extension) {
      this.a = extension.identifier.value;
      this.h();
    }
    this.b = original(request);
    return this.c;
  }
  g(target, options2) {
    this.i();
    return this.b(target, options2);
  }
  h() {
    if (!this.a) {
      return;
    }
    this.d.$publicLog2("shimming.open", { extension: this.a });
  }
  i() {
    if (!this.a) {
      return;
    }
    this.d.$publicLog2("shimming.open.call.noForward", { extension: this.a });
  }
};
OpenNodeModuleFactory = __decorate([
  __param(2, $gW)
], OpenNodeModuleFactory);

// out-build/vs/workbench/api/node/proxyResolver.js
import { LogLevel as LogLevel2, createHttpPatch, createProxyResolver, createTlsPatch, createNetPatch, loadSystemCertificates } from "@vscode/proxy-agent";
import { createRequire } from "node:module";

// out-build/vs/platform/request/node/requestService.js
import { parse as parseUrl2 } from "url";

// out-build/vs/platform/shell/node/shellEnv.js
import { spawn as spawn7 } from "child_process";

// out-build/vs/base/node/shell.js
import { userInfo } from "os";

// out-build/vs/base/node/powershell.js
import * as os from "os";
var IntRegex = /^\d+$/;
var PwshMsixRegex = /^Microsoft.PowerShell_.*/;
var PwshPreviewMsixRegex = /^Microsoft.PowerShellPreview_.*/;
var Arch;
(function(Arch2) {
  Arch2[Arch2["x64"] = 0] = "x64";
  Arch2[Arch2["x86"] = 1] = "x86";
  Arch2[Arch2["ARM"] = 2] = "ARM";
})(Arch || (Arch = {}));
var processArch;
switch (process.arch) {
  case "ia32":
    processArch = 1;
    break;
  case "arm":
  case "arm64":
    processArch = 2;
    break;
  default:
    processArch = 0;
    break;
}
var osArch;
if (process.env["PROCESSOR_ARCHITEW6432"]) {
  osArch = process.env["PROCESSOR_ARCHITEW6432"] === "ARM64" ? 2 : 0;
} else if (process.env["PROCESSOR_ARCHITECTURE"] === "ARM64") {
  osArch = 2;
} else if (process.env["PROCESSOR_ARCHITECTURE"] === "X86") {
  osArch = 1;
} else {
  osArch = 0;
}
var PossiblePowerShellExe = class {
  constructor(exePath, displayName, a) {
    this.exePath = exePath;
    this.displayName = displayName;
    this.a = a;
  }
  async exists() {
    if (this.a === void 0) {
      this.a = await SymlinkSupport.existsFile(this.exePath);
    }
    return this.a;
  }
};
function getProgramFilesPath({ useAlternateBitness = false } = {}) {
  if (!useAlternateBitness) {
    return process.env.ProgramFiles || null;
  }
  if (processArch === 0) {
    return process.env["ProgramFiles(x86)"] || null;
  }
  if (osArch === 0) {
    return process.env.ProgramW6432 || null;
  }
  return null;
}
async function findPSCoreWindowsInstallation({ useAlternateBitness = false, findPreview = false } = {}) {
  const programFilesPath = getProgramFilesPath({ useAlternateBitness });
  if (!programFilesPath) {
    return null;
  }
  const powerShellInstallBaseDir = $nc(programFilesPath, "PowerShell");
  if (!await SymlinkSupport.existsDirectory(powerShellInstallBaseDir)) {
    return null;
  }
  let highestSeenVersion = -1;
  let pwshExePath = null;
  for (const item of await Promises2.readdir(powerShellInstallBaseDir)) {
    let currentVersion = -1;
    if (findPreview) {
      const dashIndex = item.indexOf("-");
      if (dashIndex < 0) {
        continue;
      }
      const intPart = item.substring(0, dashIndex);
      if (!IntRegex.test(intPart) || item.substring(dashIndex + 1) !== "preview") {
        continue;
      }
      currentVersion = parseInt(intPart, 10);
    } else {
      if (!IntRegex.test(item)) {
        continue;
      }
      currentVersion = parseInt(item, 10);
    }
    if (currentVersion <= highestSeenVersion) {
      continue;
    }
    const exePath = $nc(powerShellInstallBaseDir, item, "pwsh.exe");
    if (!await SymlinkSupport.existsFile(exePath)) {
      continue;
    }
    pwshExePath = exePath;
    highestSeenVersion = currentVersion;
  }
  if (!pwshExePath) {
    return null;
  }
  const bitness = programFilesPath.includes("x86") ? " (x86)" : "";
  const preview = findPreview ? " Preview" : "";
  return new PossiblePowerShellExe(pwshExePath, `PowerShell${preview}${bitness}`, true);
}
async function findPSCoreMsix({ findPreview } = {}) {
  if (!process.env.LOCALAPPDATA) {
    return null;
  }
  const msixAppDir = $nc(process.env.LOCALAPPDATA, "Microsoft", "WindowsApps");
  if (!await SymlinkSupport.existsDirectory(msixAppDir)) {
    return null;
  }
  const { pwshMsixDirRegex, pwshMsixName } = findPreview ? { pwshMsixDirRegex: PwshPreviewMsixRegex, pwshMsixName: "PowerShell Preview (Store)" } : { pwshMsixDirRegex: PwshMsixRegex, pwshMsixName: "PowerShell (Store)" };
  for (const subdir of await Promises2.readdir(msixAppDir)) {
    if (pwshMsixDirRegex.test(subdir)) {
      const pwshMsixPath = $nc(msixAppDir, subdir, "pwsh.exe");
      return new PossiblePowerShellExe(pwshMsixPath, pwshMsixName);
    }
  }
  return null;
}
function findPSCoreDotnetGlobalTool() {
  const dotnetGlobalToolExePath = $nc(os.homedir(), ".dotnet", "tools", "pwsh.exe");
  return new PossiblePowerShellExe(dotnetGlobalToolExePath, ".NET Core PowerShell Global Tool");
}
function findWinPS() {
  const winPSPath = $nc(process.env.windir, processArch === 1 && osArch !== 1 ? "SysNative" : "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
  return new PossiblePowerShellExe(winPSPath, "Windows PowerShell", true);
}
async function* enumerateDefaultPowerShellInstallations() {
  let pwshExe = await findPSCoreWindowsInstallation();
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreWindowsInstallation({ useAlternateBitness: true });
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreMsix();
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = findPSCoreDotnetGlobalTool();
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreWindowsInstallation({ findPreview: true });
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreMsix({ findPreview: true });
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = await findPSCoreWindowsInstallation({ useAlternateBitness: true, findPreview: true });
  if (pwshExe) {
    yield pwshExe;
  }
  pwshExe = findWinPS();
  if (pwshExe) {
    yield pwshExe;
  }
}
async function* $Qx() {
  for await (const defaultPwsh of enumerateDefaultPowerShellInstallations()) {
    if (await defaultPwsh.exists()) {
      yield defaultPwsh;
    }
  }
}
async function $Rx() {
  for await (const pwsh of $Qx()) {
    return pwsh;
  }
  return null;
}

// out-build/vs/base/node/shell.js
async function $Ux(os3, env2) {
  if (os3 === 1) {
    if ($l) {
      return getSystemShellWindows();
    }
    return $Sx(env2);
  }
  return getSystemShellUnixLike(os3, env2);
}
var _TERMINAL_DEFAULT_SHELL_UNIX_LIKE = null;
function getSystemShellUnixLike(os3, env2) {
  if ($n && os3 === 2 || $m && os3 === 3) {
    return "/bin/bash";
  }
  if (!_TERMINAL_DEFAULT_SHELL_UNIX_LIKE) {
    let unixLikeTerminal;
    if ($l) {
      unixLikeTerminal = "/bin/bash";
    } else {
      unixLikeTerminal = env2["SHELL"];
      if (!unixLikeTerminal) {
        try {
          unixLikeTerminal = userInfo().shell;
        } catch (err) {
        }
      }
      if (!unixLikeTerminal) {
        unixLikeTerminal = "sh";
      }
      if (unixLikeTerminal === "/bin/false") {
        unixLikeTerminal = "/bin/bash";
      }
    }
    _TERMINAL_DEFAULT_SHELL_UNIX_LIKE = unixLikeTerminal;
  }
  return _TERMINAL_DEFAULT_SHELL_UNIX_LIKE;
}
var _TERMINAL_DEFAULT_SHELL_WINDOWS = null;
async function getSystemShellWindows() {
  if (!_TERMINAL_DEFAULT_SHELL_WINDOWS) {
    _TERMINAL_DEFAULT_SHELL_WINDOWS = (await $Rx()).exePath;
  }
  return _TERMINAL_DEFAULT_SHELL_WINDOWS;
}

// out-build/vs/platform/environment/node/argvHelper.js
import assert from "assert";

// out-build/vs/platform/environment/node/argv.js
var import_minimist = __toESM(require_minimist(), 1);
var helpCategories = {
  o: localize(1744, null),
  e: localize(1745, null),
  t: localize(1746, null)
};
var $it = {
  "tunnel": {
    type: "subcommand",
    description: "Make the current machine accessible from vscode.dev or other machines through a secure tunnel",
    options: {
      "cli-data-dir": { type: "string", args: "dir", description: localize(1747, null) },
      "disable-telemetry": { type: "boolean" },
      "telemetry-level": { type: "string" },
      user: {
        type: "subcommand",
        options: {
          login: {
            type: "subcommand",
            options: {
              provider: { type: "string" },
              "access-token": { type: "string" }
            }
          }
        }
      }
    }
  },
  "serve-web": {
    type: "subcommand",
    description: "Run a server that displays the editor UI in browsers.",
    options: {
      "cli-data-dir": { type: "string", args: "dir", description: localize(1748, null) },
      "disable-telemetry": { type: "boolean" },
      "telemetry-level": { type: "string" }
    }
  },
  "diff": { type: "boolean", cat: "o", alias: "d", args: ["file", "file"], description: localize(1749, null) },
  "merge": { type: "boolean", cat: "o", alias: "m", args: ["path1", "path2", "base", "result"], description: localize(1750, null) },
  "add": { type: "boolean", cat: "o", alias: "a", args: "folder", description: localize(1751, null) },
  "goto": { type: "boolean", cat: "o", alias: "g", args: "file:line[:character]", description: localize(1752, null) },
  "new-window": { type: "boolean", cat: "o", alias: "n", description: localize(1753, null) },
  "reuse-window": { type: "boolean", cat: "o", alias: "r", description: localize(1754, null) },
  "wait": { type: "boolean", cat: "o", alias: "w", description: localize(1755, null) },
  "waitMarkerFilePath": { type: "string" },
  "locale": { type: "string", cat: "o", args: "locale", description: localize(1756, null) },
  "user-data-dir": { type: "string", cat: "o", args: "dir", description: localize(1757, null) },
  "profile": { type: "string", "cat": "o", args: "profileName", description: localize(1758, null) },
  "help": { type: "boolean", cat: "o", alias: "h", description: localize(1759, null) },
  "extensions-dir": { type: "string", deprecates: ["extensionHomePath"], cat: "e", args: "dir", description: localize(1760, null) },
  "extensions-download-dir": { type: "string" },
  "builtin-extensions-dir": { type: "string" },
  "list-extensions": { type: "boolean", cat: "e", description: localize(1761, null) },
  "show-versions": { type: "boolean", cat: "e", description: localize(1762, null) },
  "category": { type: "string", allowEmptyValue: true, cat: "e", description: localize(1763, null), args: "category" },
  "install-extension": { type: "string[]", cat: "e", args: "ext-id | path", description: localize(1764, null) },
  "pre-release": { type: "boolean", cat: "e", description: localize(1765, null) },
  "uninstall-extension": { type: "string[]", cat: "e", args: "ext-id", description: localize(1766, null) },
  "update-extensions": { type: "boolean", cat: "e", description: localize(1767, null) },
  "enable-proposed-api": { type: "string[]", allowEmptyValue: true, cat: "e", args: "ext-id", description: localize(1768, null) },
  "version": { type: "boolean", cat: "t", alias: "v", description: localize(1769, null) },
  "verbose": { type: "boolean", cat: "t", global: true, description: localize(1770, null) },
  "log": { type: "string[]", cat: "t", args: "level", global: true, description: localize(1771, null) },
  "status": { type: "boolean", alias: "s", cat: "t", description: localize(1772, null) },
  "prof-startup": { type: "boolean", cat: "t", description: localize(1773, null) },
  "prof-append-timers": { type: "string" },
  "prof-duration-markers": { type: "string[]" },
  "prof-duration-markers-file": { type: "string" },
  "no-cached-data": { type: "boolean" },
  "prof-startup-prefix": { type: "string" },
  "prof-v8-extensions": { type: "boolean" },
  "disable-extensions": { type: "boolean", deprecates: ["disableExtensions"], cat: "t", description: localize(1774, null) },
  "disable-extension": { type: "string[]", cat: "t", args: "ext-id", description: localize(1775, null) },
  "sync": { type: "string", cat: "t", description: localize(1776, null), args: ["on | off"] },
  "inspect-extensions": { type: "string", allowEmptyValue: true, deprecates: ["debugPluginHost"], args: "port", cat: "t", description: localize(1777, null) },
  "inspect-brk-extensions": { type: "string", allowEmptyValue: true, deprecates: ["debugBrkPluginHost"], args: "port", cat: "t", description: localize(1778, null) },
  "disable-lcd-text": { type: "boolean", cat: "t", description: localize(1779, null) },
  "disable-gpu": { type: "boolean", cat: "t", description: localize(1780, null) },
  "disable-chromium-sandbox": { type: "boolean", cat: "t", description: localize(1781, null) },
  "sandbox": { type: "boolean" },
  "telemetry": { type: "boolean", cat: "t", description: localize(1782, null) },
  "remote": { type: "string", allowEmptyValue: true },
  "folder-uri": { type: "string[]", cat: "o", args: "uri" },
  "file-uri": { type: "string[]", cat: "o", args: "uri" },
  "locate-extension": { type: "string[]" },
  "extensionDevelopmentPath": { type: "string[]" },
  "extensionDevelopmentKind": { type: "string[]" },
  "extensionTestsPath": { type: "string" },
  "extensionEnvironment": { type: "string" },
  "debugId": { type: "string" },
  "debugRenderer": { type: "boolean" },
  "inspect-ptyhost": { type: "string", allowEmptyValue: true },
  "inspect-brk-ptyhost": { type: "string", allowEmptyValue: true },
  "inspect-search": { type: "string", deprecates: ["debugSearch"], allowEmptyValue: true },
  "inspect-brk-search": { type: "string", deprecates: ["debugBrkSearch"], allowEmptyValue: true },
  "inspect-sharedprocess": { type: "string", allowEmptyValue: true },
  "inspect-brk-sharedprocess": { type: "string", allowEmptyValue: true },
  "export-default-configuration": { type: "string" },
  "install-source": { type: "string" },
  "enable-smoke-test-driver": { type: "boolean" },
  "logExtensionHostCommunication": { type: "boolean" },
  "skip-release-notes": { type: "boolean" },
  "skip-welcome": { type: "boolean" },
  "disable-telemetry": { type: "boolean" },
  "disable-updates": { type: "boolean" },
  "use-inmemory-secretstorage": { type: "boolean", deprecates: ["disable-keytar"] },
  "password-store": { type: "string" },
  "disable-workspace-trust": { type: "boolean" },
  "disable-crash-reporter": { type: "boolean" },
  "crash-reporter-directory": { type: "string" },
  "crash-reporter-id": { type: "string" },
  "skip-add-to-recently-opened": { type: "boolean" },
  "open-url": { type: "boolean" },
  "file-write": { type: "boolean" },
  "file-chmod": { type: "boolean" },
  "install-builtin-extension": { type: "string[]" },
  "force": { type: "boolean" },
  "do-not-sync": { type: "boolean" },
  "trace": { type: "boolean" },
  "trace-category-filter": { type: "string" },
  "trace-options": { type: "string" },
  "preserve-env": { type: "boolean" },
  "force-user-env": { type: "boolean" },
  "force-disable-user-env": { type: "boolean" },
  "open-devtools": { type: "boolean" },
  "disable-gpu-sandbox": { type: "boolean" },
  "logsPath": { type: "string" },
  "__enable-file-policy": { type: "boolean" },
  "editSessionId": { type: "string" },
  "continueOn": { type: "string" },
  "locate-shell-integration-path": { type: "string", args: ["bash", "pwsh", "zsh", "fish"] },
  "enable-coi": { type: "boolean" },
  // chromium flags
  "no-proxy-server": { type: "boolean" },
  // Minimist incorrectly parses keys that start with `--no`
  // https://github.com/substack/minimist/blob/aeb3e27dae0412de5c0494e9563a5f10c82cc7a9/index.js#L118-L121
  // If --no-sandbox is passed via cli wrapper it will be treated as --sandbox which is incorrect, we use
  // the alias here to make sure --no-sandbox is always respected.
  // For https://github.com/microsoft/vscode/issues/128279
  "no-sandbox": { type: "boolean", alias: "sandbox" },
  "proxy-server": { type: "string" },
  "proxy-bypass-list": { type: "string" },
  "proxy-pac-url": { type: "string" },
  "js-flags": { type: "string" },
  // chrome js flags
  "inspect": { type: "string", allowEmptyValue: true },
  "inspect-brk": { type: "string", allowEmptyValue: true },
  "nolazy": { type: "boolean" },
  // node inspect
  "force-device-scale-factor": { type: "string" },
  "force-renderer-accessibility": { type: "boolean" },
  "ignore-certificate-errors": { type: "boolean" },
  "allow-insecure-localhost": { type: "boolean" },
  "log-net-log": { type: "string" },
  "vmodule": { type: "string" },
  "_urls": { type: "string[]" },
  "disable-dev-shm-usage": { type: "boolean" },
  "profile-temp": { type: "boolean" },
  "ozone-platform": { type: "string" },
  "enable-tracing": { type: "string" },
  "trace-startup-format": { type: "string" },
  "trace-startup-file": { type: "string" },
  "trace-startup-duration": { type: "string" },
  _: { type: "string[]" }
  // main arguments
};

// out-build/vs/platform/environment/node/argvHelper.js
function $qt(env2) {
  return env2["VSCODE_CLI"] === "1";
}

// out-build/vs/platform/shell/node/shellEnv.js
var unixShellEnvPromise = void 0;
async function $Vx(configurationService, logService, args2, env2) {
  if (args2["force-disable-user-env"]) {
    logService.trace("resolveShellEnv(): skipped (--force-disable-user-env)");
    return {};
  } else if ($l) {
    logService.trace("resolveShellEnv(): skipped (Windows)");
    return {};
  } else if ($qt(env2) && !args2["force-user-env"]) {
    logService.trace("resolveShellEnv(): skipped (VSCODE_CLI is set)");
    return {};
  } else {
    if ($qt(env2)) {
      logService.trace("resolveShellEnv(): running (--force-user-env)");
    } else {
      logService.trace("resolveShellEnv(): running (macOS/Linux)");
    }
    if (!unixShellEnvPromise) {
      unixShellEnvPromise = Promises.withAsyncBody(async (resolve, reject) => {
        const cts = new $ad();
        let timeoutValue = 1e4;
        const configuredTimeoutValue = configurationService.getValue("application.shellEnvironmentResolutionTimeout");
        if (typeof configuredTimeoutValue === "number") {
          timeoutValue = $4i(configuredTimeoutValue, 1, 120) * 1e3;
        }
        const timeout = setTimeout(() => {
          cts.dispose(true);
          reject(new Error(localize(2103, null)));
        }, timeoutValue);
        try {
          resolve(await doResolveUnixShellEnv(logService, cts.token));
        } catch (error) {
          if (!$kb(error) && !cts.token.isCancellationRequested) {
            reject(new Error(localize(2104, null, $1m(error))));
          } else {
            resolve({});
          }
        } finally {
          clearTimeout(timeout);
          cts.dispose();
        }
      });
    }
    return unixShellEnvPromise;
  }
}
async function doResolveUnixShellEnv(logService, token) {
  const runAsNode = process.env["ELECTRON_RUN_AS_NODE"];
  logService.trace("getUnixShellEnvironment#runAsNode", runAsNode);
  const noAttach = process.env["ELECTRON_NO_ATTACH_CONSOLE"];
  logService.trace("getUnixShellEnvironment#noAttach", noAttach);
  const mark = $ps().replace(/-/g, "").substr(0, 12);
  const regex = new RegExp(mark + "({.*})" + mark);
  const env2 = {
    ...process.env,
    ELECTRON_RUN_AS_NODE: "1",
    ELECTRON_NO_ATTACH_CONSOLE: "1",
    VSCODE_RESOLVING_ENVIRONMENT: "1"
  };
  logService.trace("getUnixShellEnvironment#env", env2);
  const systemShellUnix = await $Ux(OS, env2);
  logService.trace("getUnixShellEnvironment#shell", systemShellUnix);
  return new Promise((resolve, reject) => {
    if (token.isCancellationRequested) {
      return reject(new $lb());
    }
    const name = $rc(systemShellUnix);
    let command, shellArgs;
    const extraArgs = "";
    if (/^pwsh(-preview)?$/.test(name)) {
      command = `& '${process.execPath}' ${extraArgs} -p '''${mark}'' + JSON.stringify(process.env) + ''${mark}'''`;
      shellArgs = ["-Login", "-Command"];
    } else if (name === "nu") {
      command = `^'${process.execPath}' ${extraArgs} -p '"${mark}" + JSON.stringify(process.env) + "${mark}"'`;
      shellArgs = ["-i", "-l", "-c"];
    } else if (name === "xonsh") {
      command = `import os, json; print("${mark}", json.dumps(dict(os.environ)), "${mark}")`;
      shellArgs = ["-i", "-l", "-c"];
    } else {
      command = `'${process.execPath}' ${extraArgs} -p '"${mark}" + JSON.stringify(process.env) + "${mark}"'`;
      if (name === "tcsh" || name === "csh") {
        shellArgs = ["-ic"];
      } else {
        shellArgs = ["-i", "-l", "-c"];
      }
    }
    logService.trace("getUnixShellEnvironment#spawn", JSON.stringify(shellArgs), command);
    const child = spawn7(systemShellUnix, [...shellArgs, command], {
      detached: true,
      stdio: ["ignore", "pipe", "pipe"],
      env: env2
    });
    token.onCancellationRequested(() => {
      child.kill();
      return reject(new $lb());
    });
    child.on("error", (err) => {
      logService.error("getUnixShellEnvironment#errorChildProcess", $1m(err));
      reject(err);
    });
    const buffers = [];
    child.stdout.on("data", (b) => buffers.push(b));
    const stderr = [];
    child.stderr.on("data", (b) => stderr.push(b));
    child.on("close", (code, signal) => {
      const raw = Buffer.concat(buffers).toString("utf8");
      logService.trace("getUnixShellEnvironment#raw", raw);
      const stderrStr = Buffer.concat(stderr).toString("utf8");
      if (stderrStr.trim()) {
        logService.trace("getUnixShellEnvironment#stderr", stderrStr);
      }
      if (code || signal) {
        return reject(new Error(localize(2105, null, code, signal)));
      }
      const match = regex.exec(raw);
      const rawStripped = match ? match[1] : "{}";
      try {
        const env3 = JSON.parse(rawStripped);
        if (runAsNode) {
          env3["ELECTRON_RUN_AS_NODE"] = runAsNode;
        } else {
          delete env3["ELECTRON_RUN_AS_NODE"];
        }
        if (noAttach) {
          env3["ELECTRON_NO_ATTACH_CONSOLE"] = noAttach;
        } else {
          delete env3["ELECTRON_NO_ATTACH_CONSOLE"];
        }
        delete env3["VSCODE_RESOLVING_ENVIRONMENT"];
        delete env3["XDG_RUNTIME_DIR"];
        logService.trace("getUnixShellEnvironment#result", env3);
        resolve(env3);
      } catch (err) {
        logService.error("getUnixShellEnvironment#errorCaught", $1m(err));
        reject(err);
      }
    });
  });
}

// out-build/vs/platform/request/node/proxy.js
import { parse as parseUrl } from "url";
function getSystemProxyURI(requestURL, env2) {
  if (requestURL.protocol === "http:") {
    return env2.HTTP_PROXY || env2.http_proxy || null;
  } else if (requestURL.protocol === "https:") {
    return env2.HTTPS_PROXY || env2.https_proxy || env2.HTTP_PROXY || env2.http_proxy || null;
  }
  return null;
}
async function $JC(rawRequestURL, env2, options2 = {}) {
  const requestURL = parseUrl(rawRequestURL);
  const proxyURL = options2.proxyUrl || getSystemProxyURI(requestURL, env2);
  if (!proxyURL) {
    return null;
  }
  const proxyEndpoint = parseUrl(proxyURL);
  if (!/^https?:$/.test(proxyEndpoint.protocol || "")) {
    return null;
  }
  const opts = {
    host: proxyEndpoint.hostname || "",
    port: (proxyEndpoint.port ? +proxyEndpoint.port : 0) || (proxyEndpoint.protocol === "https" ? 443 : 80),
    auth: proxyEndpoint.auth,
    rejectUnauthorized: $Fg(options2.strictSSL) ? options2.strictSSL : true
  };
  if (requestURL.protocol === "http:") {
    const { default: mod } = await import("http-proxy-agent");
    return new mod.HttpProxyAgent(proxyURL, opts);
  } else {
    const { default: mod } = await import("https-proxy-agent");
    return new mod.HttpsProxyAgent(proxyURL, opts);
  }
}

// out-build/vs/platform/request/node/requestService.js
import { createGunzip } from "zlib";
var $KC = class $KC2 extends $0u {
  constructor(m, n, logService) {
    super(logService);
    this.m = m;
    this.n = n;
    this.r();
    this.B(m.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("http")) {
        this.r();
      }
    }));
  }
  r() {
    const config = this.m.getValue("http");
    this.f = config?.proxy;
    this.g = !!config?.proxyStrictSSL;
    this.h = config?.proxyAuthorization;
  }
  async request(options2, token) {
    const { f: proxyUrl, g: strictSSL } = this;
    let shellEnv = void 0;
    try {
      shellEnv = await $Vx(this.m, this.b, this.n.args, process.env);
    } catch (error) {
      if (!this.j) {
        this.j = true;
        this.b.error(`resolving shell environment failed`, $qb(error));
      }
    }
    const env2 = {
      ...process.env,
      ...shellEnv
    };
    const agent = options2.agent ? options2.agent : await $JC(options2.url || "", env2, { proxyUrl, strictSSL });
    options2.agent = agent;
    options2.strictSSL = strictSSL;
    if (this.h) {
      options2.headers = {
        ...options2.headers || {},
        "Proxy-Authorization": this.h
      };
    }
    return this.c(options2, () => $MC(options2, token));
  }
  async resolveProxy(url) {
    return void 0;
  }
  async lookupAuthorization(authInfo) {
    return void 0;
  }
  async lookupKerberosAuthorization(urlStr) {
    try {
      const spnConfig = this.m.getValue("http.proxyKerberosServicePrincipal");
      const response = await $LC(urlStr, spnConfig, this.b, "RequestService#lookupKerberosAuthorization");
      return "Negotiate " + response;
    } catch (err) {
      this.b.debug("RequestService#lookupKerberosAuthorization Kerberos authentication failed", err);
      return void 0;
    }
  }
  async loadCertificates() {
    const proxyAgent2 = await import("@vscode/proxy-agent");
    return proxyAgent2.loadSystemCertificates({ log: this.b });
  }
};
$KC = __decorate([
  __param(0, $kl),
  __param(1, $Yk),
  __param(2, $wn)
], $KC);
async function $LC(urlStr, spnConfig, logService, logPrefix) {
  const importKerberos = await import("kerberos");
  const kerberos = importKerberos.default || importKerberos;
  const url = new URL(urlStr);
  const spn = spnConfig || (process.platform === "win32" ? `HTTP/${url.hostname}` : `HTTP@${url.hostname}`);
  logService.debug(`${logPrefix} Kerberos authentication lookup`, `proxyURL:${url}`, `spn:${spn}`);
  const client = await kerberos.initializeClient(spn);
  return client.step("");
}
async function getNodeRequest(options2) {
  const endpoint = parseUrl2(options2.url);
  const module2 = endpoint.protocol === "https:" ? await import("https") : await import("http");
  return module2.request;
}
async function $MC(options2, token) {
  return Promises.withAsyncBody(async (resolve, reject) => {
    const endpoint = parseUrl2(options2.url);
    const rawRequest = options2.getRawRequest ? options2.getRawRequest(options2) : await getNodeRequest(options2);
    const opts = {
      hostname: endpoint.hostname,
      port: endpoint.port ? parseInt(endpoint.port) : endpoint.protocol === "https:" ? 443 : 80,
      protocol: endpoint.protocol,
      path: endpoint.path,
      method: options2.type || "GET",
      headers: options2.headers,
      agent: options2.agent,
      rejectUnauthorized: $Fg(options2.strictSSL) ? options2.strictSSL : true
    };
    if (options2.user && options2.password) {
      opts.auth = options2.user + ":" + options2.password;
    }
    const req = rawRequest(opts, (res) => {
      const followRedirects = $Dg(options2.followRedirects) ? options2.followRedirects : 3;
      if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && followRedirects > 0 && res.headers["location"]) {
        $MC({
          ...options2,
          url: res.headers["location"],
          followRedirects: followRedirects - 1
        }, token).then(resolve, reject);
      } else {
        let stream = res;
        if (!options2.isChromiumNetwork && res.headers["content-encoding"] === "gzip") {
          stream = res.pipe(createGunzip());
        }
        resolve({ res, stream: $Ri(stream) });
      }
    });
    req.on("error", reject);
    if (options2.timeout) {
      req.setTimeout(options2.timeout);
    }
    if (options2.isChromiumNetwork) {
      req.removeHeader("Content-Length");
    }
    if (options2.data) {
      if (typeof options2.data === "string") {
        req.write(options2.data);
      }
    }
    req.end();
    token.onCancellationRequested(() => {
      req.abort();
      reject(new $lb());
    });
  });
}

// out-build/vs/workbench/api/node/proxyResolver.js
import * as proxyAgent from "@vscode/proxy-agent";
var require2 = createRequire(import.meta.url);
var http = require2("http");
var https = require2("https");
var tls = require2("tls");
var net2 = require2("net");
var systemCertificatesV2Default = false;
var useElectronFetchDefault = false;
function $Azc(extHostWorkspace, configProvider, extensionService, extHostLogService, mainThreadTelemetry, initData, disposables) {
  const useHostProxy = initData.environment.useHostProxy;
  const doUseHostProxy = typeof useHostProxy === "boolean" ? useHostProxy : !initData.remote.isRemote;
  const params = {
    resolveProxy: (url) => extHostWorkspace.resolveProxy(url),
    lookupProxyAuthorization: lookupProxyAuthorization.bind(void 0, extHostWorkspace, extHostLogService, mainThreadTelemetry, configProvider, {}, {}, initData.remote.isRemote, doUseHostProxy),
    getProxyURL: () => configProvider.getConfiguration("http").get("proxy"),
    getProxySupport: () => configProvider.getConfiguration("http").get("proxySupport") || "off",
    getNoProxyConfig: () => configProvider.getConfiguration("http").get("noProxy") || [],
    isAdditionalFetchSupportEnabled: () => configProvider.getConfiguration("http").get("fetchAdditionalSupport", true),
    addCertificatesV1: () => certSettingV1(configProvider),
    addCertificatesV2: () => certSettingV2(configProvider),
    log: extHostLogService,
    getLogLevel: () => {
      const level = extHostLogService.getLevel();
      switch (level) {
        case LogLevel.Trace:
          return LogLevel2.Trace;
        case LogLevel.Debug:
          return LogLevel2.Debug;
        case LogLevel.Info:
          return LogLevel2.Info;
        case LogLevel.Warning:
          return LogLevel2.Warning;
        case LogLevel.Error:
          return LogLevel2.Error;
        case LogLevel.Off:
          return LogLevel2.Off;
        default:
          return never(level);
      }
      function never(level2) {
        extHostLogService.error("Unknown log level", level2);
        return LogLevel2.Debug;
      }
    },
    proxyResolveTelemetry: () => {
    },
    useHostProxy: doUseHostProxy,
    loadAdditionalCertificates: async () => {
      const promises8 = [];
      if (initData.remote.isRemote) {
        promises8.push(loadSystemCertificates({ log: extHostLogService }));
      }
      if (doUseHostProxy) {
        extHostLogService.trace("ProxyResolver#loadAdditionalCertificates: Loading certificates from main process");
        const certs = extHostWorkspace.loadCertificates();
        certs.then((certs2) => extHostLogService.trace("ProxyResolver#loadAdditionalCertificates: Loaded certificates from main process", certs2.length));
        promises8.push(certs);
      }
      if (initData.environment.extensionTestsLocationURI && https.globalAgent.testCertificates?.length) {
        extHostLogService.trace("ProxyResolver#loadAdditionalCertificates: Loading test certificates");
        promises8.push(Promise.resolve(https.globalAgent.testCertificates));
      }
      return (await Promise.all(promises8)).flat();
    },
    env: process.env
  };
  const { resolveProxyWithRequest, resolveProxyURL } = createProxyResolver(params);
  const target = proxyAgent.default || proxyAgent;
  target.resolveProxyURL = resolveProxyURL;
  patchGlobalFetch(params, configProvider, mainThreadTelemetry, initData, resolveProxyURL, disposables);
  const lookup = createPatchedModules(params, resolveProxyWithRequest);
  return configureModuleLoading(extensionService, lookup);
}
var unsafeHeaders = [
  "content-length",
  "host",
  "trailer",
  "te",
  "upgrade",
  "cookie2",
  "keep-alive",
  "transfer-encoding",
  "set-cookie"
];
function patchGlobalFetch(params, configProvider, mainThreadTelemetry, initData, resolveProxyURL, disposables) {
  if (!globalThis.__vscodeOriginalFetch) {
    const originalFetch = globalThis.fetch;
    globalThis.__vscodeOriginalFetch = originalFetch;
    const patchedFetch = proxyAgent.createFetchPatch(params, originalFetch, resolveProxyURL);
    globalThis.__vscodePatchedFetch = patchedFetch;
    let useElectronFetch = false;
    if (!initData.remote.isRemote) {
      useElectronFetch = configProvider.getConfiguration("http").get("electronFetch", useElectronFetchDefault);
      disposables.add(configProvider.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("http.electronFetch")) {
          useElectronFetch = configProvider.getConfiguration("http").get("electronFetch", useElectronFetchDefault);
        }
      }));
    }
    globalThis.fetch = async function fetch(input, init) {
      function getRequestProperty(name) {
        return init && name in init ? init[name] : typeof input === "object" && "cache" in input ? input[name] : void 0;
      }
      const urlString = typeof input === "string" ? input : "cache" in input ? input.url : input.toString();
      const isDataUrl = urlString.startsWith("data:");
      if (isDataUrl) {
        recordFetchFeatureUse(mainThreadTelemetry, "data");
      }
      const isBlobUrl = urlString.startsWith("blob:");
      if (isBlobUrl) {
        recordFetchFeatureUse(mainThreadTelemetry, "blob");
      }
      const isManualRedirect = getRequestProperty("redirect") === "manual";
      if (isManualRedirect) {
        recordFetchFeatureUse(mainThreadTelemetry, "manualRedirect");
      }
      const integrity = getRequestProperty("integrity");
      if (integrity) {
        recordFetchFeatureUse(mainThreadTelemetry, "integrity");
      }
      if (!useElectronFetch || isDataUrl || isBlobUrl || isManualRedirect || integrity) {
        const response2 = await patchedFetch(input, init);
        monitorResponseProperties(mainThreadTelemetry, response2, urlString);
        return response2;
      }
      if (init?.headers) {
        const headers = new Headers(init.headers);
        for (const header of unsafeHeaders) {
          headers.delete(header);
        }
        init = { ...init, headers };
      }
      const electronInput = input instanceof URL ? input.toString() : input;
      const electron = require2("electron");
      const response = await electron.net.fetch(electronInput, init);
      monitorResponseProperties(mainThreadTelemetry, response, urlString);
      return response;
    };
  }
}
function monitorResponseProperties(mainThreadTelemetry, response, urlString) {
  const originalUrl = response.url;
  Object.defineProperty(response, "url", {
    get() {
      recordFetchFeatureUse(mainThreadTelemetry, "url");
      return originalUrl || urlString;
    }
  });
  const originalType = response.type;
  Object.defineProperty(response, "type", {
    get() {
      recordFetchFeatureUse(mainThreadTelemetry, "typeProperty");
      return originalType !== "default" ? originalType : "basic";
    }
  });
}
var fetchFeatureUse = {
  url: 0,
  typeProperty: 0,
  data: 0,
  blob: 0,
  integrity: 0,
  manualRedirect: 0
};
var timer;
function recordFetchFeatureUse(mainThreadTelemetry, feature) {
  if (!fetchFeatureUse[feature]++) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      mainThreadTelemetry.$publicLog2("fetchFeatureUse", fetchFeatureUse);
    }, 1e4);
    timer.unref();
  }
}
function createPatchedModules(params, resolveProxy) {
  function mergeModules(module2, patch2) {
    const target = module2.default || module2;
    target.__vscodeOriginal = Object.assign({}, target);
    return Object.assign(target, patch2);
  }
  return {
    http: mergeModules(http, createHttpPatch(params, http, resolveProxy)),
    https: mergeModules(https, createHttpPatch(params, https, resolveProxy)),
    net: mergeModules(net2, createNetPatch(params, net2)),
    tls: mergeModules(tls, createTlsPatch(params, tls))
  };
}
function certSettingV1(configProvider) {
  const http3 = configProvider.getConfiguration("http");
  return !http3.get("experimental.systemCertificatesV2", systemCertificatesV2Default) && !!http3.get("systemCertificates");
}
function certSettingV2(configProvider) {
  const http3 = configProvider.getConfiguration("http");
  return !!http3.get("experimental.systemCertificatesV2", systemCertificatesV2Default) && !!http3.get("systemCertificates");
}
var modulesCache = /* @__PURE__ */ new Map();
function configureModuleLoading(extensionService, lookup) {
  return extensionService.getExtensionPathIndex().then((extensionPaths) => {
    const node_module = require2("module");
    const original = node_module._load;
    node_module._load = function load(request, parent, isMain) {
      if (request === "net") {
        return lookup.net;
      }
      if (request === "tls") {
        return lookup.tls;
      }
      if (request !== "http" && request !== "https" && request !== "undici") {
        return original.apply(this, arguments);
      }
      const ext = extensionPaths.findSubstr(URI.file(parent.filename));
      let cache = modulesCache.get(ext);
      if (!cache) {
        modulesCache.set(ext, cache = {});
      }
      if (!cache[request]) {
        if (request === "undici") {
          const undici = original.apply(this, arguments);
          proxyAgent.patchUndici(undici);
          cache[request] = undici;
        } else {
          const mod = lookup[request];
          cache[request] = { ...mod };
        }
      }
      return cache[request];
    };
  });
}
async function lookupProxyAuthorization(extHostWorkspace, extHostLogService, mainThreadTelemetry, configProvider, proxyAuthenticateCache, basicAuthCache, isRemote, useHostProxy, proxyURL, proxyAuthenticate, state) {
  const cached = proxyAuthenticateCache[proxyURL];
  if (proxyAuthenticate) {
    proxyAuthenticateCache[proxyURL] = proxyAuthenticate;
  }
  extHostLogService.trace("ProxyResolver#lookupProxyAuthorization callback", `proxyURL:${proxyURL}`, `proxyAuthenticate:${proxyAuthenticate}`, `proxyAuthenticateCache:${cached}`);
  const header = proxyAuthenticate || cached;
  const authenticate = Array.isArray(header) ? header : typeof header === "string" ? [header] : [];
  sendTelemetry(mainThreadTelemetry, authenticate, isRemote);
  if (authenticate.some((a) => /^(Negotiate|Kerberos)( |$)/i.test(a)) && !state.kerberosRequested) {
    state.kerberosRequested = true;
    try {
      const spnConfig = configProvider.getConfiguration("http").get("proxyKerberosServicePrincipal");
      const response = await $LC(proxyURL, spnConfig, extHostLogService, "ProxyResolver#lookupProxyAuthorization");
      return "Negotiate " + response;
    } catch (err) {
      extHostLogService.debug("ProxyResolver#lookupProxyAuthorization Kerberos authentication failed", err);
    }
    if (isRemote && useHostProxy) {
      extHostLogService.debug("ProxyResolver#lookupProxyAuthorization Kerberos authentication lookup on host", `proxyURL:${proxyURL}`);
      const auth = await extHostWorkspace.lookupKerberosAuthorization(proxyURL);
      if (auth) {
        return "Negotiate " + auth;
      }
    }
  }
  const basicAuthHeader = authenticate.find((a) => /^Basic( |$)/i.test(a));
  if (basicAuthHeader) {
    try {
      const cachedAuth = basicAuthCache[proxyURL];
      if (cachedAuth) {
        if (state.basicAuthCacheUsed) {
          extHostLogService.debug("ProxyResolver#lookupProxyAuthorization Basic authentication deleting cached credentials", `proxyURL:${proxyURL}`);
          delete basicAuthCache[proxyURL];
        } else {
          extHostLogService.debug("ProxyResolver#lookupProxyAuthorization Basic authentication using cached credentials", `proxyURL:${proxyURL}`);
          state.basicAuthCacheUsed = true;
          return cachedAuth;
        }
      }
      state.basicAuthAttempt = (state.basicAuthAttempt || 0) + 1;
      const realm = / realm="([^"]+)"/i.exec(basicAuthHeader)?.[1];
      extHostLogService.debug("ProxyResolver#lookupProxyAuthorization Basic authentication lookup", `proxyURL:${proxyURL}`, `realm:${realm}`);
      const url = new URL(proxyURL);
      const authInfo = {
        scheme: "basic",
        host: url.hostname,
        port: Number(url.port),
        realm: realm || "",
        isProxy: true,
        attempt: state.basicAuthAttempt
      };
      const credentials = await extHostWorkspace.lookupAuthorization(authInfo);
      if (credentials) {
        extHostLogService.debug("ProxyResolver#lookupProxyAuthorization Basic authentication received credentials", `proxyURL:${proxyURL}`, `realm:${realm}`);
        const auth = "Basic " + Buffer.from(`${credentials.username}:${credentials.password}`).toString("base64");
        basicAuthCache[proxyURL] = auth;
        return auth;
      } else {
        extHostLogService.debug("ProxyResolver#lookupProxyAuthorization Basic authentication received no credentials", `proxyURL:${proxyURL}`, `realm:${realm}`);
      }
    } catch (err) {
      extHostLogService.error("ProxyResolver#lookupProxyAuthorization Basic authentication failed", err);
    }
  }
  return void 0;
}
var telemetrySent = false;
function sendTelemetry(mainThreadTelemetry, authenticate, isRemote) {
  if (telemetrySent || !authenticate.length) {
    return;
  }
  telemetrySent = true;
  mainThreadTelemetry.$publicLog2("proxyAuthenticationRequest", {
    authenticationType: authenticate.map((a) => a.split(" ")[0]).join(","),
    extensionHostType: isRemote ? "remote" : "local"
  });
}

// out-build/vs/workbench/api/node/extHostDownloadService.js
import { tmpdir as tmpdir3 } from "os";
var $Bzc = class $Bzc2 extends $3c {
  constructor(extHostRpc, commands) {
    super();
    const proxy = extHostRpc.getProxy($xT.MainThreadDownloadService);
    commands.registerCommand(false, "_workbench.downloadResource", async (resource) => {
      const location2 = URI.file($nc(tmpdir3(), $ps()));
      await proxy.$download(resource, location2);
      return location2;
    });
  }
};
$Bzc = __decorate([
  __param(0, $gW),
  __param(1, $CW)
], $Bzc);

// out-build/vs/workbench/api/node/extHostCLIServer.js
import * as http2 from "http";
import * as fs4 from "fs";
var $HW = class {
  constructor(b, c, f) {
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = http2.createServer((req, res) => this.h(req, res));
    this.g().catch((err) => {
      c.error(err);
      return "";
    });
  }
  get ipcHandlePath() {
    return this.f;
  }
  async g() {
    try {
      this.a.listen(this.ipcHandlePath);
      this.a.on("error", (err) => this.c.error(err));
    } catch (err) {
      this.c.error("Could not start open from terminal server.");
    }
    return this.f;
  }
  h(req, res) {
    const sendResponse = (statusCode, returnObj) => {
      res.writeHead(statusCode, { "content-type": "application/json" });
      res.end(JSON.stringify(returnObj || null), (err) => err && this.c.error(err));
    };
    const chunks = [];
    req.setEncoding("utf8");
    req.on("data", (d) => chunks.push(d));
    req.on("end", async () => {
      try {
        const data = JSON.parse(chunks.join(""));
        let returnObj;
        switch (data.type) {
          case "open":
            returnObj = await this.i(data);
            break;
          case "openExternal":
            returnObj = await this.j(data);
            break;
          case "status":
            returnObj = await this.l(data);
            break;
          case "extensionManagement":
            returnObj = await this.k(data);
            break;
          default:
            sendResponse(404, `Unknown message type: ${data.type}`);
            break;
        }
        sendResponse(200, returnObj);
      } catch (e) {
        const message = e instanceof Error ? e.message : JSON.stringify(e);
        sendResponse(500, message);
        this.c.error("Error while processing pipe request", e);
      }
    });
  }
  async i(data) {
    const { fileURIs, folderURIs, forceNewWindow, diffMode, mergeMode, addMode, forceReuseWindow, gotoLineMode, waitMarkerFilePath, remoteAuthority } = data;
    const urisToOpen = [];
    if (Array.isArray(folderURIs)) {
      for (const s of folderURIs) {
        try {
          urisToOpen.push({ folderUri: URI.parse(s) });
        } catch (e) {
        }
      }
    }
    if (Array.isArray(fileURIs)) {
      for (const s of fileURIs) {
        try {
          if ($jl(s)) {
            urisToOpen.push({ workspaceUri: URI.parse(s) });
          } else {
            urisToOpen.push({ fileUri: URI.parse(s) });
          }
        } catch (e) {
        }
      }
    }
    const waitMarkerFileURI = waitMarkerFilePath ? URI.file(waitMarkerFilePath) : void 0;
    const preferNewWindow = !forceReuseWindow && !waitMarkerFileURI && !addMode;
    const windowOpenArgs = { forceNewWindow, diffMode, mergeMode, addMode, gotoLineMode, forceReuseWindow, preferNewWindow, waitMarkerFileURI, remoteAuthority };
    this.b.executeCommand("_remoteCLI.windowOpen", urisToOpen, windowOpenArgs);
  }
  async j(data) {
    for (const uriString of data.uris) {
      const uri = URI.parse(uriString);
      const urioOpen = uri.scheme === "file" ? uri : uriString;
      await this.b.executeCommand("_remoteCLI.openExternal", urioOpen);
    }
  }
  async k(data) {
    const toExtOrVSIX = (inputs) => inputs?.map((input) => /\.vsix$/i.test(input) ? URI.parse(input) : input);
    const commandArgs = {
      list: data.list,
      install: toExtOrVSIX(data.install),
      uninstall: toExtOrVSIX(data.uninstall),
      force: data.force
    };
    return await this.b.executeCommand("_remoteCLI.manageExtensions", commandArgs);
  }
  async l(data) {
    return await this.b.executeCommand("_remoteCLI.getSystemStatus");
  }
  dispose() {
    this.a.close();
    if (this.f && process.platform !== "win32" && fs4.existsSync(this.f)) {
      fs4.unlinkSync(this.f);
    }
  }
};
var $IW = class $IW2 extends $HW {
  constructor(commands, logService) {
    super(commands, logService, $xu());
  }
};
$IW = __decorate([
  __param(0, $CW),
  __param(1, $wn)
], $IW);

// out-build/vs/workbench/api/common/extHostConsoleForwarder.js
var $3yc = class $3yc2 {
  constructor(extHostRpc, initData) {
    this.a = extHostRpc.getProxy($xT.MainThreadConsole);
    this.b = initData.consoleForward.includeStack;
    this.c = initData.consoleForward.logNative;
    this.d("info", "log");
    this.d("log", "log");
    this.d("warn", "warn");
    this.d("debug", "debug");
    this.d("error", "error");
  }
  /**
   * Wraps a console message so that it is transmitted to the renderer. If
   * native logging is turned on, the original console message will be written
   * as well. This is needed since the console methods are "magic" in V8 and
   * are the only methods that allow later introspection of logged variables.
   *
   * The wrapped property is not defined with `writable: false` to avoid
   * throwing errors, but rather a no-op setting. See https://github.com/microsoft/vscode-extension-telemetry/issues/88
   */
  d(method, severity) {
    const that = this;
    const original = console[method];
    Object.defineProperty(console, method, {
      set: () => {
      },
      get: () => function() {
        that.e(method, severity, original, arguments);
      }
    });
  }
  e(method, severity, original, args2) {
    this.a.$logExtensionHostMessage({
      type: "__$console",
      severity,
      arguments: safeStringifyArgumentsToArray(args2, this.b)
    });
    if (this.c) {
      this.f(method, original, args2);
    }
  }
};
$3yc = __decorate([
  __param(0, $gW),
  __param(1, $wW)
], $3yc);
var MAX_LENGTH = 1e5;
function safeStringifyArgumentsToArray(args2, includeStack) {
  const argsArray = [];
  if (args2.length) {
    for (let i = 0; i < args2.length; i++) {
      let arg = args2[i];
      if (typeof arg === "undefined") {
        arg = "undefined";
      } else if (arg instanceof Error) {
        const errorObj = arg;
        if (errorObj.stack) {
          arg = errorObj.stack;
        } else {
          arg = errorObj.toString();
        }
      }
      argsArray.push(arg);
    }
  }
  if (includeStack) {
    const stack = new Error().stack;
    if (stack) {
      argsArray.push({ __$stack: stack.split("\n").slice(3).join("\n") });
    }
  }
  try {
    const res = $Qv(argsArray);
    if (res.length > MAX_LENGTH) {
      return "Output omitted for a large object that exceeds the limits";
    }
    return res;
  } catch (error) {
    return `Output omitted for an object that cannot be inspected ('${error.toString()}')`;
  }
}

// out-build/vs/workbench/api/node/extHostConsoleForwarder.js
var MAX_STREAM_BUFFER_LENGTH = 1024 * 1024;
var $Czc = class $Czc2 extends $3yc {
  constructor(extHostRpc, initData) {
    super(extHostRpc, initData);
    this.g = false;
    this.j("stderr", "error");
    this.j("stdout", "log");
  }
  f(method, original, args2) {
    const stream = method === "error" || method === "warn" ? process.stderr : process.stdout;
    this.g = true;
    stream.write(`
${"START_NATIVE_LOG"}
`);
    original.apply(console, args2);
    stream.write(`
${"END_NATIVE_LOG"}
`);
    this.g = false;
  }
  /**
   * Wraps process.stderr/stdout.write() so that it is transmitted to the
   * renderer or CLI. It both calls through to the original method as well
   * as to console.log with complete lines so that they're made available
   * to the debugger/CLI.
   */
  j(streamName, severity) {
    const stream = process[streamName];
    const original = stream.write;
    let buf = "";
    Object.defineProperty(stream, "write", {
      set: () => {
      },
      get: () => (chunk, encoding, callback) => {
        if (!this.g) {
          buf += chunk.toString(encoding);
          const eol = buf.length > MAX_STREAM_BUFFER_LENGTH ? buf.length : buf.lastIndexOf("\n");
          if (eol !== -1) {
            console[severity](buf.slice(0, eol));
            buf = buf.slice(eol + 1);
          }
        }
        original.call(stream, chunk, encoding, callback);
      }
    });
  }
};
$Czc = __decorate([
  __param(0, $gW),
  __param(1, $wW)
], $Czc);

// out-build/vs/platform/files/node/diskFileSystemProvider.js
import { promises as promises5 } from "fs";

// out-build/vs/platform/files/common/io.js
async function $ey(provider, resource, target, transformer, options2, token) {
  let error = void 0;
  try {
    await doReadFileIntoStream(provider, resource, target, transformer, options2, token);
  } catch (err) {
    error = err;
  } finally {
    if (error && options2.errorTransformer) {
      error = options2.errorTransformer(error);
    }
    if (typeof error !== "undefined") {
      target.error(error);
    }
    target.end();
  }
}
async function doReadFileIntoStream(provider, resource, target, transformer, options2, token) {
  throwIfCancelled(token);
  const handle = await provider.open(resource, { create: false });
  try {
    throwIfCancelled(token);
    let totalBytesRead = 0;
    let bytesRead = 0;
    let allowedRemainingBytes = options2 && typeof options2.length === "number" ? options2.length : void 0;
    let buffer = $Ci.alloc(Math.min(options2.bufferSize, typeof allowedRemainingBytes === "number" ? allowedRemainingBytes : options2.bufferSize));
    let posInFile = options2 && typeof options2.position === "number" ? options2.position : 0;
    let posInBuffer = 0;
    do {
      bytesRead = await provider.read(handle, posInFile, buffer.buffer, posInBuffer, buffer.byteLength - posInBuffer);
      posInFile += bytesRead;
      posInBuffer += bytesRead;
      totalBytesRead += bytesRead;
      if (typeof allowedRemainingBytes === "number") {
        allowedRemainingBytes -= bytesRead;
      }
      if (posInBuffer === buffer.byteLength) {
        await target.write(transformer(buffer));
        buffer = $Ci.alloc(Math.min(options2.bufferSize, typeof allowedRemainingBytes === "number" ? allowedRemainingBytes : options2.bufferSize));
        posInBuffer = 0;
      }
    } while (bytesRead > 0 && (typeof allowedRemainingBytes !== "number" || allowedRemainingBytes > 0) && throwIfCancelled(token) && throwIfTooLarge(totalBytesRead, options2));
    if (posInBuffer > 0) {
      let lastChunkLength = posInBuffer;
      if (typeof allowedRemainingBytes === "number") {
        lastChunkLength = Math.min(posInBuffer, allowedRemainingBytes);
      }
      target.write(transformer(buffer.slice(0, lastChunkLength)));
    }
  } catch (error) {
    throw $ym(error);
  } finally {
    await provider.close(handle);
  }
}
function throwIfCancelled(token) {
  if (token.isCancellationRequested) {
    throw $mb();
  }
  return true;
}
function throwIfTooLarge(totalBytesRead, options2) {
  if (typeof options2?.limits?.size === "number" && totalBytesRead > options2.limits.size) {
    throw $xm(localize(1943, null), FileSystemProviderErrorCode.FileTooLarge);
  }
  return true;
}

// out-build/vs/platform/files/common/diskFileSystemProvider.js
var $fy = class extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.c = this.B(new $ze());
    this.onDidChangeFile = this.c.event;
    this.g = this.B(new $ze());
    this.onDidWatchError = this.g.event;
    this.j = [];
    this.m = this.B(new $Th(0));
    this.y = [];
    this.z = this.B(new $Th(0));
  }
  watch(resource, opts) {
    if (opts.recursive || this.b?.watcher?.forceUniversal) {
      return this.n(resource, opts);
    }
    return this.C(resource, opts);
  }
  n(resource, opts) {
    const request = this.r(resource, opts);
    const remove = $Wb(this.j, request);
    this.s();
    return $1c(() => {
      remove();
      this.s();
    });
  }
  r(resource, opts) {
    const request = {
      path: this.L(resource),
      excludes: opts.excludes,
      includes: opts.includes,
      recursive: opts.recursive,
      filter: opts.filter,
      correlationId: opts.correlationId
    };
    if ($8s(request)) {
      const usePolling = this.b?.watcher?.recursive?.usePolling;
      if (usePolling === true) {
        request.pollingInterval = this.b?.watcher?.recursive?.pollingInterval ?? 5e3;
      } else if (Array.isArray(usePolling)) {
        if (usePolling.includes(request.path)) {
          request.pollingInterval = this.b?.watcher?.recursive?.pollingInterval ?? 5e3;
        }
      }
    }
    return request;
  }
  s() {
    this.m.trigger(() => {
      return this.t();
    }).catch((error) => $gb(error));
  }
  t() {
    if (!this.h) {
      this.h = this.B(this.u((changes) => this.c.fire($_s(changes)), (msg) => this.H(msg), this.a.getLevel() === LogLevel.Trace));
      this.B(this.a.onDidChangeLogLevel(() => {
        this.h?.setVerboseLogging(this.a.getLevel() === LogLevel.Trace);
      }));
    }
    return this.h.watch(this.j);
  }
  C(resource, opts) {
    const request = {
      path: this.L(resource),
      excludes: opts.excludes,
      includes: opts.includes,
      recursive: false,
      filter: opts.filter,
      correlationId: opts.correlationId
    };
    const remove = $Wb(this.y, request);
    this.D();
    return $1c(() => {
      remove();
      this.D();
    });
  }
  D() {
    this.z.trigger(() => {
      return this.F();
    }).catch((error) => $gb(error));
  }
  F() {
    if (!this.w) {
      this.w = this.B(this.G((changes) => this.c.fire($_s(changes)), (msg) => this.H(msg), this.a.getLevel() === LogLevel.Trace));
      this.B(this.a.onDidChangeLogLevel(() => {
        this.w?.setVerboseLogging(this.a.getLevel() === LogLevel.Trace);
      }));
    }
    return this.w.watch(this.y);
  }
  //#endregion
  H(msg) {
    if (msg.type === "error") {
      this.g.fire(msg.message);
    }
    this.I(msg);
  }
  I(msg) {
    this.a[msg.type](msg.message);
  }
  J(resource) {
    return $lc(resource.fsPath);
  }
  L(resource) {
    const filePath = this.J(resource);
    return $3g(filePath);
  }
};

// out-build/vs/base/parts/ipc/node/ipc.cp.js
import { fork as fork2 } from "child_process";

// out-build/vs/base/common/console.js
function $gy(obj) {
  const entry = obj;
  return entry && typeof entry.type === "string" && typeof entry.severity === "string";
}
function $hy(entry) {
  const args2 = [];
  let stack;
  try {
    const parsedArguments = JSON.parse(entry.arguments);
    const stackArgument = parsedArguments[parsedArguments.length - 1];
    if (stackArgument && stackArgument.__$stack) {
      parsedArguments.pop();
      stack = stackArgument.__$stack;
    }
    args2.push(...parsedArguments);
  } catch (error) {
    args2.push("Unable to log remote console arguments", entry.arguments);
  }
  return { args: args2, stack };
}
function findFirstFrame(stack) {
  if (!stack) {
    return stack;
  }
  const newlineIndex = stack.indexOf("\n");
  if (newlineIndex === -1) {
    return stack;
  }
  return stack.substring(0, newlineIndex);
}
function log2(entry, label) {
  const { args: args2, stack } = $hy(entry);
  const isOneStringArg = typeof args2[0] === "string" && args2.length === 1;
  let topFrame = findFirstFrame(stack);
  if (topFrame) {
    topFrame = `(${topFrame.trim()})`;
  }
  let consoleArgs = [];
  if (typeof args2[0] === "string") {
    if (topFrame && isOneStringArg) {
      consoleArgs = [`%c[${label}] %c${args2[0]} %c${topFrame}`, color("blue"), color(""), color("grey")];
    } else {
      consoleArgs = [`%c[${label}] %c${args2[0]}`, color("blue"), color(""), ...args2.slice(1)];
    }
  } else {
    consoleArgs = [`%c[${label}]%`, color("blue"), ...args2];
  }
  if (topFrame && !isOneStringArg) {
    consoleArgs.push(topFrame);
  }
  if (typeof console[entry.severity] !== "function") {
    throw new Error("Unknown console method");
  }
  console[entry.severity].apply(console, consoleArgs);
}
function color(color2) {
  return `color: ${color2}`;
}

// out-build/vs/base/parts/ipc/node/ipc.cp.js
var $ly = class {
  constructor(i, j) {
    this.i = i;
    this.j = j;
    this.c = /* @__PURE__ */ new Set();
    this.g = /* @__PURE__ */ new Map();
    this.h = new $ze();
    this.onDidProcessExit = this.h.event;
    const timeout = j && j.timeout ? j.timeout : 6e4;
    this.b = new $Sh(timeout);
    this.d = null;
    this.f = null;
  }
  getChannel(channelName) {
    const that = this;
    return {
      call(command, arg, cancellationToken) {
        return that.k(channelName, command, arg, cancellationToken);
      },
      listen(event, arg) {
        return that.l(channelName, event, arg);
      }
    };
  }
  k(channelName, name, arg, cancellationToken = CancellationToken.None) {
    if (!this.b) {
      return Promise.reject(new Error("disposed"));
    }
    if (cancellationToken.isCancellationRequested) {
      return Promise.reject($mb());
    }
    this.b.cancel();
    const channel = this.n(channelName);
    const result = $Hh((token) => channel.call(name, arg, token));
    const cancellationTokenListener = cancellationToken.onCancellationRequested(() => result.cancel());
    const disposable = $1c(() => result.cancel());
    this.c.add(disposable);
    result.finally(() => {
      cancellationTokenListener.dispose();
      this.c.delete(disposable);
      if (this.c.size === 0 && this.b) {
        this.b.trigger(() => this.o());
      }
    });
    return result;
  }
  l(channelName, name, arg) {
    if (!this.b) {
      return Event.None;
    }
    this.b.cancel();
    let listener;
    const emitter = new $ze({
      onWillAddFirstListener: () => {
        const channel = this.n(channelName);
        const event = channel.listen(name, arg);
        listener = event(emitter.fire, emitter);
        this.c.add(listener);
      },
      onDidRemoveLastListener: () => {
        this.c.delete(listener);
        listener.dispose();
        if (this.c.size === 0 && this.b) {
          this.b.trigger(() => this.o());
        }
      }
    });
    return emitter.event;
  }
  get m() {
    if (!this.f) {
      const args2 = this.j && this.j.args ? this.j.args : [];
      const forkOpts = /* @__PURE__ */ Object.create(null);
      forkOpts.env = { ...$Lv(process.env), "VSCODE_PARENT_PID": String(process.pid) };
      if (this.j && this.j.env) {
        forkOpts.env = { ...forkOpts.env, ...this.j.env };
      }
      if (this.j && this.j.freshExecArgv) {
        forkOpts.execArgv = [];
      }
      if (this.j && typeof this.j.debug === "number") {
        forkOpts.execArgv = ["--nolazy", "--inspect=" + this.j.debug];
      }
      if (this.j && typeof this.j.debugBrk === "number") {
        forkOpts.execArgv = ["--nolazy", "--inspect-brk=" + this.j.debugBrk];
      }
      if (forkOpts.execArgv === void 0) {
        forkOpts.execArgv = process.execArgv.filter((a) => !/^--inspect(-brk)?=/.test(a)).filter((a) => !a.startsWith("--vscode-"));
      }
      $Fx(forkOpts.env);
      this.d = fork2(this.i, args2, forkOpts);
      const onMessageEmitter = new $ze();
      const onRawMessage = Event.fromNodeEventEmitter(this.d, "message", (msg) => msg);
      const rawMessageDisposable = onRawMessage((msg) => {
        if ($gy(msg)) {
          log2(msg, `IPC Library: ${this.j.serverName}`);
          return;
        }
        onMessageEmitter.fire($Ci.wrap(Buffer.from(msg, "base64")));
      });
      const sender = this.j.useQueue ? $Tx(this.d) : this.d;
      const send = (r) => this.d && this.d.connected && sender.send(r.buffer.toString("base64"));
      const onMessage = onMessageEmitter.event;
      const protocol = { send, onMessage };
      this.f = new $iu(protocol);
      const onExit = () => this.o();
      process.once("exit", onExit);
      this.d.on("error", (err) => console.warn('IPC "' + this.j.serverName + '" errored with ' + err));
      this.d.on("exit", (code, signal) => {
        process.removeListener("exit", onExit);
        rawMessageDisposable.dispose();
        this.c.forEach((r) => $Xc(r));
        this.c.clear();
        if (code !== 0 && signal !== "SIGTERM") {
          console.warn('IPC "' + this.j.serverName + '" crashed with exit code ' + code + " and signal " + signal);
        }
        this.b?.cancel();
        this.o();
        this.h.fire({ code, signal });
      });
    }
    return this.f;
  }
  n(name) {
    let channel = this.g.get(name);
    if (!channel) {
      channel = this.m.getChannel(name);
      this.g.set(name, channel);
    }
    return channel;
  }
  o() {
    if (this.f) {
      if (this.d) {
        this.d.kill();
        this.d = null;
      }
      this.f = null;
      this.g.clear();
    }
  }
  dispose() {
    this.h.dispose();
    this.b?.cancel();
    this.b = void 0;
    this.o();
    this.c.clear();
  }
};

// out-build/vs/platform/files/node/watcher/watcherClient.js
var $my = class extends $$s {
  constructor(onFileChanges, onLogMessage, verboseLogging) {
    super(onFileChanges, onLogMessage, verboseLogging);
    this.s();
  }
  r(disposables) {
    const client = disposables.add(new $ly($ih.asFileUri("bootstrap-fork").fsPath, {
      serverName: "File Watcher",
      args: ["--type=fileWatcher"],
      env: {
        VSCODE_ESM_ENTRYPOINT: "vs/platform/files/node/watcher/watcherMain",
        VSCODE_PIPE_LOGGING: "true",
        VSCODE_VERBOSE_LOGGING: "true"
        // transmit console logs from server to client
      }
    }));
    disposables.add(client.onDidProcessExit(({ code, signal }) => this.t(`terminated by itself with code ${code}, signal: ${signal} (ETERM)`)));
    return ProxyChannel.toService($mu(client.getChannel("watcher")));
  }
};

// out-build/vs/platform/files/node/watcher/baseWatcher.js
import { watchFile, unwatchFile } from "fs";
var $ny = class extends $3c {
  constructor() {
    super();
    this.a = this.B(new $ze());
    this.onDidChangeFile = this.a.event;
    this.b = this.B(new $ze());
    this.onDidLogMessage = this.b.event;
    this.c = this.B(new $ze());
    this.f = this.c.event;
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.j = this.B(new $_c());
    this.m = /* @__PURE__ */ new Set();
    this.n = this.B(new $Th(this.y()));
    this.r = 5007;
    this.s = new $gi();
    this.R = false;
    this.B(this.f((request) => this.z({
      id: this.u(request),
      correlationId: this.t(request) ? request.correlationId : void 0,
      path: request.path
    })));
  }
  t(request) {
    return $7s(request);
  }
  u(request) {
    if (this.t(request)) {
      return request.correlationId;
    } else {
      return $Xi(request);
    }
  }
  async watch(requests) {
    if (!this.s.isSettled) {
      this.s.complete();
    }
    this.s = new $gi();
    try {
      this.g.clear();
      this.h.clear();
      for (const request of requests) {
        if (this.t(request)) {
          this.g.set(request.correlationId, request);
        } else {
          this.h.set(this.u(request), request);
        }
      }
      for (const [id2] of this.j) {
        if (!this.h.has(id2) && !this.g.has(id2)) {
          this.j.deleteAndDispose(id2);
          this.m.delete(id2);
        }
      }
      return await this.w(
        false
        /* not delayed */
      );
    } finally {
      this.s.complete();
    }
  }
  w(delayed) {
    const nonSuspendedRequests = [];
    for (const [id2, request] of [...this.h, ...this.g]) {
      if (!this.j.has(id2)) {
        nonSuspendedRequests.push(request);
      }
    }
    return this.n.trigger(() => this.N(nonSuspendedRequests), delayed ? this.y() : 0).catch((error) => $gb(error));
  }
  y() {
    return 800;
  }
  isSuspended(request) {
    const id2 = this.u(request);
    return this.m.has(id2) ? "polling" : this.j.has(id2);
  }
  async z(request) {
    if (this.j.has(request.id)) {
      return;
    }
    const disposables = new $2c();
    this.j.set(request.id, disposables);
    await this.s.p;
    if (disposables.isDisposed) {
      return;
    }
    this.D(request, disposables);
    this.w(
      true
      /* delay this call as we might accumulate many failing watch requests on startup */
    );
  }
  C(request) {
    this.j.deleteAndDispose(request.id);
    this.m.delete(request.id);
    this.w(false);
  }
  D(request, disposables) {
    if (this.F(request, disposables)) {
      this.P(`reusing an existing recursive watcher to monitor ${request.path}`);
      this.m.delete(request.id);
    } else {
      this.G(request, disposables);
      this.m.add(request.id);
    }
  }
  F(request, disposables) {
    const subscription = this.O?.subscribe(request.path, (error, change) => {
      if (disposables.isDisposed) {
        return;
      }
      if (error) {
        this.D(request, disposables);
      } else if (change?.type === 1) {
        this.H(request);
      }
    });
    if (subscription) {
      disposables.add(subscription);
      return true;
    }
    return false;
  }
  G(request, disposables) {
    let pathNotFound = false;
    const watchFileCallback = (curr, prev) => {
      if (disposables.isDisposed) {
        return;
      }
      const currentPathNotFound = this.I(curr);
      const previousPathNotFound = this.I(prev);
      const oldPathNotFound = pathNotFound;
      pathNotFound = currentPathNotFound;
      if (!currentPathNotFound && (previousPathNotFound || oldPathNotFound)) {
        this.H(request);
      }
    };
    this.P(`starting fs.watchFile() on ${request.path} (correlationId: ${request.correlationId})`);
    try {
      watchFile(request.path, { persistent: false, interval: this.r }, watchFileCallback);
    } catch (error) {
      this.Q(`fs.watchFile() failed with error ${error} on path ${request.path} (correlationId: ${request.correlationId})`);
    }
    disposables.add($1c(() => {
      this.P(`stopping fs.watchFile() on ${request.path} (correlationId: ${request.correlationId})`);
      try {
        unwatchFile(request.path, watchFileCallback);
      } catch (error) {
        this.Q(`fs.unwatchFile() failed with error ${error} on path ${request.path} (correlationId: ${request.correlationId})`);
      }
    }));
  }
  H(request) {
    this.P(`detected ${request.path} exists again, resuming watcher (correlationId: ${request.correlationId})`);
    const event = { resource: URI.file(request.path), type: 1, cId: request.correlationId };
    this.a.fire([event]);
    this.J(event, request);
    this.C(request);
  }
  I(stats) {
    return stats.ctimeMs === 0 && stats.ino === 0;
  }
  async stop() {
    this.j.clearAndDisposeAll();
    this.m.clear();
  }
  J(event, request) {
    if (this.R) {
      const traceMsg = ` >> normalized ${event.type === 1 ? "[ADDED]" : event.type === 2 ? "[DELETED]" : "[CHANGED]"} ${event.resource.fsPath}`;
      this.L(traceMsg, request);
    }
  }
  L(message, request) {
    if (this.R) {
      this.P(`${message}${typeof request.correlationId === "number" ? ` <${request.correlationId}> ` : ``}`);
    }
  }
  M(request) {
    return `${request.path} (excludes: ${request.excludes.length > 0 ? request.excludes : "<none>"}, includes: ${request.includes && request.includes.length > 0 ? JSON.stringify(request.includes) : "<all>"}, filter: ${$et(request.filter)}, correlationId: ${typeof request.correlationId === "number" ? request.correlationId : "<none>"})`;
  }
  async setVerboseLogging(enabled) {
    this.R = enabled;
  }
};

// out-build/vs/platform/files/node/watcher/nodejs/nodejsWatcherLib.js
import { watch, promises as promises4 } from "fs";
var $ft = class _$ft extends $3c {
  static {
    this.a = 100;
  }
  static {
    this.b = 75;
  }
  get isReusingRecursiveWatcher() {
    return this.n;
  }
  get failed() {
    return this.r;
  }
  constructor(s, t, u, w, y, z) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.c = this.B(new $$h({
      maxWorkChunkSize: 100,
      // only process up to 100 changes at once before...
      throttleDelay: 200,
      // ...resting for 200ms until we process events again...
      maxBufferedWork: 1e4
      // ...but never buffering more than 10000 events in memory
    }, (events) => this.u(events)));
    this.f = this.B(new $0h((events) => this.M(events), _$ft.b));
    this.g = $ct(this.s.path, this.s.excludes);
    this.h = this.s.includes ? $ct(this.s.path, this.s.includes) : void 0;
    this.j = $7s(this.s) ? this.s.filter : void 0;
    this.m = new $ad();
    this.ready = this.C();
    this.n = false;
    this.r = false;
  }
  async C() {
    try {
      const realPath = await this.F(this.s);
      if (this.m.token.isCancellationRequested) {
        return;
      }
      const stat2 = await promises4.stat(realPath);
      if (this.m.token.isCancellationRequested) {
        return;
      }
      this.B(await this.G(realPath, stat2.isDirectory()));
    } catch (error) {
      if (error.code !== "ENOENT") {
        this.O(error);
      } else {
        this.Q(`ignoring a path for watching who's stat info failed to resolve: ${this.s.path} (error: ${error})`);
      }
      this.D();
    }
  }
  D() {
    this.r = true;
    this.w?.();
  }
  async F(request) {
    let realPath = request.path;
    try {
      realPath = await Promises2.realpath(request.path);
      if (request.path === realPath) {
        realPath = await $4s(request.path, this.m.token) ?? request.path;
      }
      if (request.path !== realPath) {
        this.Q(`correcting a path to watch that seems to be a symbolic link or wrong casing (original: ${request.path}, real: ${realPath})`);
      }
    } catch (error) {
    }
    return realPath;
  }
  async G(realPath, isDirectory) {
    const disposables = new $2c();
    if (this.H(realPath, isDirectory, disposables)) {
      this.Q(`reusing an existing recursive watcher for ${this.s.path}`);
      this.n = true;
    } else {
      this.n = false;
      await this.I(realPath, isDirectory, disposables);
    }
    return disposables;
  }
  H(realPath, isDirectory, disposables) {
    if (isDirectory) {
      return false;
    }
    const resource = URI.file(this.s.path);
    const subscription = this.t?.subscribe(this.s.path, async (error, change) => {
      if (disposables.isDisposed) {
        return;
      }
      if (error) {
        const watchDisposable = await this.G(realPath, isDirectory);
        if (!disposables.isDisposed) {
          disposables.add(watchDisposable);
        } else {
          watchDisposable.dispose();
        }
      } else if (change) {
        if (typeof change.cId === "number" || typeof this.s.correlationId === "number") {
          this.L(
            { resource, type: change.type, cId: this.s.correlationId },
            true
            /* skip excludes/includes (file is explicitly watched) */
          );
        }
      }
    });
    if (subscription) {
      disposables.add(subscription);
      return true;
    }
    return false;
  }
  async I(realPath, isDirectory, disposables) {
    if ($m && $Zg(realPath, "/Volumes/", true)) {
      this.O(`Refusing to watch ${realPath} for changes using fs.watch() for possibly being a network share where watching is unreliable and unstable.`);
      return;
    }
    const cts = new $ad(this.m.token);
    disposables.add($1c(() => cts.dispose(true)));
    const watcherDisposables = new $2c();
    disposables.add(watcherDisposables);
    try {
      const requestResource = URI.file(this.s.path);
      const pathBasename = $rc(realPath);
      const watcher = watch(realPath);
      watcherDisposables.add($1c(() => {
        watcher.removeAllListeners();
        watcher.close();
      }));
      this.Q(`Started watching: '${realPath}'`);
      const folderChildren = /* @__PURE__ */ new Set();
      if (isDirectory) {
        try {
          for (const child of await Promises2.readdir(realPath)) {
            folderChildren.add(child);
          }
        } catch (error) {
          this.O(error);
        }
      }
      if (cts.token.isCancellationRequested) {
        return;
      }
      const mapPathToStatDisposable = /* @__PURE__ */ new Map();
      watcherDisposables.add($1c(() => {
        for (const [, disposable] of mapPathToStatDisposable) {
          disposable.dispose();
        }
        mapPathToStatDisposable.clear();
      }));
      watcher.on("error", (code, signal) => {
        if (cts.token.isCancellationRequested) {
          return;
        }
        this.O(`Failed to watch ${realPath} for changes using fs.watch() (${code}, ${signal})`);
        this.D();
      });
      watcher.on("change", (type, raw) => {
        if (cts.token.isCancellationRequested) {
          return;
        }
        if (this.z) {
          this.R(`[raw] ["${type}"] ${raw}`);
        }
        let changedFileName = "";
        if (raw) {
          changedFileName = raw.toString();
          if ($m) {
            changedFileName = $Qs(changedFileName);
          }
        }
        if (!changedFileName || type !== "change" && type !== "rename") {
          return;
        }
        if (isDirectory) {
          if (type === "rename") {
            mapPathToStatDisposable.get(changedFileName)?.dispose();
            const timeoutHandle = setTimeout(async () => {
              mapPathToStatDisposable.delete(changedFileName);
              if (changedFileName === pathBasename && !await Promises2.exists(realPath)) {
                this.J(requestResource);
                return;
              }
              if (cts.token.isCancellationRequested) {
                return;
              }
              const fileExists = await this.N($nc(realPath, changedFileName));
              if (cts.token.isCancellationRequested) {
                return;
              }
              let type2;
              if (fileExists) {
                if (folderChildren.has(changedFileName)) {
                  type2 = 0;
                } else {
                  type2 = 1;
                  folderChildren.add(changedFileName);
                }
              } else {
                folderChildren.delete(changedFileName);
                type2 = 2;
              }
              this.L({ resource: $vh(requestResource, changedFileName), type: type2, cId: this.s.correlationId });
            }, _$ft.a);
            mapPathToStatDisposable.set(changedFileName, $1c(() => clearTimeout(timeoutHandle)));
          } else {
            let type2;
            if (folderChildren.has(changedFileName)) {
              type2 = 0;
            } else {
              type2 = 1;
              folderChildren.add(changedFileName);
            }
            this.L({ resource: $vh(requestResource, changedFileName), type: type2, cId: this.s.correlationId });
          }
        } else {
          if (type === "rename" || changedFileName !== pathBasename) {
            const timeoutHandle = setTimeout(async () => {
              const fileExists = await Promises2.exists(realPath);
              if (cts.token.isCancellationRequested) {
                return;
              }
              if (fileExists) {
                this.L(
                  { resource: requestResource, type: 0, cId: this.s.correlationId },
                  true
                  /* skip excludes/includes (file is explicitly watched) */
                );
                watcherDisposables.add(await this.G(realPath, false));
              } else {
                this.J(requestResource);
              }
            }, _$ft.a);
            watcherDisposables.clear();
            watcherDisposables.add($1c(() => clearTimeout(timeoutHandle)));
          } else {
            this.L(
              { resource: requestResource, type: 0, cId: this.s.correlationId },
              true
              /* skip excludes/includes (file is explicitly watched) */
            );
          }
        }
      });
    } catch (error) {
      if (!cts.token.isCancellationRequested) {
        this.O(`Failed to watch ${realPath} for changes using fs.watch() (${error.toString()})`);
      }
      this.D();
    }
  }
  J(resource) {
    this.P("Watcher shutdown because watched path got deleted");
    this.L(
      { resource, type: 2, cId: this.s.correlationId },
      true
      /* skip excludes/includes (file is explicitly watched) */
    );
    this.f.flush();
    this.D();
  }
  L(event, skipIncludeExcludeChecks = false) {
    if (this.m.token.isCancellationRequested) {
      return;
    }
    if (this.z) {
      this.R(`${event.type === 1 ? "[ADDED]" : event.type === 2 ? "[DELETED]" : "[CHANGED]"} ${event.resource.fsPath}`);
    }
    if (!skipIncludeExcludeChecks && this.g.some((exclude) => exclude(event.resource.fsPath))) {
      if (this.z) {
        this.R(` >> ignored (excluded) ${event.resource.fsPath}`);
      }
    } else if (!skipIncludeExcludeChecks && this.h && this.h.length > 0 && !this.h.some((include) => include(event.resource.fsPath))) {
      if (this.z) {
        this.R(` >> ignored (not included) ${event.resource.fsPath}`);
      }
    } else {
      this.f.work(event);
    }
  }
  M(fileChanges) {
    const coalescedFileChanges = $at(fileChanges);
    const filteredEvents = [];
    for (const event of coalescedFileChanges) {
      if ($dt(event, this.j)) {
        if (this.z) {
          this.R(` >> ignored (filtered) ${event.resource.fsPath}`);
        }
        continue;
      }
      filteredEvents.push(event);
    }
    if (filteredEvents.length === 0) {
      return;
    }
    if (this.z) {
      for (const event of filteredEvents) {
        this.R(` >> normalized ${event.type === 1 ? "[ADDED]" : event.type === 2 ? "[DELETED]" : "[CHANGED]"} ${event.resource.fsPath}`);
      }
    }
    const worked = this.c.work(filteredEvents);
    if (!worked) {
      this.P(`started ignoring events due to too many file change events at once (incoming: ${filteredEvents.length}, most recent change: ${filteredEvents[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`);
    } else {
      if (this.c.pending > 0) {
        this.Q(`started throttling events due to large amount of file change events at once (pending: ${this.c.pending}, most recent change: ${filteredEvents[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`);
      }
    }
  }
  async N(path) {
    if ($n) {
      return Promises2.exists(path);
    }
    try {
      const pathBasename = $rc(path);
      const children = await Promises2.readdir($qc(path));
      return children.some((child) => child === pathBasename);
    } catch (error) {
      this.Q(error);
      return false;
    }
  }
  setVerboseLogging(verboseLogging) {
    this.z = verboseLogging;
  }
  O(error) {
    if (!this.m.token.isCancellationRequested) {
      this.y?.({ type: "error", message: `[File Watcher (node.js)] ${error}` });
    }
  }
  P(message) {
    if (!this.m.token.isCancellationRequested) {
      this.y?.({ type: "warn", message: `[File Watcher (node.js)] ${message}` });
    }
  }
  Q(message) {
    if (!this.m.token.isCancellationRequested && this.z) {
      this.y?.({ type: "trace", message: `[File Watcher (node.js)] ${message}` });
    }
  }
  R(message) {
    if (!this.m.token.isCancellationRequested && this.z) {
      this.Q(`${message}${typeof this.s.correlationId === "number" ? ` <${this.s.correlationId}> ` : ``}`);
    }
  }
  dispose() {
    this.m.dispose(true);
    super.dispose();
  }
};

// out-build/vs/platform/files/node/watcher/nodejs/nodejsWatcher.js
var $oy = class extends $ny {
  constructor(O) {
    super();
    this.O = O;
    this.onDidError = Event.None;
    this.watchers = /* @__PURE__ */ new Set();
  }
  async N(requests) {
    requests = this.Z(requests);
    const requestsToStart = [];
    const watchersToStop = new Set(Array.from(this.watchers));
    for (const request of requests) {
      const watcher = this.W(request);
      if (watcher && $Hl(watcher.request.excludes, request.excludes) && $Hl(watcher.request.includes, request.includes)) {
        watchersToStop.delete(watcher);
      } else {
        requestsToStart.push(request);
      }
    }
    if (requestsToStart.length) {
      this.P(`Request to start watching: ${requestsToStart.map((request) => this.M(request)).join(",")}`);
    }
    if (watchersToStop.size) {
      this.P(`Request to stop watching: ${Array.from(watchersToStop).map((watcher) => this.M(watcher.request)).join(",")}`);
    }
    for (const watcher of watchersToStop) {
      this.Y(watcher);
    }
    for (const request of requestsToStart) {
      this.X(request);
    }
  }
  W(request) {
    for (const watcher of this.watchers) {
      if (typeof request.correlationId === "number" || typeof watcher.request.correlationId === "number") {
        if (watcher.request.correlationId === request.correlationId) {
          return watcher;
        }
      } else {
        if ($Yg(
          watcher.request.path,
          request.path,
          !$n
          /* ignorecase */
        )) {
          return watcher;
        }
      }
    }
    return void 0;
  }
  X(request) {
    const instance = new $ft(request, this.O, (changes) => this.a.fire(changes), () => this.c.fire(request), (msg) => this.b.fire(msg), this.R);
    const watcher = { request, instance };
    this.watchers.add(watcher);
  }
  async stop() {
    await super.stop();
    for (const watcher of this.watchers) {
      this.Y(watcher);
    }
  }
  Y(watcher) {
    this.P(`stopping file watcher`, watcher);
    this.watchers.delete(watcher);
    watcher.instance.dispose();
  }
  Z(requests) {
    const mapCorrelationtoRequests = /* @__PURE__ */ new Map();
    for (const request of requests) {
      const path = $n ? request.path : request.path.toLowerCase();
      let requestsForCorrelation = mapCorrelationtoRequests.get(request.correlationId);
      if (!requestsForCorrelation) {
        requestsForCorrelation = /* @__PURE__ */ new Map();
        mapCorrelationtoRequests.set(request.correlationId, requestsForCorrelation);
      }
      if (requestsForCorrelation.has(path)) {
        this.P(`ignoring a request for watching who's path is already watched: ${this.M(request)}`);
      }
      requestsForCorrelation.set(path, request);
    }
    return Array.from(mapCorrelationtoRequests.values()).map((requests2) => Array.from(requests2.values())).flat();
  }
  async setVerboseLogging(enabled) {
    super.setVerboseLogging(enabled);
    for (const watcher of this.watchers) {
      watcher.instance.setVerboseLogging(enabled);
    }
  }
  P(message, watcher) {
    if (this.R) {
      this.b.fire({ type: "trace", message: this.bb(message, watcher) });
    }
  }
  Q(message) {
    this.b.fire({ type: "warn", message: this.bb(message) });
  }
  bb(message, watcher) {
    return watcher ? `[File Watcher (node.js)] ${message} (${this.M(watcher.request)})` : `[File Watcher (node.js)] ${message}`;
  }
};

// out-build/vs/platform/files/node/watcher/nodejs/nodejsClient.js
var $py = class extends $0s {
  constructor(onFileChanges, onLogMessage, verboseLogging) {
    super(onFileChanges, onLogMessage, verboseLogging);
    this.s();
  }
  r(disposables) {
    return disposables.add(new $oy(
      void 0
      /* no recursive watching support here */
    ));
  }
};

// out-build/vs/platform/files/node/diskFileSystemProvider.js
var $qy = class _$qy extends $fy {
  static {
    this.M = false;
  }
  // not enabled by default because very spammy
  constructor(logService, options2) {
    super(logService, options2);
    this.onDidChangeCapabilities = Event.None;
    this.Q = new $Ec((resource) => $mh.getComparisonKey(resource));
    this.Y = /* @__PURE__ */ new Map();
    this.Z = /* @__PURE__ */ new Map();
    this.$ = /* @__PURE__ */ new Map();
  }
  get capabilities() {
    if (!this.N) {
      this.N = 2 | 4 | 16 | 8 | 8192 | 16384 | 32768 | 65536 | 131072;
      if ($n) {
        this.N |= 1024;
      }
    }
    return this.N;
  }
  //#endregion
  //#region File Metadata Resolving
  async stat(resource) {
    try {
      const { stat: stat2, symbolicLink } = await SymlinkSupport.stat(this.J(resource));
      return {
        type: this.P(stat2, symbolicLink),
        ctime: stat2.birthtime.getTime(),
        // intentionally not using ctime here, we want the creation time
        mtime: stat2.mtime.getTime(),
        size: stat2.size,
        permissions: (stat2.mode & 128) === 0 ? FilePermission.Locked : void 0
      };
    } catch (error) {
      throw this.ib(error);
    }
  }
  async O(resource) {
    try {
      return await this.stat(resource);
    } catch (error) {
      return void 0;
    }
  }
  async readdir(resource) {
    try {
      const children = await Promises2.readdir(this.J(resource), { withFileTypes: true });
      const result = [];
      await Promise.all(children.map(async (child) => {
        try {
          let type;
          if (child.isSymbolicLink()) {
            type = (await this.stat($vh(resource, child.name))).type;
          } else {
            type = this.P(child);
          }
          result.push([child.name, type]);
        } catch (error) {
          this.a.trace(error);
        }
      }));
      return result;
    } catch (error) {
      throw this.ib(error);
    }
  }
  P(entry, symbolicLink) {
    let type;
    if (symbolicLink?.dangling) {
      type = FileType.Unknown;
    } else if (entry.isFile()) {
      type = FileType.File;
    } else if (entry.isDirectory()) {
      type = FileType.Directory;
    } else {
      type = FileType.Unknown;
    }
    if (symbolicLink) {
      type |= FileType.SymbolicLink;
    }
    return type;
  }
  async R(resource) {
    const filePath = this.J(resource);
    this.S(`[Disk FileSystemProvider]: createResourceLock() - request to acquire resource lock (${filePath})`);
    let existingLock = void 0;
    while (existingLock = this.Q.get(resource)) {
      this.S(`[Disk FileSystemProvider]: createResourceLock() - waiting for resource lock to be released (${filePath})`);
      await existingLock.wait();
    }
    const newLock = new $Uh();
    this.Q.set(resource, newLock);
    this.S(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${filePath})`);
    return $1c(() => {
      this.S(`[Disk FileSystemProvider]: createResourceLock() - resource lock dispose() (${filePath})`);
      if (this.Q.get(resource) === newLock) {
        this.S(`[Disk FileSystemProvider]: createResourceLock() - resource lock removed from resource-lock map (${filePath})`);
        this.Q.delete(resource);
      }
      this.S(`[Disk FileSystemProvider]: createResourceLock() - resource lock barrier open() (${filePath})`);
      newLock.open();
    });
  }
  async readFile(resource, options2) {
    let lock = void 0;
    try {
      if (options2?.atomic) {
        this.S(`[Disk FileSystemProvider]: atomic read operation started (${this.J(resource)})`);
        lock = await this.R(resource);
      }
      const filePath = this.J(resource);
      return await promises5.readFile(filePath);
    } catch (error) {
      throw this.ib(error);
    } finally {
      lock?.dispose();
    }
  }
  S(msg) {
    if (_$qy.M) {
      this.a.trace(msg);
    }
  }
  readFileStream(resource, opts, token) {
    const stream = $qi((data) => $Ci.concat(data.map((data2) => $Ci.wrap(data2))).buffer);
    $ey(this, resource, stream, (data) => data.buffer, {
      ...opts,
      bufferSize: 256 * 1024
      // read into chunks of 256kb each to reduce IPC overhead
    }, token);
    return stream;
  }
  async writeFile(resource, content, opts) {
    if (opts?.atomic !== false && opts?.atomic?.postfix && await this.U(resource)) {
      return this.W(resource, $vh($uh(resource), `${$sh(resource)}${opts.atomic.postfix}`), content, opts);
    } else {
      return this.X(resource, content, opts);
    }
  }
  async U(resource) {
    try {
      const filePath = this.J(resource);
      const { symbolicLink } = await SymlinkSupport.stat(filePath);
      if (symbolicLink) {
        return false;
      }
    } catch (error) {
    }
    return true;
  }
  async W(resource, tempResource, content, opts) {
    const locks = new $2c();
    try {
      locks.add(await this.R(resource));
      locks.add(await this.R(tempResource));
      await this.X(
        tempResource,
        content,
        opts,
        true
        /* disable write lock */
      );
      try {
        await this.rename(tempResource, resource, { overwrite: true });
      } catch (error) {
        try {
          await this.delete(tempResource, { recursive: false, useTrash: false, atomic: false });
        } catch (error2) {
        }
        throw error;
      }
    } finally {
      locks.dispose();
    }
  }
  async X(resource, content, opts, disableWriteLock) {
    let handle = void 0;
    try {
      const filePath = this.J(resource);
      if (!opts.create || !opts.overwrite) {
        const fileExists = await Promises2.exists(filePath);
        if (fileExists) {
          if (!opts.overwrite) {
            throw $xm(localize(1946, null), FileSystemProviderErrorCode.FileExists);
          }
        } else {
          if (!opts.create) {
            throw $xm(localize(1947, null), FileSystemProviderErrorCode.FileNotFound);
          }
        }
      }
      handle = await this.open(resource, { create: true, unlock: opts.unlock }, disableWriteLock);
      await this.write(handle, 0, content, 0, content.byteLength);
    } catch (error) {
      throw await this.jb(resource, error);
    } finally {
      if (typeof handle === "number") {
        await this.close(handle);
      }
    }
  }
  static {
    this.ab = true;
  }
  static configureFlushOnWrite(enabled) {
    _$qy.ab = enabled;
  }
  async open(resource, opts, disableWriteLock) {
    const filePath = this.J(resource);
    let lock = void 0;
    if ($lm(opts) && !disableWriteLock) {
      lock = await this.R(resource);
    }
    let fd = void 0;
    try {
      if ($lm(opts) && opts.unlock) {
        try {
          const { stat: stat2 } = await SymlinkSupport.stat(filePath);
          if (!(stat2.mode & 128)) {
            await promises5.chmod(filePath, stat2.mode | 128);
          }
        } catch (error) {
          if (error.code !== "ENOENT") {
            this.a.trace(error);
          }
        }
      }
      if ($l && $lm(opts)) {
        try {
          fd = await Promises2.open(filePath, "r+");
          await Promises2.ftruncate(fd, 0);
        } catch (error) {
          if (error.code !== "ENOENT") {
            this.a.trace(error);
          }
          if (typeof fd === "number") {
            try {
              await Promises2.close(fd);
            } catch (error2) {
              this.a.trace(error2);
            }
            fd = void 0;
          }
        }
      }
      if (typeof fd !== "number") {
        fd = await Promises2.open(filePath, $lm(opts) ? (
          // We take `opts.create` as a hint that the file is opened for writing
          // as such we use 'w' to truncate an existing or create the
          // file otherwise. we do not allow reading.
          "w"
        ) : (
          // Otherwise we assume the file is opened for reading
          // as such we use 'r' to neither truncate, nor create
          // the file.
          "r"
        ));
      }
    } catch (error) {
      lock?.dispose();
      if ($lm(opts)) {
        throw await this.jb(resource, error);
      } else {
        throw this.ib(error);
      }
    }
    this.Y.set(fd, 0);
    if ($lm(opts)) {
      this.$.set(fd, resource);
    }
    if (lock) {
      const previousLock = this.Z.get(fd);
      this.S(`[Disk FileSystemProvider]: open() - storing lock for handle ${fd} (${filePath})`);
      this.Z.set(fd, lock);
      if (previousLock) {
        this.S(`[Disk FileSystemProvider]: open() - disposing a previous lock that was still stored on same handle ${fd} (${filePath})`);
        previousLock.dispose();
      }
    }
    return fd;
  }
  async close(fd) {
    const lockForHandle = this.Z.get(fd);
    try {
      this.Y.delete(fd);
      if (this.$.delete(fd) && _$qy.ab) {
        try {
          await Promises2.fdatasync(fd);
        } catch (error) {
          _$qy.configureFlushOnWrite(false);
          this.a.error(error);
        }
      }
      return await Promises2.close(fd);
    } catch (error) {
      throw this.ib(error);
    } finally {
      if (lockForHandle) {
        if (this.Z.get(fd) === lockForHandle) {
          this.S(`[Disk FileSystemProvider]: close() - resource lock removed from handle-lock map ${fd}`);
          this.Z.delete(fd);
        }
        this.S(`[Disk FileSystemProvider]: close() - disposing lock for handle ${fd}`);
        lockForHandle.dispose();
      }
    }
  }
  async read(fd, pos, data, offset, length) {
    const normalizedPos = this.bb(fd, pos);
    let bytesRead = null;
    try {
      bytesRead = (await Promises2.read(fd, data, offset, length, normalizedPos)).bytesRead;
    } catch (error) {
      throw this.ib(error);
    } finally {
      this.cb(fd, normalizedPos, bytesRead);
    }
    return bytesRead;
  }
  bb(fd, pos) {
    if (pos === this.Y.get(fd)) {
      return null;
    }
    return pos;
  }
  cb(fd, pos, bytesLength) {
    const lastKnownPos = this.Y.get(fd);
    if (typeof lastKnownPos === "number") {
      if (typeof pos === "number") {
      } else if (typeof bytesLength === "number") {
        this.Y.set(fd, lastKnownPos + bytesLength);
      } else {
        this.Y.delete(fd);
      }
    }
  }
  async write(fd, pos, data, offset, length) {
    return $di(
      () => this.db(fd, pos, data, offset, length),
      100,
      3
      /* retries */
    );
  }
  async db(fd, pos, data, offset, length) {
    const normalizedPos = this.bb(fd, pos);
    let bytesWritten = null;
    try {
      bytesWritten = (await Promises2.write(fd, data, offset, length, normalizedPos)).bytesWritten;
    } catch (error) {
      throw await this.jb(this.$.get(fd), error);
    } finally {
      this.cb(fd, normalizedPos, bytesWritten);
    }
    return bytesWritten;
  }
  //#endregion
  //#region Move/Copy/Delete/Create Folder
  async mkdir(resource) {
    try {
      await promises5.mkdir(this.J(resource));
    } catch (error) {
      throw this.ib(error);
    }
  }
  async delete(resource, opts) {
    try {
      const filePath = this.J(resource);
      if (opts.recursive) {
        let rmMoveToPath = void 0;
        if (opts?.atomic !== false && opts.atomic.postfix) {
          rmMoveToPath = $nc($qc(filePath), `${$rc(filePath)}${opts.atomic.postfix}`);
        }
        await Promises2.rm(filePath, RimRafMode.MOVE, rmMoveToPath);
      } else {
        try {
          await promises5.unlink(filePath);
        } catch (unlinkError) {
          if (unlinkError.code === "EPERM" || unlinkError.code === "EISDIR") {
            let isDirectory = false;
            try {
              const { stat: stat2, symbolicLink } = await SymlinkSupport.stat(filePath);
              isDirectory = stat2.isDirectory() && !symbolicLink;
            } catch (statError) {
            }
            if (isDirectory) {
              await promises5.rmdir(filePath);
            } else {
              throw unlinkError;
            }
          } else {
            throw unlinkError;
          }
        }
      }
    } catch (error) {
      throw this.ib(error);
    }
  }
  async rename(from, to, opts) {
    const fromFilePath = this.J(from);
    const toFilePath = this.J(to);
    if (fromFilePath === toFilePath) {
      return;
    }
    try {
      await this.eb(from, to, "move", opts.overwrite);
      await Promises2.rename(fromFilePath, toFilePath);
    } catch (error) {
      if (error.code === "EINVAL" || error.code === "EBUSY" || error.code === "ENAMETOOLONG") {
        error = new Error(localize(1948, null, $rc(fromFilePath), $rc($qc(toFilePath)), error.toString()));
      }
      throw this.ib(error);
    }
  }
  async copy(from, to, opts) {
    const fromFilePath = this.J(from);
    const toFilePath = this.J(to);
    if (fromFilePath === toFilePath) {
      return;
    }
    try {
      await this.eb(from, to, "copy", opts.overwrite);
      await Promises2.copy(fromFilePath, toFilePath, { preserveSymlinks: true });
    } catch (error) {
      if (error.code === "EINVAL" || error.code === "EBUSY" || error.code === "ENAMETOOLONG") {
        error = new Error(localize(1949, null, $rc(fromFilePath), $rc($qc(toFilePath)), error.toString()));
      }
      throw this.ib(error);
    }
  }
  async eb(from, to, mode, overwrite) {
    const fromFilePath = this.J(from);
    const toFilePath = this.J(to);
    let isSameResourceWithDifferentPathCase = false;
    const isPathCaseSensitive = !!(this.capabilities & 1024);
    if (!isPathCaseSensitive) {
      isSameResourceWithDifferentPathCase = $Yg(
        fromFilePath,
        toFilePath,
        true
        /* ignore case */
      );
    }
    if (isSameResourceWithDifferentPathCase) {
      if (mode === "copy") {
        throw $xm(localize(1950, null), FileSystemProviderErrorCode.FileExists);
      } else if (mode === "move") {
        return;
      }
    }
    const fromStat = await this.O(from);
    if (!fromStat) {
      throw $xm(localize(1951, null), FileSystemProviderErrorCode.FileNotFound);
    }
    const toStat = await this.O(to);
    if (!toStat) {
      return;
    }
    if (!overwrite) {
      throw $xm(localize(1952, null), FileSystemProviderErrorCode.FileExists);
    }
    if ((fromStat.type & FileType.File) !== 0 && (toStat.type & FileType.File) !== 0) {
      return;
    } else {
      await this.delete(to, { recursive: true, useTrash: false, atomic: false });
    }
  }
  //#endregion
  //#region Clone File
  async cloneFile(from, to) {
    return this.fb(
      from,
      to,
      false
      /* optimistically assume parent folders exist */
    );
  }
  async fb(from, to, mkdir2) {
    const fromFilePath = this.J(from);
    const toFilePath = this.J(to);
    const isPathCaseSensitive = !!(this.capabilities & 1024);
    if ($Yg(fromFilePath, toFilePath, !isPathCaseSensitive)) {
      return;
    }
    const locks = new $2c();
    try {
      locks.add(await this.R(from));
      locks.add(await this.R(to));
      if (mkdir2) {
        await promises5.mkdir($qc(toFilePath), { recursive: true });
      }
      await promises5.copyFile(fromFilePath, toFilePath);
    } catch (error) {
      if (error.code === "ENOENT" && !mkdir2) {
        return this.fb(from, to, true);
      }
      throw this.ib(error);
    } finally {
      locks.dispose();
    }
  }
  //#endregion
  //#region File Watching
  u(onChange, onLogMessage, verboseLogging) {
    return new $my((changes) => onChange(changes), (msg) => onLogMessage(msg), verboseLogging);
  }
  G(onChange, onLogMessage, verboseLogging) {
    return new $py((changes) => onChange(changes), (msg) => onLogMessage(msg), verboseLogging);
  }
  //#endregion
  //#region Helpers
  ib(error) {
    if (error instanceof $wm) {
      return error;
    }
    let resultError = error;
    let code;
    switch (error.code) {
      case "ENOENT":
        code = FileSystemProviderErrorCode.FileNotFound;
        break;
      case "EISDIR":
        code = FileSystemProviderErrorCode.FileIsADirectory;
        break;
      case "ENOTDIR":
        code = FileSystemProviderErrorCode.FileNotADirectory;
        break;
      case "EEXIST":
        code = FileSystemProviderErrorCode.FileExists;
        break;
      case "EPERM":
      case "EACCES":
        code = FileSystemProviderErrorCode.NoPermissions;
        break;
      case "ERR_UNC_HOST_NOT_ALLOWED":
        resultError = `${error.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`;
        code = FileSystemProviderErrorCode.Unknown;
        break;
      default:
        code = FileSystemProviderErrorCode.Unknown;
    }
    return $xm(resultError, code);
  }
  async jb(resource, error) {
    let fileSystemProviderWriteError = this.ib(error);
    if (resource && fileSystemProviderWriteError.code === FileSystemProviderErrorCode.NoPermissions) {
      try {
        const { stat: stat2 } = await SymlinkSupport.stat(this.J(resource));
        if (!(stat2.mode & 128)) {
          fileSystemProviderWriteError = $xm(error, FileSystemProviderErrorCode.FileWriteLocked);
        }
      } catch (error2) {
        this.a.trace(error2);
      }
    }
    return fileSystemProviderWriteError;
  }
};

// out-build/vs/workbench/api/node/extHostDiskFileSystemProvider.js
var $Dzc = class $Dzc2 {
  constructor(extHostConsumerFileSystem, logService) {
    extHostConsumerFileSystem.addFileSystemProvider(Schemas.file, new DiskFileSystemProviderAdapter(logService), { isCaseSensitive: $n });
  }
};
$Dzc = __decorate([
  __param(0, $cxc),
  __param(1, $wn)
], $Dzc);
var DiskFileSystemProviderAdapter = class {
  constructor(b) {
    this.b = b;
    this.a = new $qy(this.b);
  }
  async stat(uri) {
    const stat2 = await this.a.stat(uri);
    return {
      type: stat2.type,
      ctime: stat2.ctime,
      mtime: stat2.mtime,
      size: stat2.size,
      permissions: stat2.permissions === FilePermission.Readonly ? 1 : void 0
    };
  }
  readDirectory(uri) {
    return this.a.readdir(uri);
  }
  createDirectory(uri) {
    return this.a.mkdir(uri);
  }
  readFile(uri) {
    return this.a.readFile(uri);
  }
  writeFile(uri, content, options2) {
    return this.a.writeFile(uri, content, { ...options2, unlock: false, atomic: false });
  }
  delete(uri, options2) {
    return this.a.delete(uri, { ...options2, useTrash: false, atomic: false });
  }
  rename(oldUri, newUri, options2) {
    return this.a.rename(oldUri, newUri, options2);
  }
  copy(source, destination, options2) {
    return this.a.copy(source, destination, options2);
  }
  // --- Not Implemented ---
  get onDidChangeFile() {
    throw new Error("Method not implemented.");
  }
  watch(uri, options2) {
    throw new Error("Method not implemented.");
  }
};

// out-build/vs/workbench/api/node/extHostExtensionService.js
import { createRequire as createRequire2 } from "node:module";
var require3 = createRequire2(import.meta.url);
var NodeModuleRequireInterceptor = class extends $5yc {
  j() {
    const that = this;
    const node_module = require3("module");
    const originalLoad = node_module._load;
    node_module._load = function load(request, parent, isMain) {
      request = applyAlternatives(request);
      if (!that.a.has(request)) {
        return originalLoad.apply(this, arguments);
      }
      return that.a.get(request).load(request, URI.file($6s(parent.filename)), (request2) => originalLoad.apply(this, [request2, parent, isMain]));
    };
    const originalLookup = node_module._resolveLookupPaths;
    node_module._resolveLookupPaths = (request, parent) => {
      return originalLookup.call(this, applyAlternatives(request), parent);
    };
    const originalResolveFilename = node_module._resolveFilename;
    node_module._resolveFilename = function resolveFilename(request, parent, isMain, options2) {
      if (request === "vsda" && Array.isArray(options2?.paths) && options2.paths.length === 0) {
        options2.paths = node_module._nodeModulePaths(import.meta.dirname);
      }
      return originalResolveFilename.call(this, request, parent, isMain, options2);
    };
    const applyAlternatives = (request) => {
      for (const alternativeModuleName of that.b) {
        const alternative = alternativeModuleName(request);
        if (alternative) {
          request = alternative;
          break;
        }
      }
      return request;
    };
  }
};
var $Ezc = class extends $Kxc {
  constructor() {
    super(...arguments);
    this.extensionRuntime = ExtensionRuntime.Node;
  }
  async vb() {
    this.h.createInstance($Czc);
    const extensionApiFactory = this.h.invokeFunction($1yc);
    this.h.createInstance($Bzc);
    if (this.f.remote.isRemote && this.f.remote.authority) {
      const cliServer = this.h.createInstance($IW);
      process.env["VSCODE_IPC_HOOK_CLI"] = cliServer.ipcHandlePath;
    }
    this.h.createInstance($Dzc);
    const interceptor = this.h.createInstance(NodeModuleRequireInterceptor, extensionApiFactory, { mine: this.J, all: this.L });
    await interceptor.install();
    $S("code/extHost/didInitAPI");
    const configProvider = await this.m.getConfigProvider();
    await $Azc(this.j, configProvider, this, this.s, this.z, this.f, this.q);
    $S("code/extHost/didInitProxyResolver");
  }
  wb(extensionDescription) {
    return extensionDescription.main;
  }
  async xb(extension, module2, activationTimesBuilder) {
    if (module2.scheme !== Schemas.file) {
      throw new Error(`Cannot load URI: '${module2}', must be of file-scheme`);
    }
    let r = null;
    activationTimesBuilder.codeLoadingStart();
    this.s.trace(`ExtensionService#loadCommonJSModule ${module2.toString(true)}`);
    this.s.flush();
    const extensionId = extension?.identifier.value;
    if (extension) {
      await this.w.initializeLocalizedMessages(extension);
    }
    try {
      if (extensionId) {
        $S(`code/extHost/willLoadExtensionCode/${extensionId}`);
      }
      r = require3(module2.fsPath);
    } finally {
      if (extensionId) {
        $S(`code/extHost/didLoadExtensionCode/${extensionId}`);
      }
      activationTimesBuilder.codeLoadingStop();
    }
    return r;
  }
  async $setRemoteEnvironment(env2) {
    if (!this.f.remote.isRemote) {
      return;
    }
    for (const key in env2) {
      const value = env2[key];
      if (value === null) {
        delete process.env[key];
      } else {
        process.env[key] = value;
      }
    }
  }
};

// out-build/vs/workbench/api/node/extHostTunnelService.js
import * as fs5 from "fs";
import { exec as exec2 } from "child_process";

// out-build/vs/platform/remote/common/managedSocket.js
var $wQb = (path, query, deubgLabel) => {
  const buffer = new Uint8Array(16);
  for (let i = 0; i < 16; i++) {
    buffer[i] = Math.round(Math.random() * 256);
  }
  const nonce = $Wi($Ci.wrap(buffer));
  const headers = [
    `GET ws://localhost${path}?${query}&skipWebSocketFrames=true HTTP/1.1`,
    `Connection: Upgrade`,
    `Upgrade: websocket`,
    `Sec-WebSocket-Key: ${nonce}`
  ];
  return headers.join("\r\n") + "\r\n\r\n";
};
var $xQb = $Ci.fromString("\r\n\r\n");
async function $yQb(socket, path, query, debugLabel, half) {
  socket.write($Ci.fromString($wQb(path, query, debugLabel)));
  const d = new $2c();
  try {
    return await new Promise((resolve, reject) => {
      let dataSoFar;
      d.add(socket.onData((d_1) => {
        if (!dataSoFar) {
          dataSoFar = d_1;
        } else {
          dataSoFar = $Ci.concat([dataSoFar, d_1], dataSoFar.byteLength + d_1.byteLength);
        }
        const index = dataSoFar.indexOf($xQb);
        if (index === -1) {
          return;
        }
        resolve(socket);
        socket.pauseData();
        const rest = dataSoFar.slice(index + $xQb.byteLength);
        if (rest.byteLength) {
          half.onData.fire(rest);
        }
      }));
      d.add(socket.onClose((err) => reject(err ?? new Error("socket closed"))));
      d.add(socket.onEnd(() => reject(new Error("socket ended"))));
    });
  } catch (e) {
    socket.dispose();
    throw e;
  } finally {
    d.dispose();
  }
}
var $zQb = class extends $3c {
  constructor(g, half) {
    super();
    this.g = g;
    this.a = this.B(new $Ce());
    this.onData = (...args2) => {
      if (this.a.isPaused) {
        queueMicrotask(() => this.a.resume());
      }
      return this.a.event(...args2);
    };
    this.b = this.B(new $ze());
    this.onDidDispose = this.b.event;
    this.f = false;
    this.B(half.onData);
    this.B(half.onData.event((data) => this.a.fire(data)));
    this.onClose = this.B(half.onClose).event;
    this.onEnd = this.B(half.onEnd).event;
  }
  /** Pauses data events until a new listener comes in onData() */
  pauseData() {
    this.a.pause();
  }
  /** Flushes data to the socket. */
  drain() {
    return Promise.resolve();
  }
  /** Ends the remote socket. */
  end() {
    this.f = true;
    this.h();
  }
  traceSocketEvent(type, data) {
    SocketDiagnostics.traceSocketEvent(this, this.g, type, data);
  }
  dispose() {
    if (!this.f) {
      this.h();
    }
    this.b.fire();
    super.dispose();
  }
};

// out-build/vs/platform/sign/common/sign.js
var $kz = "signService";
var $lz = $Qk($kz);

// out-build/vs/platform/tunnel/node/tunnelService.js
import * as net4 from "net";
import * as os2 from "os";

// out-build/vs/base/node/ports.js
import * as net3 from "net";
var $1s = {
  1: true,
  // tcpmux
  7: true,
  // echo
  9: true,
  // discard
  11: true,
  // systat
  13: true,
  // daytime
  15: true,
  // netstat
  17: true,
  // qotd
  19: true,
  // chargen
  20: true,
  // ftp data
  21: true,
  // ftp access
  22: true,
  // ssh
  23: true,
  // telnet
  25: true,
  // smtp
  37: true,
  // time
  42: true,
  // name
  43: true,
  // nicname
  53: true,
  // domain
  69: true,
  // tftp
  77: true,
  // priv-rjs
  79: true,
  // finger
  87: true,
  // ttylink
  95: true,
  // supdup
  101: true,
  // hostriame
  102: true,
  // iso-tsap
  103: true,
  // gppitnp
  104: true,
  // acr-nema
  109: true,
  // pop2
  110: true,
  // pop3
  111: true,
  // sunrpc
  113: true,
  // auth
  115: true,
  // sftp
  117: true,
  // uucp-path
  119: true,
  // nntp
  123: true,
  // NTP
  135: true,
  // loc-srv /epmap
  137: true,
  // netbios
  139: true,
  // netbios
  143: true,
  // imap2
  161: true,
  // snmp
  179: true,
  // BGP
  389: true,
  // ldap
  427: true,
  // SLP (Also used by Apple Filing Protocol)
  465: true,
  // smtp+ssl
  512: true,
  // print / exec
  513: true,
  // login
  514: true,
  // shell
  515: true,
  // printer
  526: true,
  // tempo
  530: true,
  // courier
  531: true,
  // chat
  532: true,
  // netnews
  540: true,
  // uucp
  548: true,
  // AFP (Apple Filing Protocol)
  554: true,
  // rtsp
  556: true,
  // remotefs
  563: true,
  // nntp+ssl
  587: true,
  // smtp (rfc6409)
  601: true,
  // syslog-conn (rfc3195)
  636: true,
  // ldap+ssl
  989: true,
  // ftps-data
  990: true,
  // ftps
  993: true,
  // ldap+ssl
  995: true,
  // pop3+ssl
  1719: true,
  // h323gatestat
  1720: true,
  // h323hostcall
  1723: true,
  // pptp
  2049: true,
  // nfs
  3659: true,
  // apple-sasl / PasswordServer
  4045: true,
  // lockd
  5060: true,
  // sip
  5061: true,
  // sips
  6e3: true,
  // X11
  6566: true,
  // sane-port
  6665: true,
  // Alternate IRC [Apple addition]
  6666: true,
  // Alternate IRC [Apple addition]
  6667: true,
  // Standard IRC [Apple addition]
  6668: true,
  // Alternate IRC [Apple addition]
  6669: true,
  // Alternate IRC [Apple addition]
  6697: true,
  // IRC + TLS
  10080: true
  // Amanda
};
function $2s(startPort, giveUpAfter, timeout, hostname = "127.0.0.1") {
  let resolved = false;
  let timeoutHandle = void 0;
  let countTried = 1;
  const server = net3.createServer({ pauseOnConnect: true });
  function doResolve(port, resolve) {
    if (!resolved) {
      resolved = true;
      server.removeAllListeners();
      server.close();
      if (timeoutHandle) {
        clearTimeout(timeoutHandle);
      }
      resolve(port);
    }
  }
  return new Promise((resolve) => {
    timeoutHandle = setTimeout(() => {
      doResolve(0, resolve);
    }, timeout);
    server.on("listening", () => {
      doResolve(startPort, resolve);
    });
    server.on("error", (err) => {
      if (err && (err.code === "EADDRINUSE" || err.code === "EACCES") && countTried < giveUpAfter) {
        startPort++;
        countTried++;
        server.listen(startPort, hostname);
      } else {
        doResolve(0, resolve);
      }
    });
    server.on("close", () => {
      doResolve(0, resolve);
    });
    server.listen(startPort, hostname);
  });
}

// out-build/vs/platform/remote/common/remoteAgentConnection.js
var RECONNECT_TIMEOUT = 30 * 1e3;
var ConnectionType;
(function(ConnectionType2) {
  ConnectionType2[ConnectionType2["Management"] = 1] = "Management";
  ConnectionType2[ConnectionType2["ExtensionHost"] = 2] = "ExtensionHost";
  ConnectionType2[ConnectionType2["Tunnel"] = 3] = "Tunnel";
})(ConnectionType || (ConnectionType = {}));
function connectionTypeToString(connectionType) {
  switch (connectionType) {
    case 1:
      return "Management";
    case 2:
      return "ExtensionHost";
    case 3:
      return "Tunnel";
  }
}
function createTimeoutCancellation(millis) {
  const source = new $ad();
  setTimeout(() => source.cancel(), millis);
  return source.token;
}
function combineTimeoutCancellation(a, b) {
  if (a.isCancellationRequested || b.isCancellationRequested) {
    return CancellationToken.Cancelled;
  }
  const source = new $ad();
  a.onCancellationRequested(() => source.cancel());
  b.onCancellationRequested(() => source.cancel());
  return source.token;
}
var PromiseWithTimeout = class {
  get didTimeout() {
    return this.c === "timedout";
  }
  constructor(timeoutCancellationToken) {
    this.c = "pending";
    this.d = new $2c();
    ({ promise: this.promise, resolve: this.f, reject: this.g } = $Oh());
    if (timeoutCancellationToken.isCancellationRequested) {
      this.h();
    } else {
      this.d.add(timeoutCancellationToken.onCancellationRequested(() => this.h()));
    }
  }
  registerDisposable(disposable) {
    if (this.c === "pending") {
      this.d.add(disposable);
    } else {
      disposable.dispose();
    }
  }
  h() {
    if (this.c !== "pending") {
      return;
    }
    this.d.dispose();
    this.c = "timedout";
    this.g(this.i());
  }
  i() {
    const err = new Error("Time limit reached");
    err.code = "ETIMEDOUT";
    err.syscall = "connect";
    return err;
  }
  resolve(value) {
    if (this.c !== "pending") {
      return;
    }
    this.d.dispose();
    this.c = "resolved";
    this.f(value);
  }
  reject(err) {
    if (this.c !== "pending") {
      return;
    }
    this.d.dispose();
    this.c = "rejected";
    this.g(err);
  }
};
function readOneControlMessage(protocol, timeoutCancellationToken) {
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  result.registerDisposable(protocol.onControlMessage((raw) => {
    const msg = JSON.parse(raw.toString());
    const error = getErrorFromMessage(msg);
    if (error) {
      result.reject(error);
    } else {
      result.resolve(msg);
    }
  }));
  return result.promise;
}
function createSocket(logService, remoteSocketFactoryService, connectTo, path, query, debugConnectionType, debugLabel, timeoutCancellationToken) {
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  const sw = $te.create(false);
  logService.info(`Creating a socket (${debugLabel})...`);
  $S(`code/willCreateSocket/${debugConnectionType}`);
  remoteSocketFactoryService.connect(connectTo, path, query, debugLabel).then((socket) => {
    if (result.didTimeout) {
      $S(`code/didCreateSocketError/${debugConnectionType}`);
      logService.info(`Creating a socket (${debugLabel}) finished after ${sw.elapsed()} ms, but this is too late and has timed out already.`);
      socket?.dispose();
    } else {
      $S(`code/didCreateSocketOK/${debugConnectionType}`);
      logService.info(`Creating a socket (${debugLabel}) was successful after ${sw.elapsed()} ms.`);
      result.resolve(socket);
    }
  }, (err) => {
    $S(`code/didCreateSocketError/${debugConnectionType}`);
    logService.info(`Creating a socket (${debugLabel}) returned an error after ${sw.elapsed()} ms.`);
    logService.error(err);
    result.reject(err);
  });
  return result.promise;
}
function raceWithTimeoutCancellation(promise, timeoutCancellationToken) {
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  promise.then((res) => {
    if (!result.didTimeout) {
      result.resolve(res);
    }
  }, (err) => {
    if (!result.didTimeout) {
      result.reject(err);
    }
  });
  return result.promise;
}
async function connectToRemoteExtensionHostAgent(options2, connectionType, args2, timeoutCancellationToken) {
  const logPrefix = connectLogPrefix(options2, connectionType);
  options2.logService.trace(`${logPrefix} 1/6. invoking socketFactory.connect().`);
  let socket;
  try {
    socket = await createSocket(options2.logService, options2.remoteSocketFactoryService, options2.connectTo, $bh.getServerRootPath(), `reconnectionToken=${options2.reconnectionToken}&reconnection=${options2.reconnectionProtocol ? "true" : "false"}`, connectionTypeToString(connectionType), `renderer-${connectionTypeToString(connectionType)}-${options2.reconnectionToken}`, timeoutCancellationToken);
  } catch (error) {
    options2.logService.error(`${logPrefix} socketFactory.connect() failed or timed out. Error:`);
    options2.logService.error(error);
    throw error;
  }
  options2.logService.trace(`${logPrefix} 2/6. socketFactory.connect() was successful.`);
  let protocol;
  let ownsProtocol;
  if (options2.reconnectionProtocol) {
    options2.reconnectionProtocol.beginAcceptReconnection(socket, null);
    protocol = options2.reconnectionProtocol;
    ownsProtocol = false;
  } else {
    protocol = new $tu({ socket });
    ownsProtocol = true;
  }
  options2.logService.trace(`${logPrefix} 3/6. sending AuthRequest control message.`);
  const message = await raceWithTimeoutCancellation(options2.signService.createNewMessage($ps()), timeoutCancellationToken);
  const authRequest = {
    type: "auth",
    auth: options2.connectionToken || "00000000000000000000",
    data: message.data
  };
  protocol.sendControl($Ci.fromString(JSON.stringify(authRequest)));
  try {
    const msg = await readOneControlMessage(protocol, combineTimeoutCancellation(timeoutCancellationToken, createTimeoutCancellation(1e4)));
    if (msg.type !== "sign" || typeof msg.data !== "string") {
      const error = new Error("Unexpected handshake message");
      error.code = "VSCODE_CONNECTION_ERROR";
      throw error;
    }
    options2.logService.trace(`${logPrefix} 4/6. received SignRequest control message.`);
    const isValid = await raceWithTimeoutCancellation(options2.signService.validate(message, msg.signedData), timeoutCancellationToken);
    if (!isValid) {
      const error = new Error("Refused to connect to unsupported server");
      error.code = "VSCODE_CONNECTION_ERROR";
      throw error;
    }
    const signed = await raceWithTimeoutCancellation(options2.signService.sign(msg.data), timeoutCancellationToken);
    const connTypeRequest = {
      type: "connectionType",
      commit: options2.commit,
      signedData: signed,
      desiredConnectionType: connectionType
    };
    if (args2) {
      connTypeRequest.args = args2;
    }
    options2.logService.trace(`${logPrefix} 5/6. sending ConnectionTypeRequest control message.`);
    protocol.sendControl($Ci.fromString(JSON.stringify(connTypeRequest)));
    return { protocol, ownsProtocol };
  } catch (error) {
    if (error && error.code === "ETIMEDOUT") {
      options2.logService.error(`${logPrefix} the handshake timed out. Error:`);
      options2.logService.error(error);
    }
    if (error && error.code === "VSCODE_CONNECTION_ERROR") {
      options2.logService.error(`${logPrefix} received error control message when negotiating connection. Error:`);
      options2.logService.error(error);
    }
    if (ownsProtocol) {
      safeDisposeProtocolAndSocket(protocol);
    }
    throw error;
  }
}
async function doConnectRemoteAgentTunnel(options2, startParams, timeoutCancellationToken) {
  const startTime = Date.now();
  const logPrefix = connectLogPrefix(
    options2,
    3
    /* ConnectionType.Tunnel */
  );
  const { protocol } = await connectToRemoteExtensionHostAgent(options2, 3, startParams, timeoutCancellationToken);
  options2.logService.trace(`${logPrefix} 6/6. handshake finished, connection is up and running after ${logElapsed(startTime)}!`);
  return protocol;
}
async function resolveConnectionOptions(options2, reconnectionToken, reconnectionProtocol) {
  const { connectTo, connectionToken } = await options2.addressProvider.getAddress();
  return {
    commit: options2.commit,
    quality: options2.quality,
    connectTo,
    connectionToken,
    reconnectionToken,
    reconnectionProtocol,
    remoteSocketFactoryService: options2.remoteSocketFactoryService,
    signService: options2.signService,
    logService: options2.logService
  };
}
async function $kC(options2, tunnelRemoteHost, tunnelRemotePort) {
  const simpleOptions = await resolveConnectionOptions(options2, $ps(), null);
  const protocol = await doConnectRemoteAgentTunnel(simpleOptions, { host: tunnelRemoteHost, port: tunnelRemotePort }, CancellationToken.None);
  return protocol;
}
function sleep(seconds) {
  return $Hh((token) => {
    return new Promise((resolve, reject) => {
      const timeout = setTimeout(resolve, seconds * 1e3);
      token.onCancellationRequested(() => {
        clearTimeout(timeout);
        resolve();
      });
    });
  });
}
var PersistentConnectionEventType;
(function(PersistentConnectionEventType2) {
  PersistentConnectionEventType2[PersistentConnectionEventType2["ConnectionLost"] = 0] = "ConnectionLost";
  PersistentConnectionEventType2[PersistentConnectionEventType2["ReconnectionWait"] = 1] = "ReconnectionWait";
  PersistentConnectionEventType2[PersistentConnectionEventType2["ReconnectionRunning"] = 2] = "ReconnectionRunning";
  PersistentConnectionEventType2[PersistentConnectionEventType2["ReconnectionPermanentFailure"] = 3] = "ReconnectionPermanentFailure";
  PersistentConnectionEventType2[PersistentConnectionEventType2["ConnectionGain"] = 4] = "ConnectionGain";
})(PersistentConnectionEventType || (PersistentConnectionEventType = {}));
var $lC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.type = 0;
  }
};
var $mC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, durationSeconds, c) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.durationSeconds = durationSeconds;
    this.c = c;
    this.type = 1;
  }
  skipWait() {
    this.c.cancel();
  }
};
var $nC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.type = 2;
  }
};
var $oC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.type = 4;
  }
};
var $pC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt, handled) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.handled = handled;
    this.type = 3;
  }
};
var $qC = class _$qC extends $3c {
  static triggerPermanentFailure(millisSinceLastIncomingData, attempt, handled) {
    this._permanentFailure = true;
    this.f = millisSinceLastIncomingData;
    this.g = attempt;
    this.h = handled;
    this.j.forEach((instance) => instance.D(this.f, this.g, this.h));
  }
  static debugTriggerReconnection() {
    this.j.forEach((instance) => instance.y());
  }
  static debugPauseSocketWriting() {
    this.j.forEach((instance) => instance.F());
  }
  static {
    this._permanentFailure = false;
  }
  static {
    this.f = 0;
  }
  static {
    this.g = 0;
  }
  static {
    this.h = false;
  }
  static {
    this.j = [];
  }
  get n() {
    return this.c || _$qC._permanentFailure;
  }
  constructor(t, u, reconnectionToken, protocol, w) {
    super();
    this.t = t;
    this.u = u;
    this.reconnectionToken = reconnectionToken;
    this.protocol = protocol;
    this.w = w;
    this.m = this.B(new $ze());
    this.onDidStateChange = this.m.event;
    this.c = false;
    this.r = false;
    this.s = false;
    this.m.fire(new $oC(this.reconnectionToken, 0, 0));
    this.B(protocol.onSocketClose((e) => {
      const logPrefix = commonLogPrefix(this.t, this.reconnectionToken, true);
      if (!e) {
        this.u.logService.info(`${logPrefix} received socket close event.`);
      } else if (e.type === 0) {
        this.u.logService.info(`${logPrefix} received socket close event (hadError: ${e.hadError}).`);
        if (e.error) {
          this.u.logService.error(e.error);
        }
      } else {
        this.u.logService.info(`${logPrefix} received socket close event (wasClean: ${e.wasClean}, code: ${e.code}, reason: ${e.reason}).`);
        if (e.event) {
          this.u.logService.error(e.event);
        }
      }
      this.y();
    }));
    this.B(protocol.onSocketTimeout((e) => {
      const logPrefix = commonLogPrefix(this.t, this.reconnectionToken, true);
      this.u.logService.info(`${logPrefix} received socket timeout event (unacknowledgedMsgCount: ${e.unacknowledgedMsgCount}, timeSinceOldestUnacknowledgedMsg: ${e.timeSinceOldestUnacknowledgedMsg}, timeSinceLastReceivedSomeData: ${e.timeSinceLastReceivedSomeData}).`);
      this.y();
    }));
    _$qC.j.push(this);
    this.B($1c(() => {
      const myIndex = _$qC.j.indexOf(this);
      if (myIndex >= 0) {
        _$qC.j.splice(myIndex, 1);
      }
    }));
    if (this.n) {
      this.D(_$qC.f, _$qC.g, _$qC.h);
    }
  }
  dispose() {
    super.dispose();
    this.s = true;
  }
  async y() {
    if (this.r) {
      return;
    }
    try {
      this.r = true;
      await this.z();
    } finally {
      this.r = false;
    }
  }
  async z() {
    if (this.n || this.s) {
      return;
    }
    const logPrefix = commonLogPrefix(this.t, this.reconnectionToken, true);
    this.u.logService.info(`${logPrefix} starting reconnecting loop. You can get more information with the trace log level.`);
    this.m.fire(new $lC(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData()));
    const TIMES = [0, 5, 5, 10, 10, 10, 10, 10, 30];
    let attempt = -1;
    do {
      attempt++;
      const waitTime = attempt < TIMES.length ? TIMES[attempt] : TIMES[TIMES.length - 1];
      try {
        if (waitTime > 0) {
          const sleepPromise = sleep(waitTime);
          this.m.fire(new $mC(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), waitTime, sleepPromise));
          this.u.logService.info(`${logPrefix} waiting for ${waitTime} seconds before reconnecting...`);
          try {
            await sleepPromise;
          } catch {
          }
        }
        if (this.n) {
          this.u.logService.error(`${logPrefix} permanent failure occurred while running the reconnecting loop.`);
          break;
        }
        this.m.fire(new $nC(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), attempt + 1));
        this.u.logService.info(`${logPrefix} resolving connection...`);
        const simpleOptions = await resolveConnectionOptions(this.u, this.reconnectionToken, this.protocol);
        this.u.logService.info(`${logPrefix} connecting to ${simpleOptions.connectTo}...`);
        await this.G(simpleOptions, createTimeoutCancellation(RECONNECT_TIMEOUT));
        this.u.logService.info(`${logPrefix} reconnected!`);
        this.m.fire(new $oC(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), attempt + 1));
        break;
      } catch (err) {
        if (err.code === "VSCODE_CONNECTION_ERROR") {
          this.u.logService.error(`${logPrefix} A permanent error occurred in the reconnecting loop! Will give up now! Error:`);
          this.u.logService.error(err);
          this.C(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
          break;
        }
        if (attempt > 360) {
          this.u.logService.error(`${logPrefix} An error occurred while reconnecting, but it will be treated as a permanent error because the reconnection grace time has expired! Will give up now! Error:`);
          this.u.logService.error(err);
          this.C(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
          break;
        }
        if ($eC.isTemporarilyNotAvailable(err)) {
          this.u.logService.info(`${logPrefix} A temporarily not available error occurred while trying to reconnect, will try again...`);
          this.u.logService.trace(err);
          continue;
        }
        if ((err.code === "ETIMEDOUT" || err.code === "ENETUNREACH" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET") && err.syscall === "connect") {
          this.u.logService.info(`${logPrefix} A network error occurred while trying to reconnect, will try again...`);
          this.u.logService.trace(err);
          continue;
        }
        if ($kb(err)) {
          this.u.logService.info(`${logPrefix} A promise cancelation error occurred while trying to reconnect, will try again...`);
          this.u.logService.trace(err);
          continue;
        }
        if (err instanceof $eC) {
          this.u.logService.error(`${logPrefix} A RemoteAuthorityResolverError occurred while trying to reconnect. Will give up now! Error:`);
          this.u.logService.error(err);
          this.C(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, $eC.isHandled(err));
          break;
        }
        this.u.logService.error(`${logPrefix} An unknown error occurred while trying to reconnect, since this is an unknown case, it will be treated as a permanent error! Will give up now! Error:`);
        this.u.logService.error(err);
        this.C(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
        break;
      }
    } while (!this.n && !this.s);
  }
  C(millisSinceLastIncomingData, attempt, handled) {
    if (this.w) {
      _$qC.triggerPermanentFailure(millisSinceLastIncomingData, attempt, handled);
    } else {
      this.D(millisSinceLastIncomingData, attempt, handled);
    }
  }
  D(millisSinceLastIncomingData, attempt, handled) {
    this.m.fire(new $pC(this.reconnectionToken, millisSinceLastIncomingData, attempt, handled));
    safeDisposeProtocolAndSocket(this.protocol);
  }
  F() {
    this.protocol.pauseSocketWriting();
  }
};
function safeDisposeProtocolAndSocket(protocol) {
  try {
    protocol.acceptDisconnect();
    const socket = protocol.getSocket();
    protocol.dispose();
    socket.dispose();
  } catch (err) {
    $gb(err);
  }
}
function getErrorFromMessage(msg) {
  if (msg && msg.type === "error") {
    const error = new Error(`Connection error: ${msg.reason}`);
    error.code = "VSCODE_CONNECTION_ERROR";
    return error;
  }
  return null;
}
function stringRightPad(str, len) {
  while (str.length < len) {
    str += " ";
  }
  return str;
}
function _commonLogPrefix(connectionType, reconnectionToken) {
  return `[remote-connection][${stringRightPad(connectionTypeToString(connectionType), 13)}][${reconnectionToken.substr(0, 5)}\u2026]`;
}
function commonLogPrefix(connectionType, reconnectionToken, isReconnect) {
  return `${_commonLogPrefix(connectionType, reconnectionToken)}[${isReconnect ? "reconnect" : "initial"}]`;
}
function connectLogPrefix(options2, connectionType) {
  return `${commonLogPrefix(connectionType, options2.reconnectionToken, !!options2.reconnectionProtocol)}[${options2.connectTo}]`;
}
function logElapsed(startTime) {
  return `${Date.now() - startTime} ms`;
}

// out-build/vs/platform/remote/common/remoteSocketFactoryService.js
var $gC = $Qk("remoteSocketFactoryService");

// out-build/vs/platform/tunnel/node/tunnelService.js
async function createRemoteTunnel(options2, defaultTunnelHost, tunnelRemoteHost, tunnelRemotePort, tunnelLocalPort) {
  let readyTunnel;
  for (let attempts = 3; attempts; attempts--) {
    readyTunnel?.dispose();
    const tunnel = new $FC(options2, defaultTunnelHost, tunnelRemoteHost, tunnelRemotePort, tunnelLocalPort);
    readyTunnel = await tunnel.waitForReady();
    if (tunnelLocalPort && $1s[tunnelLocalPort] || !$1s[readyTunnel.tunnelLocalPort]) {
      break;
    }
  }
  return readyTunnel;
}
var $FC = class extends $3c {
  constructor(options2, m, tunnelRemoteHost, tunnelRemotePort, n) {
    super();
    this.m = m;
    this.n = n;
    this.privacy = TunnelPrivacyId.Private;
    this.j = /* @__PURE__ */ new Map();
    this.a = options2;
    this.b = net4.createServer();
    this.c = new $Uh();
    this.f = () => this.c.open();
    this.b.on("listening", this.f);
    this.g = (socket) => this.r(socket);
    this.b.on("connection", this.g);
    this.h = () => {
    };
    this.b.on("error", this.h);
    this.tunnelRemotePort = tunnelRemotePort;
    this.tunnelRemoteHost = tunnelRemoteHost;
  }
  async dispose() {
    super.dispose();
    this.b.removeListener("listening", this.f);
    this.b.removeListener("connection", this.g);
    this.b.removeListener("error", this.h);
    this.b.close();
    const disposers = Array.from(this.j.values());
    disposers.forEach((disposer) => {
      disposer();
    });
  }
  async waitForReady() {
    const startPort = this.n ?? this.tunnelRemotePort;
    const hostname = $BC(this.m) ? "0.0.0.0" : "127.0.0.1";
    let localPort = await $2s(startPort, 2, 1e3, hostname);
    let address = null;
    this.b.listen(localPort, this.m);
    await this.c.wait();
    address = this.b.address();
    if (!address) {
      localPort = 0;
      this.b.listen(localPort, this.m);
      await this.c.wait();
      address = this.b.address();
    }
    this.tunnelLocalPort = address.port;
    this.localAddress = `${this.tunnelRemoteHost === "127.0.0.1" ? "127.0.0.1" : "localhost"}:${address.port}`;
    return this;
  }
  async r(localSocket) {
    localSocket.pause();
    const tunnelRemoteHost = $zC(this.tunnelRemoteHost) || $BC(this.tunnelRemoteHost) ? "localhost" : this.tunnelRemoteHost;
    const protocol = await $kC(this.a, tunnelRemoteHost, this.tunnelRemotePort);
    const remoteSocket = protocol.getSocket();
    const dataChunk = protocol.readEntireBuffer();
    protocol.dispose();
    if (dataChunk.byteLength > 0) {
      localSocket.write(dataChunk.buffer);
    }
    localSocket.on("end", () => {
      if (localSocket.localAddress) {
        this.j.delete(localSocket.localAddress);
      }
      remoteSocket.end();
    });
    localSocket.on("close", () => remoteSocket.end());
    localSocket.on("error", () => {
      if (localSocket.localAddress) {
        this.j.delete(localSocket.localAddress);
      }
      if (remoteSocket instanceof $uu) {
        remoteSocket.socket.destroy();
      } else {
        remoteSocket.end();
      }
    });
    if (remoteSocket instanceof $uu) {
      this.t(localSocket, remoteSocket);
    } else {
      this.s(localSocket, remoteSocket);
    }
    if (localSocket.localAddress) {
      this.j.set(localSocket.localAddress, () => {
        localSocket.end();
        remoteSocket.end();
      });
    }
  }
  s(localSocket, remoteSocket) {
    remoteSocket.onClose(() => localSocket.destroy());
    remoteSocket.onEnd(() => localSocket.end());
    remoteSocket.onData((d) => localSocket.write(d.buffer));
    localSocket.on("data", (d) => remoteSocket.write($Ci.wrap(d)));
    localSocket.resume();
  }
  t(localSocket, remoteNodeSocket) {
    const remoteSocket = remoteNodeSocket.socket;
    remoteSocket.on("end", () => localSocket.end());
    remoteSocket.on("close", () => localSocket.end());
    remoteSocket.on("error", () => {
      localSocket.destroy();
    });
    remoteSocket.pipe(localSocket);
    localSocket.pipe(remoteSocket);
  }
};
var $GC = class $GC2 extends $EC {
  constructor(H, logService, I, J, configurationService) {
    super(logService, configurationService);
    this.H = H;
    this.I = I;
    this.J = J;
  }
  isPortPrivileged(port) {
    return $CC(port, this.t, OS, os2.release());
  }
  F(addressOrTunnelProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol) {
    const existing = this.D(remoteHost, remotePort);
    if (existing) {
      ++existing.refcount;
      return existing.value;
    }
    if ($vC(addressOrTunnelProvider)) {
      return this.G(addressOrTunnelProvider, remoteHost, remotePort, localPort, elevateIfNeeded, privacy, protocol);
    } else {
      this.r.trace(`ForwardedPorts: (TunnelService) Creating tunnel without provider ${remoteHost}:${remotePort} on local port ${localPort}.`);
      const options2 = {
        commit: this.J.commit,
        quality: this.J.quality,
        addressProvider: addressOrTunnelProvider,
        remoteSocketFactoryService: this.H,
        signService: this.I,
        logService: this.r,
        ipcLogger: null
      };
      const tunnel = createRemoteTunnel(options2, localHost, remoteHost, remotePort, localPort);
      this.r.trace("ForwardedPorts: (TunnelService) Tunnel created without provider.");
      this.z(remoteHost, remotePort, tunnel);
      return tunnel;
    }
  }
};
$GC = __decorate([
  __param(0, $gC),
  __param(1, $wn),
  __param(2, $lz),
  __param(3, $Vu),
  __param(4, $kl)
], $GC);
var $HC = class $HC2 extends $GC {
  constructor(remoteSocketFactoryService, logService, signService, productService, configurationService) {
    super(remoteSocketFactoryService, logService, signService, productService, configurationService);
  }
};
$HC = __decorate([
  __param(0, $gC),
  __param(1, $wn),
  __param(2, $lz),
  __param(3, $Vu),
  __param(4, $kl)
], $HC);
var $IC = class $IC2 extends $3c {
  constructor(b, c, f, g, h) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h;
    this.a = /* @__PURE__ */ new Map();
  }
  async openTunnel(authority, addressProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol) {
    this.c.trace(`ForwardedPorts: (SharedTunnelService) openTunnel request for ${remoteHost}:${remotePort} on local port ${localPort}.`);
    if (!this.a.has(authority)) {
      const tunnelService = new $HC(this.b, this.c, this.g, this.f, this.h);
      this.B(tunnelService);
      this.a.set(authority, tunnelService);
      tunnelService.onTunnelClosed(async () => {
        if ((await tunnelService.tunnels).length === 0) {
          tunnelService.dispose();
          this.a.delete(authority);
        }
      });
    }
    return this.a.get(authority).openTunnel(addressProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol);
  }
};
$IC = __decorate([
  __param(0, $gC),
  __param(1, $wn),
  __param(2, $Vu),
  __param(3, $lz),
  __param(4, $kl)
], $IC);

// out-build/vs/platform/dialogs/common/dialogs.js
var $Yv = $Qk("dialogService");
var DialogKind;
(function(DialogKind2) {
  DialogKind2[DialogKind2["Confirmation"] = 1] = "Confirmation";
  DialogKind2[DialogKind2["Prompt"] = 2] = "Prompt";
  DialogKind2[DialogKind2["Input"] = 3] = "Input";
})(DialogKind || (DialogKind = {}));
var $1v = $Qk("fileDialogService");
var ConfirmResult;
(function(ConfirmResult2) {
  ConfirmResult2[ConfirmResult2["SAVE"] = 0] = "SAVE";
  ConfirmResult2[ConfirmResult2["DONT_SAVE"] = 1] = "DONT_SAVE";
  ConfirmResult2[ConfirmResult2["CANCEL"] = 2] = "CANCEL";
})(ConfirmResult || (ConfirmResult = {}));

// out-build/vs/workbench/services/remote/common/tunnelModel.js
var MISMATCH_LOCAL_PORT_COOLDOWN = 10 * 1e3;
var TUNNELS_TO_RESTORE = "remote.tunnels.toRestore";
var TUNNELS_TO_RESTORE_EXPIRATION = "remote.tunnels.toRestoreExpiration";
var RESTORE_EXPIRATION_TIME = 1e3 * 60 * 60 * 24 * 14;
var $VS = "onTunnel";
var $WS = new $nn("forwardedPortsViewEnabled", false, localize(13093, null));
var $XS = new $nn("forwardedPortsViewOnlyEnabled", false, localize(13094, null));
function $YS(address) {
  const matches = address.match(/^([a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*:)?([0-9]+)$/);
  if (!matches) {
    return void 0;
  }
  return { host: matches[1]?.substring(0, matches[1].length - 1) || "localhost", port: Number(matches[2]) };
}
var TunnelCloseReason;
(function(TunnelCloseReason2) {
  TunnelCloseReason2["Other"] = "Other";
  TunnelCloseReason2["User"] = "User";
  TunnelCloseReason2["AutoForwardEnd"] = "AutoForwardEnd";
})(TunnelCloseReason || (TunnelCloseReason = {}));
var TunnelSource;
(function(TunnelSource2) {
  TunnelSource2[TunnelSource2["User"] = 0] = "User";
  TunnelSource2[TunnelSource2["Auto"] = 1] = "Auto";
  TunnelSource2[TunnelSource2["Extension"] = 2] = "Extension";
})(TunnelSource || (TunnelSource = {}));
var $ZS = {
  source: TunnelSource.User,
  description: localize(13095, null)
};
var $1S = {
  source: TunnelSource.Auto,
  description: localize(13096, null)
};
function $2S(map, host, port) {
  const initialAddress = map.get($4S(host, port));
  if (initialAddress) {
    return initialAddress;
  }
  if ($zC(host)) {
    for (const testHost of $yC) {
      const testAddress = $4S(testHost, port);
      if (map.has(testAddress)) {
        return map.get(testAddress);
      }
    }
  } else if ($BC(host)) {
    for (const testHost of $AC) {
      const testAddress = $4S(testHost, port);
      if (map.has(testAddress)) {
        return map.get(testAddress);
      }
    }
  }
  return void 0;
}
function $3S(map, host, port) {
  const originalAddress = $2S(map, host, port);
  if (originalAddress) {
    return originalAddress;
  }
  const otherHost = $BC(host) ? "localhost" : $zC(host) ? "0.0.0.0" : void 0;
  if (otherHost) {
    return $2S(map, otherHost, port);
  }
  return void 0;
}
function $4S(host, port) {
  return host + ":" + port;
}
var OnPortForward;
(function(OnPortForward2) {
  OnPortForward2["Notify"] = "notify";
  OnPortForward2["OpenBrowser"] = "openBrowser";
  OnPortForward2["OpenBrowserOnce"] = "openBrowserOnce";
  OnPortForward2["OpenPreview"] = "openPreview";
  OnPortForward2["Silent"] = "silent";
  OnPortForward2["Ignore"] = "ignore";
})(OnPortForward || (OnPortForward = {}));
function $5S(candidate) {
  return candidate && "host" in candidate && typeof candidate.host === "string" && "port" in candidate && typeof candidate.port === "number" && (!("detail" in candidate) || typeof candidate.detail === "string") && (!("pid" in candidate) || typeof candidate.pid === "string");
}
var $6S = class _$6S extends $3c {
  static {
    this.c = "remote.portsAttributes";
  }
  static {
    this.f = "remote.otherPortsAttributes";
  }
  static {
    this.g = /^(\d+)\-(\d+)$/;
  }
  static {
    this.h = /^([a-z0-9\-]+):(\d{1,5})$/;
  }
  constructor(r) {
    super();
    this.r = r;
    this.j = [];
    this.n = new $ze();
    this.onDidChangeAttributes = this.n.event;
    this.B(r.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(_$6S.c) || e.affectsConfiguration(_$6S.f)) {
        this.s();
      }
    }));
    this.s();
  }
  s() {
    this.j = this.y();
    this.n.fire();
  }
  getAttributes(port, host, commandLine) {
    let index = this.w(port, host, commandLine, this.j, 0);
    const attributes = {
      label: void 0,
      onAutoForward: void 0,
      elevateIfNeeded: void 0,
      requireLocalPort: void 0,
      protocol: void 0
    };
    while (index >= 0) {
      const found = this.j[index];
      if (found.key === port) {
        attributes.onAutoForward = found.onAutoForward ?? attributes.onAutoForward;
        attributes.elevateIfNeeded = found.elevateIfNeeded !== void 0 ? found.elevateIfNeeded : attributes.elevateIfNeeded;
        attributes.label = found.label ?? attributes.label;
        attributes.requireLocalPort = found.requireLocalPort;
        attributes.protocol = found.protocol;
      } else {
        attributes.onAutoForward = attributes.onAutoForward ?? found.onAutoForward;
        attributes.elevateIfNeeded = attributes.elevateIfNeeded !== void 0 ? attributes.elevateIfNeeded : found.elevateIfNeeded;
        attributes.label = attributes.label ?? found.label;
        attributes.requireLocalPort = attributes.requireLocalPort !== void 0 ? attributes.requireLocalPort : void 0;
        attributes.protocol = attributes.protocol ?? found.protocol;
      }
      index = this.w(port, host, commandLine, this.j, index + 1);
    }
    if (attributes.onAutoForward !== void 0 || attributes.elevateIfNeeded !== void 0 || attributes.label !== void 0 || attributes.requireLocalPort !== void 0 || attributes.protocol !== void 0) {
      return attributes;
    }
    return this.C();
  }
  t(value) {
    return value.start !== void 0 && value.end !== void 0;
  }
  u(value) {
    return value.host !== void 0 && value.port !== void 0 && $zg(value.host) && $Dg(value.port);
  }
  w(port, host, commandLine, attributes, fromIndex) {
    if (fromIndex >= attributes.length) {
      return -1;
    }
    const shouldUseHost = !$zC(host) && !$BC(host);
    const sliced = attributes.slice(fromIndex);
    const foundIndex = sliced.findIndex((value) => {
      if ($Dg(value.key)) {
        return shouldUseHost ? false : value.key === port;
      } else if (this.t(value.key)) {
        return shouldUseHost ? false : port >= value.key.start && port <= value.key.end;
      } else if (this.u(value.key)) {
        return port === value.key.port && host === value.key.host;
      } else {
        return commandLine ? value.key.test(commandLine) : false;
      }
    });
    return foundIndex >= 0 ? foundIndex + fromIndex : -1;
  }
  y() {
    const settingValue = this.r.getValue(_$6S.c);
    if (!settingValue || !$Bg(settingValue)) {
      return [];
    }
    const attributes = [];
    for (const attributesKey in settingValue) {
      if (attributesKey === void 0) {
        continue;
      }
      const setting = settingValue[attributesKey];
      let key = void 0;
      if (Number(attributesKey)) {
        key = Number(attributesKey);
      } else if ($zg(attributesKey)) {
        if (_$6S.g.test(attributesKey)) {
          const match = attributesKey.match(_$6S.g);
          key = { start: Number(match[1]), end: Number(match[2]) };
        } else if (_$6S.h.test(attributesKey)) {
          const match = attributesKey.match(_$6S.h);
          key = { host: match[1], port: Number(match[2]) };
        } else {
          let regTest = void 0;
          try {
            regTest = RegExp(attributesKey);
          } catch (e) {
          }
          if (regTest) {
            key = regTest;
          }
        }
      }
      if (!key) {
        continue;
      }
      attributes.push({
        key,
        elevateIfNeeded: setting.elevateIfNeeded,
        onAutoForward: setting.onAutoForward,
        label: setting.label,
        requireLocalPort: setting.requireLocalPort,
        protocol: setting.protocol
      });
    }
    const defaults = this.r.getValue(_$6S.f);
    if (defaults) {
      this.m = {
        elevateIfNeeded: defaults.elevateIfNeeded,
        label: defaults.label,
        onAutoForward: defaults.onAutoForward,
        requireLocalPort: defaults.requireLocalPort,
        protocol: defaults.protocol
      };
    }
    return this.z(attributes);
  }
  z(attributes) {
    function getVal(item, thisRef) {
      if ($Dg(item.key)) {
        return item.key;
      } else if (thisRef.t(item.key)) {
        return item.key.start;
      } else if (thisRef.u(item.key)) {
        return item.key.port;
      } else {
        return Number.MAX_VALUE;
      }
    }
    return attributes.sort((a, b) => {
      return getVal(a, this) - getVal(b, this);
    });
  }
  C() {
    return this.m;
  }
  static providedActionToAction(providedAction) {
    switch (providedAction) {
      case ProvidedOnAutoForward.Notify:
        return OnPortForward.Notify;
      case ProvidedOnAutoForward.OpenBrowser:
        return OnPortForward.OpenBrowser;
      case ProvidedOnAutoForward.OpenBrowserOnce:
        return OnPortForward.OpenBrowserOnce;
      case ProvidedOnAutoForward.OpenPreview:
        return OnPortForward.OpenPreview;
      case ProvidedOnAutoForward.Silent:
        return OnPortForward.Silent;
      case ProvidedOnAutoForward.Ignore:
        return OnPortForward.Ignore;
      default:
        return void 0;
    }
  }
  async addAttributes(port, attributes, target) {
    const settingValue = this.r.inspect(_$6S.c);
    const remoteValue = settingValue.userRemoteValue;
    let newRemoteValue;
    if (!remoteValue || !$Bg(remoteValue)) {
      newRemoteValue = {};
    } else {
      newRemoteValue = $Lv(remoteValue);
    }
    if (!newRemoteValue[`${port}`]) {
      newRemoteValue[`${port}`] = {};
    }
    for (const attribute in attributes) {
      newRemoteValue[`${port}`][attribute] = attributes[attribute];
    }
    return this.r.updateValue(_$6S.c, newRemoteValue, target);
  }
};
var $7S = class $7S2 extends $3c {
  constructor(H, I, J, L, M, N, O, P, Q, R) {
    super();
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.c = /* @__PURE__ */ new Map();
    this.g = new $ze();
    this.onForwardPort = this.g.event;
    this.h = new $ze();
    this.onClosePort = this.h.event;
    this.j = new $ze();
    this.onPortName = this.j.event;
    this.n = new $ze();
    this.onCandidatesChanged = this.n.event;
    this.t = new $ze();
    this.onEnvironmentTunnelsSet = this.t.event;
    this.u = false;
    this.w = void 0;
    this.z = false;
    this.C = new $ze();
    this.D = /* @__PURE__ */ new Map();
    this.F = /* @__PURE__ */ new Map();
    this.G = [];
    this.U = false;
    this.eb = /* @__PURE__ */ new Date();
    this.configPortsAttributes = new $6S(J);
    this.s = this.bb();
    this.B(this.configPortsAttributes.onDidChangeAttributes(this.kb, this));
    this.forwarded = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.H.tunnels.then(async (tunnels) => {
      const attributes = await this.getAttributes(tunnels.map((tunnel) => {
        return { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost };
      }));
      for (const tunnel of tunnels) {
        if (tunnel.localAddress) {
          const key = $4S(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
          const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
          this.forwarded.set(key, {
            remotePort: tunnel.tunnelRemotePort,
            remoteHost: tunnel.tunnelRemoteHost,
            localAddress: tunnel.localAddress,
            protocol: attributes?.get(tunnel.tunnelRemotePort)?.protocol ?? TunnelProtocol.Http,
            localUri: await this.Y(tunnel.localAddress, attributes?.get(tunnel.tunnelRemotePort)),
            localPort: tunnel.tunnelLocalPort,
            name: attributes?.get(tunnel.tunnelRemotePort)?.label,
            runningProcess: matchingCandidate?.detail,
            hasRunningProcess: !!matchingCandidate,
            pid: matchingCandidate?.pid,
            privacy: tunnel.privacy,
            source: $ZS
          });
          this.f.set(key, tunnel);
        }
      }
    });
    this.detected = /* @__PURE__ */ new Map();
    this.B(this.H.onTunnelOpened(async (tunnel) => {
      const key = $4S(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
      if (!$3S(this.forwarded, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort) && !$3S(this.detected, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort) && !$3S(this.c, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort) && tunnel.localAddress) {
        const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
        const attributes = (await this.getAttributes([{ port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost }]))?.get(tunnel.tunnelRemotePort);
        this.forwarded.set(key, {
          remoteHost: tunnel.tunnelRemoteHost,
          remotePort: tunnel.tunnelRemotePort,
          localAddress: tunnel.localAddress,
          protocol: attributes?.protocol ?? TunnelProtocol.Http,
          localUri: await this.Y(tunnel.localAddress, attributes),
          localPort: tunnel.tunnelLocalPort,
          name: attributes?.label,
          closeable: true,
          runningProcess: matchingCandidate?.detail,
          hasRunningProcess: !!matchingCandidate,
          pid: matchingCandidate?.pid,
          privacy: tunnel.privacy,
          source: $ZS
        });
      }
      await this.db();
      this.W(true);
      this.f.set(key, tunnel);
      this.g.fire(this.forwarded.get(key));
    }));
    this.B(this.H.onTunnelClosed((address) => {
      return this.X(address, TunnelCloseReason.Other);
    }));
    this.W(false);
  }
  S() {
    if (this.Q.extensions.find((extension) => extension.activationEvents?.includes($VS))) {
      this.R.createKey($XS.key, true);
      return true;
    }
    return false;
  }
  W(tunnelOpened) {
    if (this.U) {
      return;
    }
    if (tunnelOpened) {
      this.U = true;
    }
    const hasRemote = this.L.remoteAuthority !== void 0;
    if (hasRemote && !tunnelOpened) {
      return;
    }
    if (this.S()) {
      return;
    }
    const activationDisposable = this.B(this.Q.onDidRegisterExtensions(() => {
      if (this.S()) {
        activationDisposable.dispose();
      }
    }));
  }
  async X(address, reason) {
    const key = $4S(address.host, address.port);
    if (this.forwarded.has(key)) {
      this.forwarded.delete(key);
      await this.db();
      this.h.fire(address);
    }
  }
  Y(localAddress, attributes) {
    if (localAddress.startsWith("http")) {
      return URI.parse(localAddress);
    }
    const protocol = attributes?.protocol ?? "http";
    return URI.parse(`${protocol}://${localAddress}`);
  }
  async Z(prefix) {
    const workspace = this.N.getWorkspace();
    const workspaceHash = workspace.configuration ? $Xi(workspace.configuration.path) : workspace.folders.length > 0 ? $Xi(workspace.folders[0].uri.path) : void 0;
    if (workspaceHash === void 0) {
      this.O.debug("Could not get workspace hash for forwarded ports storage key.");
      return void 0;
    }
    return `${prefix}.${this.L.remoteAuthority}.${workspaceHash}`;
  }
  async $() {
    return this.Z(TUNNELS_TO_RESTORE);
  }
  async ab() {
    return this.Z(TUNNELS_TO_RESTORE_EXPIRATION);
  }
  async bb() {
    const deprecatedValue = this.I.get(
      TUNNELS_TO_RESTORE,
      1
      /* StorageScope.WORKSPACE */
    );
    if (deprecatedValue) {
      this.I.remove(
        TUNNELS_TO_RESTORE,
        1
        /* StorageScope.WORKSPACE */
      );
      await this.db();
      return deprecatedValue;
    }
    const storageKey = await this.$();
    if (!storageKey) {
      return void 0;
    }
    return this.I.get(
      storageKey,
      0
      /* StorageScope.PROFILE */
    );
  }
  async restoreForwarded() {
    this.cb();
    if (this.J.getValue("remote.restoreForwardedPorts")) {
      const tunnelRestoreValue = await this.s;
      if (tunnelRestoreValue && tunnelRestoreValue !== this.y) {
        const tunnels = JSON.parse(tunnelRestoreValue) ?? [];
        this.O.trace(`ForwardedPorts: (TunnelModel) restoring ports ${tunnels.map((tunnel) => tunnel.remotePort).join(", ")}`);
        for (const tunnel of tunnels) {
          const alreadyForwarded = $3S(this.detected, tunnel.remoteHost, tunnel.remotePort);
          if (tunnel.source.source !== TunnelSource.Extension && !alreadyForwarded || tunnel.source.source === TunnelSource.Extension && alreadyForwarded) {
            await this.gb({
              remote: { host: tunnel.remoteHost, port: tunnel.remotePort },
              local: tunnel.localPort,
              name: tunnel.name,
              elevateIfNeeded: true,
              source: tunnel.source
            });
          } else if (tunnel.source.source === TunnelSource.Extension && !alreadyForwarded) {
            this.D.set($4S(tunnel.remoteHost, tunnel.remotePort), tunnel);
          }
        }
      }
    }
    this.z = true;
    this.C.fire();
    if (!this.w) {
      const key = await this.$();
      this.w = this.B(new $2c());
      this.w.add(this.I.onDidChangeValue(0, void 0, this.w)(async (e) => {
        if (e.key === key) {
          this.s = Promise.resolve(this.I.get(
            key,
            0
            /* StorageScope.PROFILE */
          ));
          await this.restoreForwarded();
        }
      }));
    }
  }
  cb() {
    const keys = this.I.keys(
      0,
      0
      /* StorageTarget.USER */
    ).filter((key) => key.startsWith(TUNNELS_TO_RESTORE_EXPIRATION));
    for (const key of keys) {
      const expiration = this.I.getNumber(
        key,
        0
        /* StorageScope.PROFILE */
      );
      if (expiration && expiration < Date.now()) {
        this.s = Promise.resolve(void 0);
        const storageKey = key.replace(TUNNELS_TO_RESTORE_EXPIRATION, TUNNELS_TO_RESTORE);
        this.I.remove(
          key,
          0
          /* StorageScope.PROFILE */
        );
        this.I.remove(
          storageKey,
          0
          /* StorageScope.PROFILE */
        );
      }
    }
  }
  async db() {
    if (this.J.getValue("remote.restoreForwardedPorts")) {
      const forwarded = Array.from(this.forwarded.values());
      const restorableTunnels = forwarded.map((tunnel) => {
        return {
          remoteHost: tunnel.remoteHost,
          remotePort: tunnel.remotePort,
          localPort: tunnel.localPort,
          name: tunnel.name,
          localAddress: tunnel.localAddress,
          localUri: tunnel.localUri,
          protocol: tunnel.protocol,
          source: tunnel.source
        };
      });
      let valueToStore;
      if (forwarded.length > 0) {
        valueToStore = JSON.stringify(restorableTunnels);
      }
      const key = await this.$();
      const expirationKey = await this.ab();
      if (!valueToStore && key && expirationKey) {
        this.I.remove(
          key,
          0
          /* StorageScope.PROFILE */
        );
        this.I.remove(
          expirationKey,
          0
          /* StorageScope.PROFILE */
        );
      } else if (valueToStore !== this.y && key && expirationKey) {
        this.I.store(
          key,
          valueToStore,
          0,
          0
          /* StorageTarget.USER */
        );
        this.I.store(
          expirationKey,
          Date.now() + RESTORE_EXPIRATION_TIME,
          0,
          0
          /* StorageTarget.USER */
        );
      }
      this.y = valueToStore;
    }
  }
  async fb(tunnel, expectedLocal, attributes) {
    if (!tunnel.tunnelLocalPort || !attributes?.requireLocalPort) {
      return;
    }
    if (tunnel.tunnelLocalPort === expectedLocal) {
      return;
    }
    const newCooldown = /* @__PURE__ */ new Date();
    if (this.eb.getTime() + MISMATCH_LOCAL_PORT_COOLDOWN > newCooldown.getTime()) {
      return;
    }
    this.eb = newCooldown;
    const mismatchString = localize(13097, null, expectedLocal, tunnel.tunnelRemotePort, tunnel.tunnelLocalPort);
    return this.P.info(mismatchString);
  }
  async forward(tunnelProperties, attributes) {
    if (!this.z && this.L.remoteAuthority) {
      await Event.toPromise(this.C.event);
    }
    return this.gb(tunnelProperties, attributes);
  }
  async gb(tunnelProperties, attributes) {
    await this.Q.activateByEvent($VS);
    const existingTunnel = $3S(this.forwarded, tunnelProperties.remote.host, tunnelProperties.remote.port);
    attributes = attributes ?? (attributes !== null ? (await this.getAttributes([tunnelProperties.remote]))?.get(tunnelProperties.remote.port) : void 0);
    const localPort = tunnelProperties.local !== void 0 ? tunnelProperties.local : tunnelProperties.remote.port;
    let noTunnelValue;
    if (!existingTunnel) {
      const authority = this.L.remoteAuthority;
      const addressProvider = authority ? {
        getAddress: async () => {
          return (await this.M.resolveAuthority(authority)).authority;
        }
      } : void 0;
      const key = $4S(tunnelProperties.remote.host, tunnelProperties.remote.port);
      this.c.set(key, true);
      tunnelProperties = this.hb(key, tunnelProperties);
      const tunnel = await this.H.openTunnel(addressProvider, tunnelProperties.remote.host, tunnelProperties.remote.port, void 0, localPort, !tunnelProperties.elevateIfNeeded ? attributes?.elevateIfNeeded : tunnelProperties.elevateIfNeeded, tunnelProperties.privacy, attributes?.protocol);
      if (typeof tunnel === "string") {
        noTunnelValue = tunnel;
      } else if (tunnel && tunnel.localAddress) {
        const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), tunnelProperties.remote.host, tunnelProperties.remote.port);
        const protocol = tunnel.protocol ? tunnel.protocol === TunnelProtocol.Https ? TunnelProtocol.Https : TunnelProtocol.Http : attributes?.protocol ?? TunnelProtocol.Http;
        const newForward = {
          remoteHost: tunnel.tunnelRemoteHost,
          remotePort: tunnel.tunnelRemotePort,
          localPort: tunnel.tunnelLocalPort,
          name: attributes?.label ?? tunnelProperties.name,
          closeable: true,
          localAddress: tunnel.localAddress,
          protocol,
          localUri: await this.Y(tunnel.localAddress, attributes),
          runningProcess: matchingCandidate?.detail,
          hasRunningProcess: !!matchingCandidate,
          pid: matchingCandidate?.pid,
          source: tunnelProperties.source ?? $ZS,
          privacy: tunnel.privacy
        };
        this.forwarded.set(key, newForward);
        this.f.set(key, tunnel);
        this.c.delete(key);
        await this.db();
        await this.fb(tunnel, localPort, attributes);
        this.g.fire(newForward);
        return tunnel;
      }
      this.c.delete(key);
    } else {
      return this.ib(existingTunnel, tunnelProperties, attributes);
    }
    return noTunnelValue;
  }
  hb(key, tunnelProperties) {
    const map = this.D.has(key) ? this.D : this.F.has(key) ? this.F : void 0;
    if (map) {
      const updateProps = map.get(key);
      map.delete(key);
      if (updateProps) {
        tunnelProperties.name = updateProps.name ?? tunnelProperties.name;
        tunnelProperties.local = ("local" in updateProps ? updateProps.local : "localPort" in updateProps ? updateProps.localPort : void 0) ?? tunnelProperties.local;
        tunnelProperties.privacy = tunnelProperties.privacy;
      }
    }
    return tunnelProperties;
  }
  async ib(existingTunnel, tunnelProperties, attributes) {
    const newName = attributes?.label ?? tunnelProperties.name;
    let MergedAttributeAction;
    (function(MergedAttributeAction2) {
      MergedAttributeAction2[MergedAttributeAction2["None"] = 0] = "None";
      MergedAttributeAction2[MergedAttributeAction2["Fire"] = 1] = "Fire";
      MergedAttributeAction2[MergedAttributeAction2["Reopen"] = 2] = "Reopen";
    })(MergedAttributeAction || (MergedAttributeAction = {}));
    let mergedAction = MergedAttributeAction.None;
    if (newName !== existingTunnel.name) {
      existingTunnel.name = newName;
      mergedAction = MergedAttributeAction.Fire;
    }
    if ((attributes?.protocol || existingTunnel.protocol !== TunnelProtocol.Http) && attributes?.protocol !== existingTunnel.protocol) {
      tunnelProperties.source = existingTunnel.source;
      mergedAction = MergedAttributeAction.Reopen;
    }
    if (tunnelProperties.privacy && existingTunnel.privacy !== tunnelProperties.privacy) {
      mergedAction = MergedAttributeAction.Reopen;
    }
    switch (mergedAction) {
      case MergedAttributeAction.Fire: {
        this.g.fire();
        break;
      }
      case MergedAttributeAction.Reopen: {
        await this.close(existingTunnel.remoteHost, existingTunnel.remotePort, TunnelCloseReason.User);
        await this.gb(tunnelProperties, attributes);
      }
    }
    return $3S(this.f, tunnelProperties.remote.host, tunnelProperties.remote.port);
  }
  async name(host, port, name) {
    const existingForwarded = $3S(this.forwarded, host, port);
    const key = $4S(host, port);
    if (existingForwarded) {
      existingForwarded.name = name;
      await this.db();
      this.j.fire({ host, port });
      return;
    } else if (this.detected.has(key)) {
      this.detected.get(key).name = name;
      this.j.fire({ host, port });
    }
  }
  async close(host, port, reason) {
    const key = $4S(host, port);
    const oldTunnel = this.forwarded.get(key);
    if (reason === TunnelCloseReason.AutoForwardEnd && oldTunnel && oldTunnel.source.source === TunnelSource.Auto) {
      this.F.set(key, {
        local: oldTunnel.localPort,
        name: oldTunnel.name,
        privacy: oldTunnel.privacy
      });
    }
    await this.H.closeTunnel(host, port);
    return this.X({ host, port }, reason);
  }
  address(host, port) {
    const key = $4S(host, port);
    return (this.forwarded.get(key) || this.detected.get(key))?.localAddress;
  }
  get environmentTunnelsSet() {
    return this.u;
  }
  addEnvironmentTunnels(tunnels) {
    if (tunnels) {
      for (const tunnel of tunnels) {
        const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), tunnel.remoteAddress.host, tunnel.remoteAddress.port);
        const localAddress = typeof tunnel.localAddress === "string" ? tunnel.localAddress : $4S(tunnel.localAddress.host, tunnel.localAddress.port);
        this.detected.set($4S(tunnel.remoteAddress.host, tunnel.remoteAddress.port), {
          remoteHost: tunnel.remoteAddress.host,
          remotePort: tunnel.remoteAddress.port,
          localAddress,
          protocol: TunnelProtocol.Http,
          localUri: this.Y(localAddress),
          closeable: false,
          runningProcess: matchingCandidate?.detail,
          hasRunningProcess: !!matchingCandidate,
          pid: matchingCandidate?.pid,
          privacy: TunnelPrivacyId.ConstantPrivate,
          source: {
            source: TunnelSource.Extension,
            description: localize(13098, null)
          }
        });
        this.H.setEnvironmentTunnel(tunnel.remoteAddress.host, tunnel.remoteAddress.port, localAddress, TunnelPrivacyId.ConstantPrivate, TunnelProtocol.Http);
      }
    }
    this.u = true;
    this.t.fire();
    this.g.fire();
  }
  setCandidateFilter(filter) {
    this.r = filter;
  }
  async setCandidates(candidates) {
    let processedCandidates = candidates;
    if (this.r) {
      processedCandidates = await this.r(candidates);
    }
    const removedCandidates = this.jb(processedCandidates);
    this.O.trace(`ForwardedPorts: (TunnelModel) removed candidates ${Array.from(removedCandidates.values()).map((candidate) => candidate.port).join(", ")}`);
    this.n.fire(removedCandidates);
  }
  // Returns removed candidates
  jb(candidates) {
    const removedCandidates = this.m ?? /* @__PURE__ */ new Map();
    const candidatesMap = /* @__PURE__ */ new Map();
    this.m = candidatesMap;
    candidates.forEach((value) => {
      const addressKey = $4S(value.host, value.port);
      candidatesMap.set(addressKey, {
        host: value.host,
        port: value.port,
        detail: value.detail,
        pid: value.pid
      });
      if (removedCandidates.has(addressKey)) {
        removedCandidates.delete(addressKey);
      }
      const forwardedValue = $3S(this.forwarded, value.host, value.port);
      if (forwardedValue) {
        forwardedValue.runningProcess = value.detail;
        forwardedValue.hasRunningProcess = true;
        forwardedValue.pid = value.pid;
      }
    });
    removedCandidates.forEach((_value, key) => {
      const parsedAddress = $YS(key);
      if (!parsedAddress) {
        return;
      }
      const forwardedValue = $3S(this.forwarded, parsedAddress.host, parsedAddress.port);
      if (forwardedValue) {
        forwardedValue.runningProcess = void 0;
        forwardedValue.hasRunningProcess = false;
        forwardedValue.pid = void 0;
      }
      const detectedValue = $3S(this.detected, parsedAddress.host, parsedAddress.port);
      if (detectedValue) {
        detectedValue.runningProcess = void 0;
        detectedValue.hasRunningProcess = false;
        detectedValue.pid = void 0;
      }
    });
    return removedCandidates;
  }
  get candidates() {
    return this.m ? Array.from(this.m.values()) : [];
  }
  get candidatesOrUndefined() {
    return this.m ? this.candidates : void 0;
  }
  async kb() {
    const tunnels = Array.from(this.forwarded.values());
    const allAttributes = await this.getAttributes(tunnels.map((tunnel) => {
      return { port: tunnel.remotePort, host: tunnel.remoteHost };
    }), false);
    if (!allAttributes) {
      return;
    }
    for (const forwarded of tunnels) {
      const attributes = allAttributes.get(forwarded.remotePort);
      if ((attributes?.protocol || forwarded.protocol !== TunnelProtocol.Http) && attributes?.protocol !== forwarded.protocol) {
        await this.gb({
          remote: { host: forwarded.remoteHost, port: forwarded.remotePort },
          local: forwarded.localPort,
          name: forwarded.name,
          source: forwarded.source
        }, attributes);
      }
      if (!attributes) {
        continue;
      }
      if (attributes.label && attributes.label !== forwarded.name) {
        await this.name(forwarded.remoteHost, forwarded.remotePort, attributes.label);
      }
    }
  }
  async getAttributes(forwardedPorts, checkProviders = true) {
    const matchingCandidates = /* @__PURE__ */ new Map();
    const pidToPortsMapping = /* @__PURE__ */ new Map();
    forwardedPorts.forEach((forwardedPort) => {
      const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), $yC[0], forwardedPort.port) ?? forwardedPort;
      if (matchingCandidate) {
        matchingCandidates.set(forwardedPort.port, matchingCandidate);
        const pid = $5S(matchingCandidate) ? matchingCandidate.pid : void 0;
        if (!pidToPortsMapping.has(pid)) {
          pidToPortsMapping.set(pid, []);
        }
        pidToPortsMapping.get(pid)?.push(forwardedPort.port);
      }
    });
    const configAttributes = /* @__PURE__ */ new Map();
    forwardedPorts.forEach((forwardedPort) => {
      const attributes = this.configPortsAttributes.getAttributes(forwardedPort.port, forwardedPort.host, matchingCandidates.get(forwardedPort.port)?.detail);
      if (attributes) {
        configAttributes.set(forwardedPort.port, attributes);
      }
    });
    if (this.G.length === 0 || !checkProviders) {
      return configAttributes.size > 0 ? configAttributes : void 0;
    }
    const allProviderResults = await Promise.all(this.G.flatMap((provider) => {
      return Array.from(pidToPortsMapping.entries()).map((entry) => {
        const portGroup = entry[1];
        const matchingCandidate = matchingCandidates.get(portGroup[0]);
        return provider.providePortAttributes(portGroup, matchingCandidate?.pid, matchingCandidate?.detail, CancellationToken.None);
      });
    }));
    const providedAttributes = /* @__PURE__ */ new Map();
    allProviderResults.forEach((attributes) => attributes.forEach((attribute) => {
      if (attribute) {
        providedAttributes.set(attribute.port, attribute);
      }
    }));
    if (!configAttributes && !providedAttributes) {
      return void 0;
    }
    const mergedAttributes = /* @__PURE__ */ new Map();
    forwardedPorts.forEach((forwardedPorts2) => {
      const config = configAttributes.get(forwardedPorts2.port);
      const provider = providedAttributes.get(forwardedPorts2.port);
      mergedAttributes.set(forwardedPorts2.port, {
        elevateIfNeeded: config?.elevateIfNeeded,
        label: config?.label,
        onAutoForward: config?.onAutoForward ?? $6S.providedActionToAction(provider?.autoForwardAction),
        requireLocalPort: config?.requireLocalPort,
        protocol: config?.protocol
      });
    });
    return mergedAttributes;
  }
  addAttributesProvider(provider) {
    this.G.push(provider);
  }
};
__decorate([
  $$t(1e3)
], $7S.prototype, "db", null);
$7S = __decorate([
  __param(0, $tC),
  __param(1, $jv),
  __param(2, $kl),
  __param(3, $US),
  __param(4, $bC),
  __param(5, $Zk),
  __param(6, $wn),
  __param(7, $Yv),
  __param(8, $wN),
  __param(9, $on)
], $7S);

// out-build/vs/workbench/api/node/extHostTunnelService.js
function $Fzc(stdout) {
  const lines = stdout.trim().split("\n");
  const mapped = [];
  lines.forEach((line) => {
    const match = /\/proc\/(\d+)\/fd\/\d+ -> socket:\[(\d+)\]/.exec(line);
    if (match && match.length >= 3) {
      mapped.push({
        pid: parseInt(match[1], 10),
        socket: parseInt(match[2], 10)
      });
    }
  });
  const socketMap = mapped.reduce((m, socket) => {
    m[socket.socket] = socket;
    return m;
  }, {});
  return socketMap;
}
function $Gzc(...stdouts) {
  const table = [].concat(...stdouts.map($Izc));
  return [
    ...new Map(table.filter((row) => row.st === "0A").map((row) => {
      const address = row.local_address.split(":");
      return {
        socket: parseInt(row.inode, 10),
        ip: $Hzc(address[0]),
        port: parseInt(address[1], 16)
      };
    }).map((port) => [port.ip + ":" + port.port, port])).values()
  ];
}
function $Hzc(hex) {
  let result = "";
  if (hex.length === 8) {
    for (let i = hex.length - 2; i >= 0; i -= 2) {
      result += parseInt(hex.substr(i, 2), 16);
      if (i !== 0) {
        result += ".";
      }
    }
  } else {
    for (let i = 0; i < hex.length; i += 8) {
      const word = hex.substring(i, i + 8);
      let subWord = "";
      for (let j = 8; j >= 2; j -= 2) {
        subWord += word.substring(j - 2, j);
        if (j === 6 || j === 2) {
          subWord = parseInt(subWord, 16).toString(16);
          result += `${subWord}`;
          subWord = "";
          if (i + j !== hex.length - 6) {
            result += ":";
          }
        }
      }
    }
  }
  return result;
}
function $Izc(stdout) {
  const lines = stdout.trim().split("\n");
  const names = lines.shift().trim().split(/\s+/).filter((name) => name !== "rx_queue" && name !== "tm->when");
  const table = lines.map((line) => line.trim().split(/\s+/).reduce((obj, value, i) => {
    obj[names[i] || i] = value;
    return obj;
  }, {}));
  return table;
}
function knownExcludeCmdline(command) {
  if (command.length > 500) {
    return false;
  }
  return !!command.match(/.*\.vscode-server-[a-zA-Z]+\/bin.*/) || command.indexOf("out/server-main.js") !== -1 || command.indexOf("_productName=VSCode") !== -1;
}
function $Jzc(stdout) {
  const lines = stdout.trim().split("\n");
  const mapped = [];
  lines.forEach((line) => {
    const match = /^\d+\s+\D+\s+root\s+(\d+)\s+(\d+).+\d+\:\d+\:\d+\s+(.+)$/.exec(line);
    if (match && match.length >= 4) {
      mapped.push({
        pid: parseInt(match[1], 10),
        ppid: parseInt(match[2]),
        cmd: match[3]
      });
    }
  });
  return mapped;
}
async function $Kzc(connections, socketMap, processes) {
  const processMap = processes.reduce((m, process2) => {
    m[process2.pid] = process2;
    return m;
  }, {});
  const ports = [];
  connections.forEach(({ socket, ip, port }) => {
    const pid = socketMap[socket] ? socketMap[socket].pid : void 0;
    const command = pid ? processMap[pid]?.cmd : void 0;
    if (pid && command && !knownExcludeCmdline(command)) {
      ports.push({ host: ip, port, detail: command, pid });
    }
  });
  return ports;
}
function $Lzc(connections, rootProcessesStdout, previousPorts) {
  const ports = /* @__PURE__ */ new Map();
  const rootProcesses = $Jzc(rootProcessesStdout);
  for (const connection of connections) {
    const previousPort = previousPorts.get(connection.port);
    if (previousPort) {
      ports.set(connection.port, previousPort);
      continue;
    }
    const rootProcessMatch = rootProcesses.find((value) => value.cmd.includes(`${connection.port}`));
    if (rootProcessMatch) {
      let bestMatch = rootProcessMatch;
      let mostChild;
      do {
        mostChild = rootProcesses.find((value) => value.ppid === bestMatch.pid);
        if (mostChild) {
          bestMatch = mostChild;
        }
      } while (mostChild);
      ports.set(connection.port, { host: connection.ip, port: connection.port, pid: bestMatch.pid, detail: bestMatch.cmd, ppid: bestMatch.ppid });
    } else {
      ports.set(connection.port, { host: connection.ip, port: connection.port, ppid: Number.MAX_VALUE });
    }
  }
  return ports;
}
var $Mzc = class $Mzc2 extends $7Sb {
  constructor(extHostRpc, D, logService, F) {
    super(extHostRpc, D, logService);
    this.D = D;
    this.F = F;
    this.y = void 0;
    this.z = /* @__PURE__ */ new Map();
    this.C = false;
    if ($n && D.remote.isRemote && D.remote.authority) {
      this.a.$setRemoteTunnelService(process.pid);
      this.H();
    }
  }
  async $registerCandidateFinder(enable) {
    if (enable && this.C) {
      return;
    }
    this.C = enable;
    let oldPorts = void 0;
    if (this.y) {
      oldPorts = this.y;
      await this.a.$onFoundNewCandidates(this.y);
    }
    const movingAverage = new $7i();
    let scanCount = 0;
    while (this.C) {
      const startTime = (/* @__PURE__ */ new Date()).getTime();
      const newPorts = (await this.I()).filter((candidate) => $zC(candidate.host) || $BC(candidate.host));
      this.s.trace(`ForwardedPorts: (ExtHostTunnelService) found candidate ports ${newPorts.map((port) => port.port).join(", ")}`);
      const timeTaken = (/* @__PURE__ */ new Date()).getTime() - startTime;
      this.s.trace(`ForwardedPorts: (ExtHostTunnelService) candidate port scan took ${timeTaken} ms.`);
      if (scanCount++ > 3) {
        movingAverage.update(timeTaken);
      }
      if (!oldPorts || JSON.stringify(oldPorts) !== JSON.stringify(newPorts)) {
        oldPorts = newPorts;
        await this.a.$onFoundNewCandidates(oldPorts);
      }
      const delay = this.G(movingAverage.value);
      this.s.trace(`ForwardedPorts: (ExtHostTunnelService) next candidate port scan in ${delay} ms.`);
      await new Promise((resolve) => setTimeout(() => resolve(), delay));
    }
  }
  G(movingAverage) {
    return Math.max(movingAverage * 20, 2e3);
  }
  async H() {
    this.y = await this.I();
    this.s.trace(`ForwardedPorts: (ExtHostTunnelService) Initial candidates found: ${this.y.map((c) => c.port).join(", ")}`);
  }
  async I() {
    let tcp = "";
    let tcp6 = "";
    try {
      tcp = await fs5.promises.readFile("/proc/net/tcp", "utf8");
      tcp6 = await fs5.promises.readFile("/proc/net/tcp6", "utf8");
    } catch (e) {
    }
    const connections = $Gzc(tcp, tcp6);
    const procSockets = await new Promise((resolve) => {
      exec2("ls -l /proc/[0-9]*/fd/[0-9]* | grep socket:", (error, stdout, stderr) => {
        resolve(stdout);
      });
    });
    const socketMap = $Fzc(procSockets);
    const procChildren = await Promises2.readdir("/proc");
    const processes = [];
    for (const childName of procChildren) {
      try {
        const pid = Number(childName);
        const childUri = $vh(URI.file("/proc"), childName);
        const childStat = await fs5.promises.stat(childUri.fsPath);
        if (childStat.isDirectory() && !isNaN(pid)) {
          const cwd2 = await fs5.promises.readlink($vh(childUri, "cwd").fsPath);
          const cmd = await fs5.promises.readFile($vh(childUri, "cmdline").fsPath, "utf8");
          processes.push({ pid, cwd: cwd2, cmd });
        }
      } catch (e) {
      }
    }
    const unFoundConnections = [];
    const filteredConnections = connections.filter((connection) => {
      const foundConnection = socketMap[connection.socket];
      if (!foundConnection) {
        unFoundConnections.push(connection);
      }
      return foundConnection;
    });
    const foundPorts = $Kzc(filteredConnections, socketMap, processes);
    let heuristicPorts;
    this.s.trace(`ForwardedPorts: (ExtHostTunnelService) number of possible root ports ${unFoundConnections.length}`);
    if (unFoundConnections.length > 0) {
      const rootProcesses = await new Promise((resolve) => {
        exec2("ps -F -A -l | grep root", (error, stdout, stderr) => {
          resolve(stdout);
        });
      });
      this.z = $Lzc(unFoundConnections, rootProcesses, this.z);
      heuristicPorts = Array.from(this.z.values());
      this.s.trace(`ForwardedPorts: (ExtHostTunnelService) heuristic ports ${heuristicPorts.map((heuristicPort) => heuristicPort.port).join(", ")}`);
    }
    return foundPorts.then((foundCandidates) => {
      if (heuristicPorts) {
        return foundCandidates.concat(heuristicPorts);
      } else {
        return foundCandidates;
      }
    });
  }
  w(authority) {
    return async (tunnelOptions) => {
      const t = new $FC({
        commit: this.D.commit,
        quality: this.D.quality,
        logService: this.s,
        ipcLogger: null,
        // services and address providers have stubs since we don't need
        // the connection identification that the renderer process uses
        remoteSocketFactoryService: {
          _serviceBrand: void 0,
          async connect(_connectTo, path, query, debugLabel) {
            const result = await authority.makeConnection();
            return ExtHostManagedSocket.connect(result, path, query, debugLabel);
          },
          register() {
            throw new Error("not implemented");
          }
        },
        addressProvider: {
          getAddress() {
            return Promise.resolve({
              connectTo: new $cC(0),
              connectionToken: authority.connectionToken
            });
          }
        },
        signService: this.F
      }, "localhost", tunnelOptions.remoteAddress.host || "localhost", tunnelOptions.remoteAddress.port, tunnelOptions.localAddressPort);
      await t.waitForReady();
      const disposeEmitter = new $ze();
      return {
        localAddress: $YS(t.localAddress) ?? t.localAddress,
        remoteAddress: { port: t.tunnelRemotePort, host: t.tunnelRemoteHost },
        onDidDispose: disposeEmitter.event,
        dispose: () => {
          t.dispose();
          disposeEmitter.fire();
          disposeEmitter.dispose();
        }
      };
    };
  }
};
$Mzc = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $wn),
  __param(3, $lz)
], $Mzc);
var ExtHostManagedSocket = class _ExtHostManagedSocket extends $zQb {
  static connect(passing, path, query, debugLabel) {
    const d = new $2c();
    const half = {
      onClose: d.add(new $ze()),
      onData: d.add(new $ze()),
      onEnd: d.add(new $ze())
    };
    d.add(passing.onDidReceiveMessage((d2) => half.onData.fire($Ci.wrap(d2))));
    d.add(passing.onDidEnd(() => half.onEnd.fire()));
    d.add(passing.onDidClose((error) => half.onClose.fire({
      type: 0,
      error,
      hadError: !!error
    })));
    const socket = new _ExtHostManagedSocket(passing, debugLabel, half);
    socket.B(d);
    return $yQb(socket, path, query, debugLabel, half);
  }
  constructor(n, debugLabel, half) {
    super(debugLabel, half);
    this.n = n;
  }
  write(buffer) {
    this.n.send(buffer.buffer);
  }
  h() {
    this.n.end();
  }
  async drain() {
    await this.n.drain?.();
  }
};

// out-build/vs/workbench/api/node/extHostStoragePaths.js
import * as fs6 from "fs";
var $Nzc = class extends $exc {
  constructor() {
    super(...arguments);
    this.i = null;
  }
  async g(storageName) {
    const workspaceStorageURI = await super.g(storageName);
    if (workspaceStorageURI.scheme !== Schemas.file) {
      return workspaceStorageURI;
    }
    if (this.b.skipWorkspaceStorageLock) {
      this.d.info(`Skipping acquiring lock for ${workspaceStorageURI.fsPath}.`);
      return workspaceStorageURI;
    }
    const workspaceStorageBase = workspaceStorageURI.fsPath;
    let attempt = 0;
    do {
      let workspaceStoragePath;
      if (attempt === 0) {
        workspaceStoragePath = workspaceStorageBase;
      } else {
        workspaceStoragePath = /[/\\]$/.test(workspaceStorageBase) ? `${workspaceStorageBase.substr(0, workspaceStorageBase.length - 1)}-${attempt}` : `${workspaceStorageBase}-${attempt}`;
      }
      await mkdir(workspaceStoragePath);
      const lockfile = $nc(workspaceStoragePath, "vscode.lock");
      const lock = await tryAcquireLock(this.d, lockfile, false);
      if (lock) {
        this.i = lock;
        process.on("exit", () => {
          lock.dispose();
        });
        return URI.file(workspaceStoragePath);
      }
      attempt++;
    } while (attempt < 10);
    return workspaceStorageURI;
  }
  onWillDeactivateAll() {
    this.i?.setWillRelease(6e3);
  }
};
async function mkdir(dir) {
  try {
    await fs6.promises.stat(dir);
    return;
  } catch {
  }
  try {
    await fs6.promises.mkdir(dir, { recursive: true });
  } catch {
  }
}
var MTIME_UPDATE_TIME = 1e3;
var STALE_LOCK_TIME = 10 * 60 * 1e3;
var Lock = class extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(new $7h());
    this.a.cancelAndSet(async () => {
      const contents = await readLockfileContents(b, c);
      if (!contents || contents.pid !== process.pid) {
        b.info(`Lock '${c}': The lock was lost unexpectedly.`);
        this.a.cancel();
      }
      try {
        await fs6.promises.utimes(c, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
      } catch (err) {
        b.error(err);
        b.info(`Lock '${c}': Could not update mtime.`);
      }
    }, MTIME_UPDATE_TIME);
  }
  dispose() {
    super.dispose();
    try {
      fs6.unlinkSync(this.c);
    } catch (err) {
    }
  }
  async setWillRelease(timeUntilReleaseMs) {
    this.b.info(`Lock '${this.c}': Marking the lockfile as scheduled to be released in ${timeUntilReleaseMs} ms.`);
    try {
      const contents = {
        pid: process.pid,
        willReleaseAt: Date.now() + timeUntilReleaseMs
      };
      await Promises2.writeFile(this.c, JSON.stringify(contents), { flag: "w" });
    } catch (err) {
      this.b.error(err);
    }
  }
};
async function tryAcquireLock(logService, filename, isSecondAttempt) {
  try {
    const contents2 = {
      pid: process.pid,
      willReleaseAt: 0
    };
    await Promises2.writeFile(filename, JSON.stringify(contents2), { flag: "wx" });
  } catch (err) {
    logService.error(err);
  }
  const contents = await readLockfileContents(logService, filename);
  if (!contents || contents.pid !== process.pid) {
    if (isSecondAttempt) {
      logService.info(`Lock '${filename}': Could not acquire lock, giving up.`);
      return null;
    }
    logService.info(`Lock '${filename}': Could not acquire lock, checking if the file is stale.`);
    return checkStaleAndTryAcquireLock(logService, filename);
  }
  logService.info(`Lock '${filename}': Lock acquired.`);
  return new Lock(logService, filename);
}
async function readLockfileContents(logService, filename) {
  let contents;
  try {
    contents = await fs6.promises.readFile(filename);
  } catch (err) {
    logService.error(err);
    return null;
  }
  try {
    return JSON.parse(String(contents));
  } catch (err) {
    logService.error(err);
    return null;
  }
}
async function readmtime(logService, filename) {
  let stats;
  try {
    stats = await fs6.promises.stat(filename);
  } catch (err) {
    logService.error(err);
    return 0;
  }
  return stats.mtime.getTime();
}
function processExists(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch (e) {
    return false;
  }
}
async function checkStaleAndTryAcquireLock(logService, filename) {
  const contents = await readLockfileContents(logService, filename);
  if (!contents) {
    logService.info(`Lock '${filename}': Could not read pid of lock holder.`);
    return tryDeleteAndAcquireLock(logService, filename);
  }
  if (contents.willReleaseAt) {
    let timeUntilRelease = contents.willReleaseAt - Date.now();
    if (timeUntilRelease < 5e3) {
      if (timeUntilRelease > 0) {
        logService.info(`Lock '${filename}': The lockfile is scheduled to be released in ${timeUntilRelease} ms.`);
      } else {
        logService.info(`Lock '${filename}': The lockfile is scheduled to have been released.`);
      }
      while (timeUntilRelease > 0) {
        await $Wh(Math.min(100, timeUntilRelease));
        const mtime = await readmtime(logService, filename);
        if (mtime === 0) {
          return tryDeleteAndAcquireLock(logService, filename);
        }
        timeUntilRelease = contents.willReleaseAt - Date.now();
      }
      return tryDeleteAndAcquireLock(logService, filename);
    }
  }
  if (!processExists(contents.pid)) {
    logService.info(`Lock '${filename}': The pid ${contents.pid} appears to be gone.`);
    return tryDeleteAndAcquireLock(logService, filename);
  }
  const mtime1 = await readmtime(logService, filename);
  const elapsed1 = Date.now() - mtime1;
  if (elapsed1 <= STALE_LOCK_TIME) {
    logService.info(`Lock '${filename}': The lock does not look stale, elapsed: ${elapsed1} ms, giving up.`);
    return null;
  }
  logService.info(`Lock '${filename}': The lock looks stale, waiting for 2s.`);
  await $Wh(2e3);
  const mtime2 = await readmtime(logService, filename);
  const elapsed2 = Date.now() - mtime2;
  if (elapsed2 <= STALE_LOCK_TIME) {
    logService.info(`Lock '${filename}': The lock does not look stale, elapsed: ${elapsed2} ms, giving up.`);
    return null;
  }
  logService.info(`Lock '${filename}': The lock looks stale even after waiting for 2s.`);
  return tryDeleteAndAcquireLock(logService, filename);
}
async function tryDeleteAndAcquireLock(logService, filename) {
  logService.info(`Lock '${filename}': Deleting a stale lock.`);
  try {
    await fs6.promises.unlink(filename);
  } catch (err) {
  }
  return tryAcquireLock(logService, filename, true);
}

// out-build/vs/platform/log/node/spdlogLog.js
var SpdLogLevel;
(function(SpdLogLevel2) {
  SpdLogLevel2[SpdLogLevel2["Trace"] = 0] = "Trace";
  SpdLogLevel2[SpdLogLevel2["Debug"] = 1] = "Debug";
  SpdLogLevel2[SpdLogLevel2["Info"] = 2] = "Info";
  SpdLogLevel2[SpdLogLevel2["Warning"] = 3] = "Warning";
  SpdLogLevel2[SpdLogLevel2["Error"] = 4] = "Error";
  SpdLogLevel2[SpdLogLevel2["Critical"] = 5] = "Critical";
  SpdLogLevel2[SpdLogLevel2["Off"] = 6] = "Off";
})(SpdLogLevel || (SpdLogLevel = {}));
async function createSpdLogLogger(name, logfilePath, filesize, filecount, donotUseFormatters) {
  try {
    const _spdlog = await import("@vscode/spdlog");
    _spdlog.setFlushOn(SpdLogLevel.Trace);
    const logger = await _spdlog.createAsyncRotatingLogger(name, logfilePath, filesize, filecount);
    if (donotUseFormatters) {
      logger.clearFormatters();
    } else {
      logger.setPattern("%Y-%m-%d %H:%M:%S.%e [%l] %v");
    }
    return logger;
  } catch (e) {
    console.error(e);
  }
  return null;
}
function log3(logger, level, message) {
  switch (level) {
    case LogLevel.Trace:
      logger.trace(message);
      break;
    case LogLevel.Debug:
      logger.debug(message);
      break;
    case LogLevel.Info:
      logger.info(message);
      break;
    case LogLevel.Warning:
      logger.warn(message);
      break;
    case LogLevel.Error:
      logger.error(message);
      break;
    case LogLevel.Off:
      break;
    default:
      throw new Error(`Invalid log level ${level}`);
  }
}
function setLogLevel(logger, level) {
  switch (level) {
    case LogLevel.Trace:
      logger.setLevel(SpdLogLevel.Trace);
      break;
    case LogLevel.Debug:
      logger.setLevel(SpdLogLevel.Debug);
      break;
    case LogLevel.Info:
      logger.setLevel(SpdLogLevel.Info);
      break;
    case LogLevel.Warning:
      logger.setLevel(SpdLogLevel.Warning);
      break;
    case LogLevel.Error:
      logger.setLevel(SpdLogLevel.Error);
      break;
    case LogLevel.Off:
      logger.setLevel(SpdLogLevel.Off);
      break;
    default:
      throw new Error(`Invalid log level ${level}`);
  }
}
var $fx = class extends $Cn {
  constructor(name, filepath, rotating, donotUseFormatters, level) {
    super();
    this.n = [];
    this.setLevel(level);
    this.r = this.t(name, filepath, rotating, donotUseFormatters);
    this.B(this.onDidChangeLogLevel((level2) => {
      if (this.s) {
        setLogLevel(this.s, level2);
      }
    }));
  }
  async t(name, filepath, rotating, donotUseFormatters) {
    const filecount = rotating ? 6 : 1;
    const filesize = 30 / filecount * $Sm.MB;
    const logger = await createSpdLogLogger(name, filepath, filesize, filecount, donotUseFormatters);
    if (logger) {
      this.s = logger;
      setLogLevel(this.s, this.getLevel());
      for (const { level, message } of this.n) {
        log3(this.s, level, message);
      }
      this.n = [];
    }
  }
  m(level, message) {
    if (this.s) {
      log3(this.s, level, message);
    } else if (this.getLevel() <= level) {
      this.n.push({ level, message });
    }
  }
  flush() {
    if (this.s) {
      this.w();
    } else {
      this.r.then(() => this.w());
    }
  }
  dispose() {
    if (this.s) {
      this.y();
    } else {
      this.r.then(() => this.y());
    }
    super.dispose();
  }
  w() {
    if (this.s) {
      this.s.flush();
    }
  }
  y() {
    if (this.s) {
      this.s.drop();
      this.s = void 0;
    }
  }
};

// out-build/vs/workbench/api/node/extHostLoggerService.js
var $Ozc = class extends $2yc {
  s(resource, logLevel, options2) {
    if (resource.scheme === Schemas.file) {
      return new $fx(options2?.name || $ps(), resource.fsPath, !options2?.donotRotate, !!options2?.donotUseFormatters, logLevel);
    }
    return super.s(resource, logLevel, options2);
  }
  registerLogger(resource) {
    super.registerLogger(resource);
    this.r.$registerLogger(resource);
  }
  deregisterLogger(resource) {
    super.deregisterLogger(resource);
    this.r.$deregisterLogger(resource);
  }
};

// out-build/vs/workbench/api/node/extHostVariableResolverService.js
import { homedir as homedir3 } from "os";
var $Pzc = class extends $Uxc {
  m() {
    return homedir3();
  }
};

// out-build/vs/platform/log/common/logService.js
var $WC = class extends $3c {
  constructor(primaryLogger, otherLoggers = []) {
    super();
    this.a = new $Gn([primaryLogger, ...otherLoggers]);
    this.B(primaryLogger.onDidChangeLogLevel((level) => this.setLevel(level)));
  }
  get onDidChangeLogLevel() {
    return this.a.onDidChangeLogLevel;
  }
  setLevel(level) {
    this.a.setLevel(level);
  }
  getLevel() {
    return this.a.getLevel();
  }
  trace(message, ...args2) {
    this.a.trace(message, ...args2);
  }
  debug(message, ...args2) {
    this.a.debug(message, ...args2);
  }
  info(message, ...args2) {
    this.a.info(message, ...args2);
  }
  warn(message, ...args2) {
    this.a.warn(message, ...args2);
  }
  error(message, ...args2) {
    this.a.error(message, ...args2);
  }
  flush() {
    this.a.flush();
  }
};

// out-build/vs/workbench/api/common/extHostLogService.js
var $4yc = class $4yc2 extends $WC {
  constructor(isWorker, loggerService, initData) {
    const id2 = initData.remote.isRemote ? "remoteexthost" : isWorker ? "workerexthost" : "exthost";
    const name = initData.remote.isRemote ? localize(2760, null) : isWorker ? localize(2761, null) : localize(2762, null);
    super(loggerService.createLogger(id2, { name }));
  }
};
$4yc = __decorate([
  __param(1, $xn),
  __param(2, $wW)
], $4yc);

// out-build/vs/workbench/api/node/extHost.node.services.js
$SC(
  $Lxc,
  $Ezc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $xn,
  $Ozc,
  1
  /* InstantiationType.Delayed */
);
$SC($wn, new $Nk($4yc, [false], true));
$SC(
  $lz,
  $PC,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $dxc,
  $Nzc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Vxc,
  $ezc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $kyc,
  $zzc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Nyc,
  $9yc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $yxc,
  $8yc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $6Sb,
  $Mzc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $Txc,
  $Pzc,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/api/node/extensionHostProcess.js
import { createRequire as createRequire3 } from "node:module";
var require4 = createRequire3(import.meta.url);
(function removeInspectPort() {
  for (let i = 0; i < process.execArgv.length; i++) {
    if (process.execArgv[i] === "--inspect-port=0") {
      process.execArgv.splice(i, 1);
      i--;
    }
  }
})();
var args = (0, import_minimist2.default)(process.argv.slice(2), {
  boolean: [
    "transformURIs",
    "skipWorkspaceStorageLock"
  ],
  string: [
    "useHostProxy"
    // 'true' | 'false' | undefined
  ]
});
(function() {
  const Module = require4("module");
  const originalLoad = Module._load;
  Module._load = function(request) {
    if (request === "natives") {
      throw new Error('Either the extension or an NPM dependency is using the [unsupported "natives" node module](https://go.microsoft.com/fwlink/?linkid=871887).');
    }
    return originalLoad.apply(this, arguments);
  };
})();
var nativeExit = process.exit.bind(process);
var nativeOn = process.on.bind(process);
function patchProcess(allowExit) {
  process.exit = function(code) {
    if (allowExit) {
      nativeExit(code);
    } else {
      const err = new Error("An extension called process.exit() and this was prevented.");
      console.warn(err.stack);
    }
  };
  process.crash = function() {
    const err = new Error("An extension called process.crash() and this was prevented.");
    console.warn(err.stack);
  };
  process.env["ELECTRON_RUN_AS_NODE"] = "1";
  process.on = function(event, listener) {
    if (event === "uncaughtException") {
      listener = function() {
        try {
          return listener.call(void 0, arguments);
        } catch {
        }
      };
    }
    nativeOn(event, listener);
  };
}
var onTerminate = function(reason) {
  nativeExit();
};
function _createExtHostProtocol() {
  const extHostConnection = $VW(process.env);
  if (extHostConnection.type === 3) {
    return new Promise((resolve, reject) => {
      const withPorts = (ports) => {
        const port = ports[0];
        const onMessage = new $su();
        port.on("message", (e) => onMessage.fire($Ci.wrap(e.data)));
        port.on("close", () => {
          onTerminate("renderer closed the MessagePort");
        });
        port.start();
        resolve({
          onMessage: onMessage.event,
          send: (message) => port.postMessage(message.buffer)
        });
      };
      process.parentPort.on("message", (e) => withPorts(e.ports));
    });
  } else if (extHostConnection.type === 2) {
    return new Promise((resolve, reject) => {
      let protocol = null;
      const timer2 = setTimeout(() => {
        onTerminate("VSCODE_EXTHOST_IPC_SOCKET timeout");
      }, 6e4);
      const reconnectionGraceTime = 108e5;
      const reconnectionShortGraceTime = 3e5;
      const disconnectRunner1 = new $9h(() => onTerminate("renderer disconnected for too long (1)"), reconnectionGraceTime);
      const disconnectRunner2 = new $9h(() => onTerminate("renderer disconnected for too long (2)"), reconnectionShortGraceTime);
      process.on("message", (msg, handle) => {
        if (msg && msg.type === "VSCODE_EXTHOST_IPC_SOCKET") {
          handle.setNoDelay(true);
          const initialDataChunk = $Ci.wrap(Buffer.from(msg.initialDataChunk, "base64"));
          let socket;
          if (msg.skipWebSocketFrames) {
            socket = new $uu(handle, "extHost-socket");
          } else {
            const inflateBytes = $Ci.wrap(Buffer.from(msg.inflateBytes, "base64"));
            socket = new $vu(new $uu(handle, "extHost-socket"), msg.permessageDeflate, inflateBytes, false);
          }
          if (protocol) {
            disconnectRunner1.cancel();
            disconnectRunner2.cancel();
            protocol.beginAcceptReconnection(socket, initialDataChunk);
            protocol.endAcceptReconnection();
            protocol.sendResume();
          } else {
            clearTimeout(timer2);
            protocol = new $tu({ socket, initialChunk: initialDataChunk });
            protocol.sendResume();
            protocol.onDidDispose(() => onTerminate("renderer disconnected"));
            resolve(protocol);
            protocol.onSocketClose(() => {
              disconnectRunner1.schedule();
            });
          }
        }
        if (msg && msg.type === "VSCODE_EXTHOST_IPC_REDUCE_GRACE_TIME") {
          if (disconnectRunner2.isScheduled()) {
            return;
          }
          if (disconnectRunner1.isScheduled()) {
            disconnectRunner2.schedule();
          }
        }
      });
      const req = { type: "VSCODE_EXTHOST_IPC_READY" };
      process.send?.(req);
    });
  } else {
    const pipeName = extHostConnection.pipeName;
    return new Promise((resolve, reject) => {
      const socket = net5.createConnection(pipeName, () => {
        socket.removeListener("error", reject);
        const protocol = new $tu({ socket: new $uu(socket, "extHost-renderer") });
        protocol.sendResume();
        resolve(protocol);
      });
      socket.once("error", reject);
      socket.on("close", () => {
        onTerminate("renderer closed the socket");
      });
    });
  }
}
async function createExtHostProtocol() {
  const protocol = await _createExtHostProtocol();
  return new class {
    constructor() {
      this.a = new $su();
      this.onMessage = this.a.event;
      this.b = false;
      this.d = protocol.onMessage((msg) => {
        if ($kN(
          msg,
          2
          /* MessageType.Terminate */
        )) {
          this.b = true;
          this.d.dispose();
          onTerminate("received terminate message from renderer");
        } else {
          this.a.fire(msg);
        }
      });
    }
    send(msg) {
      if (!this.b) {
        protocol.send(msg);
      }
    }
    async drain() {
      if (protocol.drain) {
        return protocol.drain();
      }
    }
  }();
}
function connectToRenderer(protocol) {
  return new Promise((c) => {
    const first = protocol.onMessage((raw) => {
      first.dispose();
      const initData = JSON.parse(raw.toString());
      const rendererCommit = initData.commit;
      const myCommit = product_default.commit;
      if (rendererCommit && myCommit) {
        if (rendererCommit !== myCommit) {
          nativeExit(
            55
            /* ExtensionHostExitCode.VersionMismatch */
          );
        }
      }
      if (initData.parentPid) {
        let epermErrors = 0;
        setInterval(function() {
          try {
            process.kill(initData.parentPid, 0);
            epermErrors = 0;
          } catch (e) {
            if (e && e.code === "EPERM") {
              epermErrors++;
              if (epermErrors >= 3) {
                onTerminate(`parent process ${initData.parentPid} does not exist anymore (3 x EPERM): ${e.message} (code: ${e.code}) (errno: ${e.errno})`);
              }
            } else {
              onTerminate(`parent process ${initData.parentPid} does not exist anymore: ${e.message} (code: ${e.code}) (errno: ${e.errno})`);
            }
          }
        }, 1e3);
        let watchdog;
        try {
          watchdog = require4("native-watchdog");
          watchdog.start(initData.parentPid);
        } catch (err) {
          $gb(err);
        }
      }
      protocol.send($jN(
        0
        /* MessageType.Initialized */
      ));
      c({ protocol, initData });
    });
    protocol.send($jN(
      1
      /* MessageType.Ready */
    ));
  });
}
async function startExtensionHostProcess() {
  const unhandledPromises = [];
  process.on("unhandledRejection", (reason, promise) => {
    unhandledPromises.push(promise);
    setTimeout(() => {
      const idx = unhandledPromises.indexOf(promise);
      if (idx >= 0) {
        promise.catch((e) => {
          unhandledPromises.splice(idx, 1);
          if (!$kb(e)) {
            console.warn(`rejected promise not handled within 1 second: ${e}`);
            if (e && e.stack) {
              console.warn(`stack trace: ${e.stack}`);
            }
            if (reason) {
              $gb(reason);
            }
          }
        });
      }
    }, 1e3);
  });
  process.on("rejectionHandled", (promise) => {
    const idx = unhandledPromises.indexOf(promise);
    if (idx >= 0) {
      unhandledPromises.splice(idx, 1);
    }
  });
  process.on("uncaughtException", function(err) {
    if (!$eb(err)) {
      $gb(err);
    }
  });
  $S(`code/extHost/willConnectToRenderer`);
  const protocol = await createExtHostProtocol();
  $S(`code/extHost/didConnectToRenderer`);
  const renderer = await connectToRenderer(protocol);
  $S(`code/extHost/didWaitForInitData`);
  const { initData } = renderer;
  patchProcess(!!initData.environment.extensionTestsLocationURI);
  initData.environment.useHostProxy = args.useHostProxy !== void 0 ? args.useHostProxy !== "false" : void 0;
  initData.environment.skipWorkspaceStorageLock = boolean(args.skipWorkspaceStorageLock, false);
  const hostUtils = new class NodeHost {
    constructor() {
      this.pid = process.pid;
    }
    exit(code) {
      nativeExit(code);
    }
    fsExists(path) {
      return Promises2.exists(path);
    }
    fsRealpath(path) {
      return $5s(path);
    }
  }();
  let uriTransformer = null;
  if (initData.remote.authority && args.transformURIs) {
    uriTransformer = $FX(initData.remote.authority);
  }
  const extensionHostMain = new $7yc(renderer.protocol, initData, hostUtils, uriTransformer);
  onTerminate = (reason) => extensionHostMain.terminate(reason);
}
startExtensionHostProcess().catch((err) => console.log(err));

//# sourceMappingURL=extensionHostProcess.js.map
