/*!--------------------------------------------------------
 * 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 Q1=Object.defineProperty;var X1=Object.getOwnPropertyDescriptor;var b=(o,r,e,t)=>{for(var n=t>1?void 0:t?X1(r,e):r,i=o.length-1,s;i>=0;i--)(s=o[i])&&(n=(t?s(r,e,n):s(n))||n);return t&&n&&Q1(r,e,n),n},g=(o,r)=>(e,t)=>r(e,t,o);import{hostname as _C,release as kC}from"os";function Y1(o,r,e=0,t=o.length){let n=e,i=t;for(;n<i;){let s=Math.floor((n+i)/2);r(o[s])?n=s+1:i=s}return n-1}var hy=class o{constructor(r){this._array=r;this._findLastMonotonousLastIdx=0}static{this.assertInvariants=!1}findLastMonotonous(r){if(o.assertInvariants){if(this._prevFindLastPredicate){for(let t of this._array)if(this._prevFindLastPredicate(t)&&!r(t))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=r}let e=Y1(this._array,r,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=e+1,e===-1?void 0:this._array[e]}};var fm=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(r){setTimeout(()=>{throw r.stack?$r.isErrorNoTelemetry(r)?new $r(r.message+`

`+r.stack):new Error(r.message+`

`+r.stack):r},0)}}addListener(r){return this.listeners.push(r),()=>{this._removeListener(r)}}emit(r){this.listeners.forEach(e=>{e(r)})}_removeListener(r){this.listeners.splice(this.listeners.indexOf(r),1)}setUnexpectedErrorHandler(r){this.unexpectedErrorHandler=r}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(r){this.unexpectedErrorHandler(r),this.emit(r)}onUnexpectedExternalError(r){this.unexpectedErrorHandler(r)}},yy=new fm;function Sy(o){yy.setUnexpectedErrorHandler(o)}function Me(o){lr(o)||yy.onUnexpectedError(o)}var Yc="Canceled";function lr(o){return o instanceof We?!0:o instanceof Error&&o.name===Yc&&o.message===Yc}var We=class extends Error{constructor(){super(Yc),this.name=this.message}},vy=class o extends Error{static{this._name="PendingMigrationError"}static is(r){return r instanceof o||r instanceof Error&&r.name===o._name}constructor(r){super(r),this.name=o._name}};function Yn(){let o=new Error(Yc);return o.name=o.message,o}function mm(o){return o?new Error(`Illegal argument: ${o}`):new Error("Illegal argument")}function Zc(o){return o?new Error(`Illegal state: ${o}`):new Error("Illegal state")}function ee(o){return o?o.message?o.message:o.stack?o.stack.split(`
`)[0]:String(o):"Error"}var $r=class o extends Error{constructor(r){super(r),this.name="CodeExpectedError"}static fromError(r){if(r instanceof o)return r;let e=new o;return e.message=r.message,e.stack=r.stack,e}static isErrorNoTelemetry(r){return r.name==="CodeExpectedError"}},Xn=class o extends Error{constructor(r){super(r||"An unexpected bug occurred."),Object.setPrototypeOf(this,o.prototype)}};function Pt(o,r,e=(t,n)=>t===n){if(o===r)return!0;if(!o||!r||o.length!==r.length)return!1;for(let t=0,n=o.length;t<n;t++)if(!e(o[t],r[t]))return!1;return!0}function ed(o,r,e){if(o=o|0,o>=r.length)throw new TypeError("invalid index");let t=r[Math.floor(r.length*Math.random())],n=[],i=[],s=[];for(let a of r){let l=e(a,t);l<0?n.push(a):l>0?i.push(a):s.push(a)}return o<n.length?ed(o,n,e):o<n.length+s.length?s[0]:ed(o-(n.length+s.length),i,e)}function hn(o){return o.filter(r=>!!r)}function Zn(o){return Array.isArray(o)&&o.length>0}function dt(o,r=e=>e){let e=new Set;return o.filter(t=>{let n=r(t);return e.has(n)?!1:(e.add(n),!0)})}function gm(o,r){return o.push(r),()=>Z1(o,r)}function Z1(o,r){let e=o.indexOf(r);if(e>-1)return o.splice(e,1),r}function hm(o,r){let e;if(typeof r=="number"){let t=r;e=()=>{let n=Math.sin(t++)*179426549;return n-Math.floor(n)}}else e=Math.random;for(let t=o.length-1;t>0;t-=1){let n=Math.floor(e()*(t+1)),i=o[t];o[t]=o[n],o[n]=i}}function xy(o){return o[Math.floor(Math.random()*o.length)]}var Ey;(a=>{function o(l){return l<0}a.isLessThan=o;function r(l){return l<=0}a.isLessThanOrEqual=r;function e(l){return l>0}a.isGreaterThan=e;function t(l){return l===0}a.isNeitherLessOrGreaterThan=t,a.greaterThan=1,a.lessThan=-1,a.neitherLessOrGreaterThan=0})(Ey||={});function wy(o,r){return(e,t)=>r(o(e),o(t))}var Py=(o,r)=>o-r;var by=class o{constructor(r){this.iterate=r}static{this.empty=new o(r=>{})}forEach(r){this.iterate(e=>(r(e),!0))}toArray(){let r=[];return this.iterate(e=>(r.push(e),!0)),r}filter(r){return new o(e=>this.iterate(t=>r(t)?e(t):!0))}map(r){return new o(e=>this.iterate(t=>e(r(t))))}some(r){let e=!1;return this.iterate(t=>(e=r(t),!e)),e}findFirst(r){let e;return this.iterate(t=>r(t)?(e=t,!1):!0),e}findLast(r){let e;return this.iterate(t=>(r(t)&&(e=t),!0)),e}findLastMaxBy(r){let e,t=!0;return this.iterate(n=>((t||Ey.isGreaterThan(r(n,e)))&&(t=!1,e=n),!0)),e}};function td(o,r){if(!o)throw new Error(r?`Assertion failed (${r})`:"Assertion Failed")}function vm(o,r="Unreachable"){throw new Error(r)}function Bo(o,r="unexpected state"){if(!o)throw typeof r=="string"?new Xn(`Assertion Failed: ${r}`):r}function ue(o){return typeof o=="string"}function Re(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)&&!(o instanceof RegExp)&&!(o instanceof Date)}function Ty(o){let r=Object.getPrototypeOf(Uint8Array);return typeof o=="object"&&o instanceof r}function Un(o){return typeof o=="number"&&!isNaN(o)}function Cy(o){return!!o&&typeof o[Symbol.iterator]=="function"}function Bt(o){return o===!0||o===!1}function st(o){return typeof o>"u"}function rd(o){return!ft(o)}function ft(o){return st(o)||o===null}function Dy(o,r){if(!o)throw new Error(r?`Unexpected type, expected '${r}'`:"Unexpected type")}function Tr(o){return Bo(o!=null,"Argument is `undefined` or `null`."),o}var tE=Object.prototype.hasOwnProperty;function nd(o){if(!Re(o))return!1;for(let r in o)if(tE.call(o,r))return!1;return!0}function gl(o){return typeof o=="function"}function rE(){return globalThis._VSCODE_NLS_MESSAGES}function ym(){return globalThis._VSCODE_NLS_LANGUAGE}var nE=ym()==="pseudo"||typeof document<"u"&&document.location&&typeof document.location.hash=="string"&&document.location.hash.indexOf("pseudo=true")>=0;function id(o,r){let e;return r.length===0?e=o:e=o.replace(/\{(\d+)\}/g,(t,n)=>{let i=r[parseInt(n)],s=t;return typeof i=="string"?s=i:(typeof i=="number"||typeof i=="boolean"||i===void 0||i===null)&&(s=String(i)),s}),nE&&(e="\uFF3B"+e.replace(/[aouei]/g,"$&$&")+"\uFF3D"),e}function S(o,r,...e){return id(typeof o=="number"?_y(o,r):r,e)}function _y(o,r){let e=rE()?.[o];if(typeof e!="string"){if(typeof r=="string")return r;throw new Error(`!!! NLS MISSING: ${o} !!!`)}return e}function Sm(o,r,...e){let t;typeof o=="number"?t=_y(o,r):t=r;let n=id(t,e);return{value:n,original:r===t?n:id(r,e)}}function Im(o,r){return r&&(o.stack||o.stacktrace)?S(119,null,Uy(o),ky(o.stack)||ky(o.stacktrace)):Uy(o)}function ky(o){return Array.isArray(o)?o.join(`
`):o}function Uy(o){return o.code==="ERR_UNC_HOST_NOT_ALLOWED"?`${o.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`:typeof o.code=="string"&&typeof o.errno=="number"&&typeof o.syscall=="string"?S(118,null,o.message):o.message||S(116,null)}function _t(o=null,r=!1){if(!o)return S(116,null);if(Array.isArray(o)){let e=hn(o),t=_t(e[0],r);return e.length>1?S(117,null,t,e.length):t}if(ue(o))return o;if(o.detail){let e=o.detail;if(e.error)return Im(e.error,r);if(e.exception)return Im(e.exception,r)}return o.stack?Im(o,r):o.message?o.message:S(116,null)}function Fy(o,r){let e=Object.create(null);for(let t of o){let n=r(t),i=e[n];i||(i=e[n]=[]),i.push(t)}return e}var My,Ay,Ly=class{constructor(r,e){this.toKey=e;this._map=new Map;this[My]="SetWithKey";for(let t of r)this.add(t)}get size(){return this._map.size}add(r){let e=this.toKey(r);return this._map.set(e,r),this}delete(r){return this._map.delete(this.toKey(r))}has(r){return this._map.has(this.toKey(r))}*entries(){for(let r of this._map.values())yield[r,r]}keys(){return this.values()}*values(){for(let r of this._map.values())yield r}clear(){this._map.clear()}forEach(r,e){this._map.forEach(t=>r.call(e,t,t,this))}[(Ay=Symbol.iterator,My=Symbol.toStringTag,Ay)](){return this.values()}};var bm=class{constructor(r,e){this.uri=r;this.value=e}};function iE(o){return Array.isArray(o)}var Oy,He=class o{constructor(r,e){this[Oy]="ResourceMap";if(r instanceof o)this.map=new Map(r.map),this.toKey=e??o.defaultToKey;else if(iE(r)){this.map=new Map,this.toKey=e??o.defaultToKey;for(let[t,n]of r)this.set(t,n)}else this.map=new Map,this.toKey=r??o.defaultToKey}static{this.defaultToKey=r=>r.toString()}set(r,e){return this.map.set(this.toKey(r),new bm(r,e)),this}get(r){return this.map.get(this.toKey(r))?.value}has(r){return this.map.has(this.toKey(r))}get size(){return this.map.size}clear(){this.map.clear()}delete(r){return this.map.delete(this.toKey(r))}forEach(r,e){typeof e<"u"&&(r=r.bind(e));for(let[t,n]of this.map)r(n.value,n.uri,this)}*values(){for(let r of this.map.values())yield r.value}*keys(){for(let r of this.map.values())yield r.uri}*entries(){for(let r of this.map.values())yield[r.uri,r.value]}*[(Oy=Symbol.toStringTag,Symbol.iterator)](){for(let[,r]of this.map)yield[r.uri,r.value]}},Ny,ei=class{constructor(r,e){this[Ny]="ResourceSet";!r||typeof r=="function"?this._map=new He(r):(this._map=new He(e),r.forEach(this.add,this))}get size(){return this._map.size}add(r){return this._map.set(r,r),this}clear(){this._map.clear()}delete(r){return this._map.delete(r)}forEach(r,e){this._map.forEach((t,n)=>r.call(e,n,n,this))}has(r){return this._map.has(r)}entries(){return this._map.entries()}keys(){return this._map.keys()}values(){return this._map.keys()}[(Ny=Symbol.toStringTag,Symbol.iterator)](){return this.keys()}};var Vy,xm=class{constructor(){this[Vy]="LinkedMap";this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(r){return this._map.has(r)}get(r,e=0){let t=this._map.get(r);if(t)return e!==0&&this.touch(t,e),t.value}set(r,e,t=0){let n=this._map.get(r);if(n)n.value=e,t!==0&&this.touch(n,t);else{switch(n={key:r,value:e,next:void 0,previous:void 0},t){case 0:this.addItemLast(n);break;case 1:this.addItemFirst(n);break;case 2:this.addItemLast(n);break;default:this.addItemLast(n);break}this._map.set(r,n),this._size++}return this}delete(r){return!!this.remove(r)}remove(r){let e=this._map.get(r);if(e)return this._map.delete(r),this.removeItem(e),this._size--,e.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let r=this._head;return this._map.delete(r.key),this.removeItem(r),this._size--,r.value}forEach(r,e){let t=this._state,n=this._head;for(;n;){if(e?r.bind(e)(n.value,n.key,this):r(n.value,n.key,this),this._state!==t)throw new Error("LinkedMap got modified during iteration.");n=n.next}}keys(){let r=this,e=this._state,t=this._head,n={[Symbol.iterator](){return n},next(){if(r._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:t.key,done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return n}values(){let r=this,e=this._state,t=this._head,n={[Symbol.iterator](){return n},next(){if(r._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:t.value,done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return n}entries(){let r=this,e=this._state,t=this._head,n={[Symbol.iterator](){return n},next(){if(r._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:[t.key,t.value],done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return n}[(Vy=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(r){if(r>=this.size)return;if(r===0){this.clear();return}let e=this._head,t=this.size;for(;e&&t>r;)this._map.delete(e.key),e=e.next,t--;this._head=e,this._size=t,e&&(e.previous=void 0),this._state++}trimNew(r){if(r>=this.size)return;if(r===0){this.clear();return}let e=this._tail,t=this.size;for(;e&&t>r;)this._map.delete(e.key),e=e.previous,t--;this._tail=e,this._size=t,e&&(e.next=void 0),this._state++}addItemFirst(r){if(!this._head&&!this._tail)this._tail=r;else if(this._head)r.next=this._head,this._head.previous=r;else throw new Error("Invalid list");this._head=r,this._state++}addItemLast(r){if(!this._head&&!this._tail)this._head=r;else if(this._tail)r.previous=this._tail,this._tail.next=r;else throw new Error("Invalid list");this._tail=r,this._state++}removeItem(r){if(r===this._head&&r===this._tail)this._head=void 0,this._tail=void 0;else if(r===this._head){if(!r.next)throw new Error("Invalid list");r.next.previous=void 0,this._head=r.next}else if(r===this._tail){if(!r.previous)throw new Error("Invalid list");r.previous.next=void 0,this._tail=r.previous}else{let e=r.next,t=r.previous;if(!e||!t)throw new Error("Invalid list");e.previous=t,t.next=e}r.next=void 0,r.previous=void 0,this._state++}touch(r,e){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(e!==1&&e!==2)){if(e===1){if(r===this._head)return;let t=r.next,n=r.previous;r===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),r.previous=void 0,r.next=this._head,this._head.previous=r,this._head=r,this._state++}else if(e===2){if(r===this._tail)return;let t=r.next,n=r.previous;r===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),r.next=void 0,r.previous=this._tail,this._tail.next=r,this._tail=r,this._state++}}}toJSON(){let r=[];return this.forEach((e,t)=>{r.push([t,e])}),r}fromJSON(r){this.clear();for(let[e,t]of r)this.set(e,t)}},Em=class extends xm{constructor(r,e=1){super(),this._limit=r,this._ratio=Math.min(Math.max(0,e),1)}get limit(){return this._limit}set limit(r){this._limit=r,this.checkTrim()}get ratio(){return this._ratio}set ratio(r){this._ratio=Math.min(Math.max(0,r),1),this.checkTrim()}get(r,e=2){return super.get(r,e)}peek(r){return super.get(r,0)}set(r,e){return super.set(r,e,2),this}checkTrim(){this.size>this._limit&&this.trim(Math.round(this._limit*this._ratio))}},yn=class extends Em{constructor(r,e=1){super(r,e)}trim(r){this.trimOld(r)}set(r,e){return super.set(r,e),this.checkTrim(),this}};var od=class{constructor(){this.map=new Map}add(r,e){let t=this.map.get(r);t||(t=new Set,this.map.set(r,t)),t.add(e)}delete(r,e){let t=this.map.get(r);t&&(t.delete(e),t.size===0&&this.map.delete(r))}forEach(r,e){let t=this.map.get(r);t&&t.forEach(e)}get(r){let e=this.map.get(r);return e||new Set}};function hl(o,r){let e=this,t=!1,n;return function(){if(t)return n;if(t=!0,r)try{n=o.apply(e,arguments)}finally{r()}else n=o.apply(e,arguments);return n}}var ti;(qe=>{function o(B){return!!B&&typeof B=="object"&&typeof B[Symbol.iterator]=="function"}qe.is=o;let r=Object.freeze([]);function e(){return r}qe.empty=e;function*t(B){yield B}qe.single=t;function n(B){return o(B)?B:t(B)}qe.wrap=n;function i(B){return B??r}qe.from=i;function*s(B){for(let C=B.length-1;C>=0;C--)yield B[C]}qe.reverse=s;function a(B){return!B||B[Symbol.iterator]().next().done===!0}qe.isEmpty=a;function l(B){return B[Symbol.iterator]().next().value}qe.first=l;function c(B,C){let A=0;for(let ae of B)if(C(ae,A++))return!0;return!1}qe.some=c;function d(B,C){let A=0;for(let ae of B)if(!C(ae,A++))return!1;return!0}qe.every=d;function u(B,C){for(let A of B)if(C(A))return A}qe.find=u;function*p(B,C){for(let A of B)C(A)&&(yield A)}qe.filter=p;function*m(B,C){let A=0;for(let ae of B)yield C(ae,A++)}qe.map=m;function*h(B,C){let A=0;for(let ae of B)yield*C(ae,A++)}qe.flatMap=h;function*v(...B){for(let C of B)Cy(C)?yield*C:yield C}qe.concat=v;function y(B,C,A){let ae=A;for(let J of B)ae=C(ae,J);return ae}qe.reduce=y;function x(B){let C=0;for(let A of B)C++;return C}qe.length=x;function*E(B,C,A=B.length){for(C<-B.length&&(C=0),C<0&&(C+=B.length),A<0?A+=B.length:A>B.length&&(A=B.length);C<A;C++)yield B[C]}qe.slice=E;function R(B,C=Number.POSITIVE_INFINITY){let A=[];if(C===0)return[A,B];let ae=B[Symbol.iterator]();for(let J=0;J<C;J++){let ge=ae.next();if(ge.done)return[A,qe.empty()];A.push(ge.value)}return[A,{[Symbol.iterator](){return ae}}]}qe.consume=R;async function F(B){let C=[];for await(let A of B)C.push(A);return C}qe.asyncToArray=F;async function H(B){let C=[];for await(let A of B)C=C.concat(A);return C}qe.asyncToArrayFlat=H})(ti||={});var oE=!1,Go=null;var Wy=class o{constructor(){this.livingDisposables=new Map}static{this.idx=0}getDisposableData(r){let e=this.livingDisposables.get(r);return e||(e={parent:null,source:null,isSingleton:!1,value:r,idx:o.idx++},this.livingDisposables.set(r,e)),e}trackDisposable(r){let e=this.getDisposableData(r);e.source||(e.source=new Error().stack)}setParent(r,e){let t=this.getDisposableData(r);t.parent=e}markAsDisposed(r){this.livingDisposables.delete(r)}markAsSingleton(r){this.getDisposableData(r).isSingleton=!0}getRootParent(r,e){let t=e.get(r);if(t)return t;let n=r.parent?this.getRootParent(this.getDisposableData(r.parent),e):r;return e.set(r,n),n}getTrackedDisposables(){let r=new Map;return[...this.livingDisposables.entries()].filter(([,t])=>t.source!==null&&!this.getRootParent(t,r).isSingleton).flatMap(([t])=>t)}computeLeakingDisposables(r=10,e){let t;if(e)t=e;else{let l=new Map,c=[...this.livingDisposables.values()].filter(u=>u.source!==null&&!this.getRootParent(u,l).isSingleton);if(c.length===0)return;let d=new Set(c.map(u=>u.value));if(t=c.filter(u=>!(u.parent&&d.has(u.parent))),t.length===0)throw new Error("There are cyclic diposable chains!")}if(!t)return;function n(l){function c(u,p){for(;u.length>0&&p.some(m=>typeof m=="string"?m===u[0]:u[0].match(m));)u.shift()}let d=l.source.split(`
`).map(u=>u.trim().replace("at ","")).filter(u=>u!=="");return c(d,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),d.reverse()}let i=new od;for(let l of t){let c=n(l);for(let d=0;d<=c.length;d++)i.add(c.slice(0,d).join(`
`),l)}t.sort(wy(l=>l.idx,Py));let s="",a=0;for(let l of t.slice(0,r)){a++;let c=n(l),d=[];for(let u=0;u<c.length;u++){let p=c[u];p=`(shared with ${i.get(c.slice(0,u+1).join(`
`)).size}/${t.length} leaks) at ${p}`;let h=i.get(c.slice(0,u).join(`
`)),v=Fy([...h].map(y=>n(y)[u]),y=>y);delete v[c[u]];for(let[y,x]of Object.entries(v))x&&d.unshift(`    - stacktraces of ${x.length} other leaks continue with ${y}`);d.unshift(p)}s+=`


==================== Leaking disposable ${a}/${t.length}: ${l.value.constructor.name} ====================
${d.join(`
`)}
============================================================

`}return t.length>r&&(s+=`


... and ${t.length-r} more leaking disposables

`),{leaks:t,details:s}}};function sE(o){Go=o}if(oE){let o="__is_disposable_tracked__";sE(new class{trackDisposable(r){let e=new Error("Potentially leaked disposable").stack;setTimeout(()=>{r[o]||console.log(e)},3e3)}setParent(r,e){if(r&&r!==T.None)try{r[o]=!0}catch{}}markAsDisposed(r){if(r&&r!==T.None)try{r[o]=!0}catch{}}markAsSingleton(r){}})}function vl(o){return Go?.trackDisposable(o),o}function yl(o){Go?.markAsDisposed(o)}function Gi(o,r){Go?.setParent(o,r)}function aE(o,r){if(Go)for(let e of o)Go.setParent(e,r)}function qo(o){return typeof o=="object"&&o!==null&&typeof o.dispose=="function"&&o.dispose.length===0}function $t(o){if(ti.is(o)){let r=[];for(let e of o)if(e)try{e.dispose()}catch(t){r.push(t)}if(r.length===1)throw r[0];if(r.length>1)throw new AggregateError(r,"Encountered errors while disposing of store");return Array.isArray(o)?[]:o}else if(o)return o.dispose(),o}function zo(...o){let r=oe(()=>$t(o));return aE(o,r),r}var wm=class{constructor(r){this._isDisposed=!1,this._fn=r,vl(this)}dispose(){if(!this._isDisposed){if(!this._fn)throw new Error("Unbound disposable context: Need to use an arrow function to preserve the value of this");this._isDisposed=!0,yl(this),this._fn()}}};function oe(o){return new wm(o)}var se=class o{constructor(){this._toDispose=new Set;this._isDisposed=!1;vl(this)}static{this.DISABLE_DISPOSED_WARNING=!1}dispose(){this._isDisposed||(yl(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{$t(this._toDispose)}finally{this._toDispose.clear()}}add(r){if(!r||r===T.None)return r;if(r===this)throw new Error("Cannot register a disposable on itself!");return Gi(r,this),this._isDisposed?o.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):this._toDispose.add(r),r}delete(r){if(r){if(r===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(r),r.dispose()}}deleteAndLeak(r){r&&this._toDispose.delete(r)&&Gi(r,null)}assertNotDisposed(){this._isDisposed&&Me(new Xn("Object disposed"))}},T=class{constructor(){this._store=new se;vl(this),Gi(this._store,this)}static{this.None=Object.freeze({dispose(){}})}dispose(){yl(this),this._store.dispose()}_register(r){if(r===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(r)}},kt=class{constructor(){this._isDisposed=!1;vl(this)}get value(){return this._isDisposed?void 0:this._value}set value(r){this._isDisposed||r===this._value||(this._value?.dispose(),r&&Gi(r,this),this._value=r)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,yl(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let r=this._value;return this._value=void 0,r&&Gi(r,null),r}};var Gr=class{constructor(r=new Map){this._isDisposed=!1;this._store=r,vl(this)}dispose(){yl(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{$t(this._store.values())}finally{this._store.clear()}}has(r){return this._store.has(r)}get size(){return this._store.size}get(r){return this._store.get(r)}set(r,e,t=!1){this._isDisposed&&console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack),t||this._store.get(r)?.dispose(),this._store.set(r,e),Gi(e,this)}deleteAndDispose(r){this._store.get(r)?.dispose(),this._store.delete(r)}deleteAndLeak(r){let e=this._store.get(r);return e&&Gi(e,null),this._store.delete(r),e}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}};function By(o,r){return o.then(e=>(r.isDisposed?e.dispose():r.add(e),e))}var qi="en",Il=!1,bl=!1,Sl=!1,Gy=!1,qy=!1,Pm=!1,lE=!1,zy=!1,cE=!1,dE=!1,sd,ad=qi,$y=qi,Ky,Ln,Mn=globalThis,vr;typeof Mn.vscode<"u"&&typeof Mn.vscode.process<"u"?vr=Mn.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(vr=process);var jy=typeof vr?.versions?.electron=="string",uE=jy&&vr?.type==="renderer";if(typeof vr=="object"){Il=vr.platform==="win32",bl=vr.platform==="darwin",Sl=vr.platform==="linux",Gy=Sl&&!!vr.env.SNAP&&!!vr.env.SNAP_REVISION,lE=jy,cE=!!vr.env.CI||!!vr.env.BUILD_ARTIFACTSTAGINGDIRECTORY||!!vr.env.GITHUB_WORKSPACE,sd=qi,ad=qi;let o=vr.env.VSCODE_NLS_CONFIG;if(o)try{let r=JSON.parse(o);sd=r.userLocale,$y=r.osLocale,ad=r.resolvedLanguage||qi,Ky=r.languagePack?.translationsConfigFile}catch{}qy=!0}else typeof navigator=="object"&&!uE?(Ln=navigator.userAgent,Il=Ln.indexOf("Windows")>=0,bl=Ln.indexOf("Macintosh")>=0,zy=(Ln.indexOf("Macintosh")>=0||Ln.indexOf("iPad")>=0||Ln.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Sl=Ln.indexOf("Linux")>=0,dE=Ln?.indexOf("Mobi")>=0,Pm=!0,ad=ym()||qi,sd=navigator.language.toLowerCase(),$y=sd):console.error("Unable to resolve platform.");function cd(o){switch(o){case 0:return"Web";case 1:return"Mac";case 2:return"Linux";case 3:return"Windows"}}var ld=0;bl?ld=1:Il?ld=3:Sl&&(ld=2);var he=Il,Gt=bl,Be=Sl,Hy=Gy,Jy=qy;var ze=Pm,pE=Pm&&typeof Mn.importScripts=="function",Qy=pE?Mn.origin:void 0;var In=ld,Sn=Ln,Cr=ad,fE;(t=>{function o(){return Cr}t.value=o;function r(){return Cr.length===2?Cr==="en":Cr.length>=3?Cr[0]==="e"&&Cr[1]==="n"&&Cr[2]==="-":!1}t.isDefaultVariant=r;function e(){return Cr==="en"}t.isDefault=e})(fE||={});var Rm=Ky,mE=typeof Mn.postMessage=="function"&&!Mn.importScripts,Xy=(()=>{if(mE){let o=[];Mn.addEventListener("message",e=>{if(e.data&&e.data.vscodeScheduleAsyncWork)for(let t=0,n=o.length;t<n;t++){let i=o[t];if(i.id===e.data.vscodeScheduleAsyncWork){o.splice(t,1),i.callback();return}}});let r=0;return e=>{let t=++r;o.push({id:t,callback:e}),Mn.postMessage({vscodeScheduleAsyncWork:t},"*")}}return o=>setTimeout(o)})();var bn=bl||zy?2:Il?1:3;var xl=!!(Sn&&Sn.indexOf("Chrome")>=0),dd=!!(Sn&&Sn.indexOf("Firefox")>=0),ud=!!(!xl&&Sn&&Sn.indexOf("Safari")>=0),pd=!!(Sn&&Sn.indexOf("Edg/")>=0),Yy=!!(Sn&&Sn.indexOf("Android")>=0);var at=class o{static{this.Undefined=new o(void 0)}constructor(r){this.element=r,this.next=o.Undefined,this.prev=o.Undefined}},jo=class{constructor(){this._first=at.Undefined;this._last=at.Undefined;this._size=0}get size(){return this._size}isEmpty(){return this._first===at.Undefined}clear(){let r=this._first;for(;r!==at.Undefined;){let e=r.next;r.prev=at.Undefined,r.next=at.Undefined,r=e}this._first=at.Undefined,this._last=at.Undefined,this._size=0}unshift(r){return this._insert(r,!1)}push(r){return this._insert(r,!0)}_insert(r,e){let t=new at(r);if(this._first===at.Undefined)this._first=t,this._last=t;else if(e){let i=this._last;this._last=t,t.prev=i,i.next=t}else{let i=this._first;this._first=t,t.next=i,i.prev=t}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(t))}}shift(){if(this._first!==at.Undefined){let r=this._first.element;return this._remove(this._first),r}}pop(){if(this._last!==at.Undefined){let r=this._last.element;return this._remove(this._last),r}}peek(){if(this._last!==at.Undefined)return this._last.element}_remove(r){if(r.prev!==at.Undefined&&r.next!==at.Undefined){let e=r.prev;e.next=r.next,r.next.prev=e}else r.prev===at.Undefined&&r.next===at.Undefined?(this._first=at.Undefined,this._last=at.Undefined):r.next===at.Undefined?(this._last=this._last.prev,this._last.next=at.Undefined):r.prev===at.Undefined&&(this._first=this._first.next,this._first.prev=at.Undefined);this._size-=1}*[Symbol.iterator](){let r=this._first;for(;r!==at.Undefined;)yield r.element,r=r.next}};var gE=globalThis.performance.now.bind(globalThis.performance),qr=class o{static create(r){return new o(r)}constructor(r){this._now=r===!1?Date.now:gE,this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}};var Zy=!1,hE=!1,k;(Ze=>{Ze.None=()=>T.None;function r(N){if(hE){let{onDidAddListener:O}=N,q=El.create(),z=0;N.onDidAddListener=()=>{++z===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),q.print()),O?.()}}}function e(N,O,q){return m(N,()=>{},0,void 0,O??!0,void 0,q)}Ze.defer=e;function t(N){return(O,q=null,z)=>{let Z=!1,pe;return pe=N(Ee=>{if(!Z)return pe?pe.dispose():Z=!0,O.call(q,Ee)},null,z),Z&&pe.dispose(),pe}}Ze.once=t;function n(N,O){return Ze.once(Ze.filter(N,O))}Ze.onceIf=n;function i(N,O,q){return u((z,Z=null,pe)=>N(Ee=>z.call(Z,O(Ee)),null,pe),q)}Ze.map=i;function s(N,O,q){return u((z,Z=null,pe)=>N(Ee=>{O(Ee),z.call(Z,Ee)},null,pe),q)}Ze.forEach=s;function a(N,O,q){return u((z,Z=null,pe)=>N(Ee=>O(Ee)&&z.call(Z,Ee),null,pe),q)}Ze.filter=a;function l(N){return N}Ze.signal=l;function c(...N){return(O,q=null,z)=>{let Z=zo(...N.map(pe=>pe(Ee=>O.call(q,Ee))));return p(Z,z)}}Ze.any=c;function d(N,O,q,z){let Z=q;return i(N,pe=>(Z=O(Z,pe),Z),z)}Ze.reduce=d;function u(N,O){let q,z={onWillAddFirstListener(){q=N(Z.fire,Z)},onDidRemoveLastListener(){q?.dispose()}};O||r(z);let Z=new w(z);return O?.add(Z),Z.event}function p(N,O){return O instanceof Array?O.push(N):O&&O.add(N),N}function m(N,O,q=100,z=!1,Z=!1,pe,Ee){let ot,Ye,Kt,Yt=0,Rr,sr={leakWarningThreshold:pe,onWillAddFirstListener(){ot=N(dl=>{Yt++,Ye=O(Ye,dl),z&&!Kt&&(mn.fire(Ye),Ye=void 0),Rr=()=>{let ul=Ye;Ye=void 0,Kt=void 0,(!z||Yt>1)&&mn.fire(ul),Yt=0},typeof q=="number"?(Kt&&clearTimeout(Kt),Kt=setTimeout(Rr,q)):Kt===void 0&&(Kt=null,queueMicrotask(Rr))})},onWillRemoveListener(){Z&&Yt>0&&Rr?.()},onDidRemoveLastListener(){Rr=void 0,ot.dispose()}};Ee||r(sr);let mn=new w(sr);return Ee?.add(mn),mn.event}Ze.debounce=m;function h(N,O=0,q,z){return Ze.debounce(N,(Z,pe)=>Z?(Z.push(pe),Z):[pe],O,void 0,q??!0,void 0,z)}Ze.accumulate=h;function v(N,O,q=100,z=!0,Z=!0,pe,Ee){let ot,Ye,Kt,Yt=0,Rr={leakWarningThreshold:pe,onWillAddFirstListener(){ot=N(mn=>{Yt++,Ye=O(Ye,mn),Kt===void 0&&(z&&(sr.fire(Ye),Ye=void 0,Yt=0),typeof q=="number"?Kt=setTimeout(()=>{Z&&Yt>0&&sr.fire(Ye),Ye=void 0,Kt=void 0,Yt=0},q):(Kt=0,queueMicrotask(()=>{Z&&Yt>0&&sr.fire(Ye),Ye=void 0,Kt=void 0,Yt=0})))})},onDidRemoveLastListener(){ot.dispose()}};Ee||r(Rr);let sr=new w(Rr);return Ee?.add(sr),sr.event}Ze.throttle=v;function y(N,O=(z,Z)=>z===Z,q){let z=!0,Z;return a(N,pe=>{let Ee=z||!O(pe,Z);return z=!1,Z=pe,Ee},q)}Ze.latch=y;function x(N,O,q){return[Ze.filter(N,O,q),Ze.filter(N,z=>!O(z),q)]}Ze.split=x;function E(N,O=!1,q=[],z){let Z=q.slice(),pe=N(Ye=>{Z?Z.push(Ye):ot.fire(Ye)});z&&z.add(pe);let Ee=()=>{Z?.forEach(Ye=>ot.fire(Ye)),Z=null},ot=new w({onWillAddFirstListener(){pe||(pe=N(Ye=>ot.fire(Ye)),z&&z.add(pe))},onDidAddFirstListener(){Z&&(O?setTimeout(Ee):Ee())},onDidRemoveLastListener(){pe&&pe.dispose(),pe=null}});return z&&z.add(ot),ot.event}Ze.buffer=E;function R(N,O){return(z,Z,pe)=>{let Ee=O(new H);return N(function(ot){let Ye=Ee.evaluate(ot);Ye!==F&&z.call(Z,Ye)},void 0,pe)}}Ze.chain=R;let F=Symbol("HaltChainable");class H{constructor(){this.steps=[]}map(O){return this.steps.push(O),this}forEach(O){return this.steps.push(q=>(O(q),q)),this}filter(O){return this.steps.push(q=>O(q)?q:F),this}reduce(O,q){let z=q;return this.steps.push(Z=>(z=O(z,Z),z)),this}latch(O=(q,z)=>q===z){let q=!0,z;return this.steps.push(Z=>{let pe=q||!O(Z,z);return q=!1,z=Z,pe?Z:F}),this}evaluate(O){for(let q of this.steps)if(O=q(O),O===F)break;return O}}function qe(N,O,q=z=>z){let z=(...ot)=>Ee.fire(q(...ot)),Z=()=>N.on(O,z),pe=()=>N.removeListener(O,z),Ee=new w({onWillAddFirstListener:Z,onDidRemoveLastListener:pe});return Ee.event}Ze.fromNodeEventEmitter=qe;function B(N,O,q=z=>z){let z=(...ot)=>Ee.fire(q(...ot)),Z=()=>N.addEventListener(O,z),pe=()=>N.removeEventListener(O,z),Ee=new w({onWillAddFirstListener:Z,onDidRemoveLastListener:pe});return Ee.event}Ze.fromDOMEventEmitter=B;function C(N,O){let q,z,Z=new Promise(pe=>{z=t(N)(pe),Um(z,O),q=()=>{tS(z,O)}});return Z.cancel=q,O&&Z.finally(()=>tS(z,O)),Z}Ze.toPromise=C;function A(N,O){return N(q=>O.fire(q))}Ze.forward=A;function ae(N,O,q){return O(q),N(z=>O(z))}Ze.runAndSubscribe=ae;class J{constructor(O,q){this._observable=O;this._counter=0;this._hasChanged=!1;let z={onWillAddFirstListener:()=>{O.addObserver(this),this._observable.reportChanges()},onDidRemoveLastListener:()=>{O.removeObserver(this)}};q||r(z),this.emitter=new w(z),q&&q.add(this.emitter)}beginUpdate(O){this._counter++}handlePossibleChange(O){}handleChange(O,q){this._hasChanged=!0}endUpdate(O){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function ge(N,O){return new J(N,O).emitter.event}Ze.fromObservable=ge;function Xe(N){return(O,q,z)=>{let Z=0,pe=!1,Ee={beginUpdate(){Z++},endUpdate(){Z--,Z===0&&(N.reportChanges(),pe&&(pe=!1,O.call(q)))},handlePossibleChange(){},handleChange(){pe=!0}};N.addObserver(Ee),N.reportChanges();let ot={dispose(){N.removeObserver(Ee)}};return Um(ot,z),ot}}Ze.fromObservableLight=Xe})(k||={});var Tm=class o{constructor(r){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${r}_${o._idPool++}`,o.all.add(this)}static{this.all=new Set}static{this._idPool=0}start(r){this._stopWatch=new qr,this.listenerCount=r}stop(){if(this._stopWatch){let r=this._stopWatch.elapsed();this.durations.push(r),this.elapsedOverall+=r,this.invocationCount+=1,this._stopWatch=void 0}}},eS=-1;var Cm=class o{constructor(r,e,t=(o._idPool++).toString(16).padStart(3,"0")){this._errorHandler=r;this.threshold=e;this.name=t;this._warnCountdown=0}static{this._idPool=1}dispose(){this._stacks?.clear()}check(r,e){let t=this.threshold;if(t<=0||e<t)return;this._stacks||(this._stacks=new Map);let n=this._stacks.get(r.value)||0;if(this._stacks.set(r.value,n+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=t*.5;let[i,s]=this.getMostFrequentStack(),a=`[${this.name}] potential listener LEAK detected, having ${e} listeners already. MOST frequent listener (${s}):`;console.warn(a),console.warn(i);let l=new Dm(a,i);this._errorHandler(l)}return()=>{let i=this._stacks.get(r.value)||0;this._stacks.set(r.value,i-1)}}getMostFrequentStack(){if(!this._stacks)return;let r,e=0;for(let[t,n]of this._stacks)(!r||e<n)&&(r=[t,n],e=n);return r}},El=class o{constructor(r){this.value=r}static create(){let r=new Error;return new o(r.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},Dm=class extends Error{constructor(r,e){super(r),this.name="ListenerLeakError",this.stack=e}},_m=class extends Error{constructor(r,e){super(r),this.name="ListenerRefusalError",this.stack=e}},vE=0,Ho=class{constructor(r){this.value=r;this.id=vE++}},yE=2,SE=(o,r)=>{if(o instanceof Ho)r(o);else for(let e=0;e<o.length;e++){let t=o[e];t&&r(t)}},w=class{constructor(r){this._size=0;this._options=r,this._leakageMon=eS>0||this._options?.leakWarningThreshold?new Cm(r?.onListenerError??Me,this._options?.leakWarningThreshold??eS):void 0,this._perfMon=this._options?._profName?new Tm(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(Zy){let r=this._listeners;queueMicrotask(()=>{SE(r,e=>e.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(r,e,t)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let l=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(l);let c=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],d=new _m(`${l}. HINT: Stack shows most frequent listener (${c[1]}-times)`,c[0]);return(this._options?.onListenerError||Me)(d),T.None}if(this._disposed)return T.None;e&&(r=r.bind(e));let n=new Ho(r),i,s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(n.stack=El.create(),i=this._leakageMon.check(n.stack,this._size+1)),Zy&&(n.stack=s??El.create()),this._listeners?this._listeners instanceof Ho?(this._deliveryQueue??=new km,this._listeners=[this._listeners,n]):this._listeners.push(n):(this._options?.onWillAddFirstListener?.(this),this._listeners=n,this._options?.onDidAddFirstListener?.(this)),this._options?.onDidAddListener?.(this),this._size++;let a=oe(()=>{i?.(),this._removeListener(n)});return Um(a,t),a},this._event}_removeListener(r){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let e=this._listeners,t=e.indexOf(r);if(t===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,e[t]=void 0;let n=this._deliveryQueue.current===this;if(this._size*yE<=e.length){let i=0;for(let s=0;s<e.length;s++)e[s]?e[i++]=e[s]:n&&i<this._deliveryQueue.end&&(this._deliveryQueue.end--,i<this._deliveryQueue.i&&this._deliveryQueue.i--);e.length=i}}_deliver(r,e){if(!r)return;let t=this._options?.onListenerError||Me;if(!t){r.value(e);return}try{r.value(e)}catch(n){t(n)}}_deliverQueue(r){let e=r.current._listeners;for(;r.i<r.end;)this._deliver(e[r.i++],r.value);r.reset()}fire(r){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof Ho)this._deliver(this._listeners,r);else{let e=this._deliveryQueue;e.enqueue(this,r,this._listeners.length),this._deliverQueue(e)}this._perfMon?.stop()}hasListeners(){return this._size>0}};var km=class{constructor(){this.i=-1;this.end=0}enqueue(r,e,t){this.i=0,this.end=t,this.current=r,this.value=e}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var ri=class extends w{constructor(e){super(e);this._isPaused=0;this._eventQueue=new jo;this._mergeFn=e?.merge}get isPaused(){return this._isPaused!==0}pause(){this._isPaused++}resume(){if(this._isPaused!==0&&--this._isPaused===0)if(this._mergeFn){if(this._eventQueue.size>0){let e=Array.from(this._eventQueue);this._eventQueue.clear(),super.fire(this._mergeFn(e))}}else for(;!this._isPaused&&this._eventQueue.size!==0;)super.fire(this._eventQueue.shift())}fire(e){this._size&&(this._isPaused!==0?this._eventQueue.push(e):super.fire(e))}};var fd=class{constructor(){this.hasListeners=!1;this.events=[];this.emitter=new w({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(r){let e={event:r,listener:null};return this.events.push(e),this.hasListeners&&this.hook(e),oe(hl(()=>{this.hasListeners&&this.unhook(e);let n=this.events.indexOf(e);this.events.splice(n,1)}))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach(r=>this.hook(r))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach(r=>this.unhook(r))}hook(r){r.listener=r.event(e=>this.emitter.fire(e))}unhook(r){r.listener?.dispose(),r.listener=null}dispose(){this.emitter.dispose();for(let r of this.events)r.listener?.dispose();this.events=[]}};var wl=class{constructor(){this.listening=!1;this.inputEvent=k.None;this.inputEventListener=T.None;this.emitter=new w({onDidAddFirstListener:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onDidRemoveLastListener:()=>{this.listening=!1,this.inputEventListener.dispose()}});this.event=this.emitter.event}set input(r){this.inputEvent=r,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=r(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}};function Um(o,r){r instanceof se?r.add(o):Array.isArray(r)&&r.push(o)}function tS(o,r){if(r instanceof se)r.delete(o);else if(Array.isArray(r)){let e=r.indexOf(o);e!==-1&&r.splice(e,1)}o.dispose()}var rS=Object.freeze(function(o,r){let e=setTimeout(o.bind(r),0);return{dispose(){clearTimeout(e)}}}),Y;(t=>{function o(n){return n===t.None||n===t.Cancelled||n instanceof Jo?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}t.isCancellationToken=o,t.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:k.None}),t.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:rS})})(Y||={});var Jo=class{constructor(){this._isCancelled=!1;this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?rS:(this._emitter||(this._emitter=new w),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},mt=class{constructor(r){this._token=void 0;this._parentListener=void 0;this._parentListener=r&&r.onCancellationRequested(this.cancel,this)}get token(){return this._token||(this._token=new Jo),this._token}cancel(){this._token?this._token instanceof Jo&&this._token.cancel():this._token=Y.Cancelled}dispose(r=!1){r&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof Jo&&this._token.dispose():this._token=Y.None}};function IE(o){return o}var md=class{constructor(r,e){this.lastCache=void 0;this.lastArgKey=void 0;typeof r=="function"?(this._fn=r,this._computeKey=IE):(this._fn=e,this._computeKey=r.getCacheKey)}get(r){let e=this._computeKey(r);return this.lastArgKey!==e&&(this.lastArgKey=e,this.lastCache=this._fn(r)),this.lastCache}};var cr=class{constructor(r){this.executor=r;this._state=0}get hasValue(){return this._state===2}get value(){if(this._state===0){this._state=1;try{this._value=this.executor()}catch(r){this._error=r}finally{this._state=2}}else if(this._state===1)throw new Error("Cannot read the value of a lazy that is being initialized");if(this._error)throw this._error;return this._value}get rawValue(){return this._value}};function aS(o){return!o||typeof o!="string"?!0:o.trim().length===0}var bE=/{([^}]+)}/g;function Dr(o,r){return Object.keys(r).length===0?o:o.replace(bE,(e,t)=>r[t]??e)}function zr(o){return o.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&")}function lS(o,r=" "){let e=gd(o,r);return Qo(e,r)}function gd(o,r){if(!o||!r)return o;let e=r.length,t=0;if(e===1){let n=r.charCodeAt(0);for(;t<o.length&&o.charCodeAt(t)===n;)t++}else for(;o.startsWith(r,t);)t+=e;return o.substring(t)}function Qo(o,r){if(!o||!r)return o;let e=r.length,t=o.length;if(e===1){let i=t,s=r.charCodeAt(0);for(;i>0&&o.charCodeAt(i-1)===s;)i--;return o.substring(0,i)}let n=t;for(;n>0&&o.endsWith(r,n);)n-=e;return o.substring(0,n)}function zi(o,r){return o<r?-1:o>r?1:0}function hd(o,r,e=0,t=o.length,n=0,i=r.length){for(;e<t&&n<i;e++,n++){let l=o.charCodeAt(e),c=r.charCodeAt(n);if(l<c)return-1;if(l>c)return 1}let s=t-e,a=i-n;return s<a?-1:s>a?1:0}function Xo(o,r){return Ki(o,r,0,o.length,0,r.length)}function Ki(o,r,e=0,t=o.length,n=0,i=r.length){for(;e<t&&n<i;e++,n++){let l=o.charCodeAt(e),c=r.charCodeAt(n);if(l===c)continue;if(l>=128||c>=128)return hd(o.toLowerCase(),r.toLowerCase(),e,t,n,i);nS(l)&&(l-=32),nS(c)&&(c-=32);let d=l-c;if(d!==0)return d}let s=t-e,a=i-n;return s<a?-1:s>a?1:0}function nS(o){return o>=97&&o<=122}function Lm(o){return o>=65&&o<=90}function yr(o,r){return o.length===r.length&&Ki(o,r)===0}function ji(o,r){let e=r.length;return e<=o.length&&Ki(o,r,0,e)===0}function cS(o,r){let e=o.length,t=e-r.length;return t>=0&&Ki(o,r,t,e)===0}function dS(o){return 55296<=o&&o<=56319}function Mm(o){return 56320<=o&&o<=57343}function uS(o,r){return(o-55296<<10)+(r-56320)+65536}var xE=/(?:\x1b\[|\x9b)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~]/,EE=/(?:\x1b\]|\x9d).*?(?:\x1b\\|\x07|\x9c)/,wE=/\x1b(?:[ #%\(\)\*\+\-\.\/]?[a-zA-Z0-9\|}~@])/,TD=new RegExp("(?:"+[xE.source,EE.source,wE.source].join("|")+")","g");var CD=String.fromCharCode(65279);function Pl(o){return o.charAt(0).toUpperCase()+o.slice(1)}var iS=class o{static{this._INSTANCE=null}static getInstance(){return o._INSTANCE||(o._INSTANCE=new o),o._INSTANCE}constructor(){this._data=PE()}getGraphemeBreakType(r){if(r<32)return r===10?3:r===13?2:4;if(r<127)return 0;let e=this._data,t=e.length/3,n=1;for(;n<=t;)if(r<e[3*n])n=2*n;else if(r>e[3*n+1])n=2*n+1;else return e[3*n+2];return 0}};function PE(){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 oS=class o{constructor(r){this.confusableDictionary=r}static{this.ambiguousCharacterData=new cr(()=>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,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,1523,96,8242,96,1370,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,118002,50,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,118003,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,118004,52,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,118005,53,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,118006,54,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,118007,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,118008,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,118009,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,117974,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,117975,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,71913,67,71922,67,65315,67,8557,67,8450,67,8493,67,117976,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,117977,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,117978,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,117979,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,117980,71,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,117981,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,117983,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,117984,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,118001,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,117982,108,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,117985,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,117986,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,117987,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,118000,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,117988,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,117989,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,117990,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,117991,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,117992,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,117993,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,117994,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,117995,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,71910,87,71919,87,117996,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,117997,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,117998,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,71909,90,66293,90,65338,90,8484,90,8488,90,117999,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,65283,35,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,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,8218,44,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,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"cs":[65374,126,8218,44,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,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"de":[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,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"es":[8211,45,65374,126,8218,44,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,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"fr":[65374,126,8218,44,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,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"it":[160,32,8211,45,65374,126,8218,44,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,65292,44,65297,49,65307,59,65311,63],"ja":[8211,45,8218,44,65281,33,8216,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,65292,44,65297,49,65307,59],"ko":[8211,45,65374,126,8218,44,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,65292,44,65297,49,65307,59,65311,63],"pl":[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,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"pt-BR":[65374,126,8218,44,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,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"qps-ploc":[160,32,8211,45,65374,126,8218,44,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,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"ru":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"tr":[160,32,8211,45,65374,126,8218,44,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,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"zh-hans":[160,32,65374,126,8218,44,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,65297,49],"zh-hant":[8211,45,65374,126,8218,44,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]}'))}static{this.cache=new md(r=>{let e=r.split(",");function t(u){let p=new Map;for(let m=0;m<u.length;m+=2)p.set(u[m],u[m+1]);return p}function n(u,p){let m=new Map(u);for(let[h,v]of p)m.set(h,v);return m}function i(u,p){if(!u)return p;let m=new Map;for(let[h,v]of u)p.has(h)&&m.set(h,v);return m}let s=this.ambiguousCharacterData.value,a=e.filter(u=>!u.startsWith("_")&&Object.hasOwn(s,u));a.length===0&&(a=["_default"]);let l;for(let u of a){let p=t(s[u]);l=i(l,p)}let c=t(s._common),d=n(c,l);return new o(d)})}static getInstance(r){return o.cache.get(Array.from(r).join(","))}static{this._locales=new cr(()=>Object.keys(o.ambiguousCharacterData.value).filter(r=>!r.startsWith("_")))}static getLocales(){return o._locales.value}isAmbiguous(r){return this.confusableDictionary.has(r)}containsAmbiguousCharacter(r){for(let e=0;e<r.length;e++){let t=r.codePointAt(e);if(typeof t=="number"&&this.isAmbiguous(t))return!0}return!1}getPrimaryConfusable(r){return this.confusableDictionary.get(r)}getConfusableCodePoints(){return new Set(this.confusableDictionary.keys())}},sS=class o{static getRawData(){return JSON.parse('{"_common":[11,12,13,127,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,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,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],"cs":[173,8203,12288],"de":[173,8203,12288],"es":[8203,12288],"fr":[173,8203,12288],"it":[160,173,12288],"ja":[173],"ko":[173,12288],"pl":[173,8203,12288],"pt-BR":[173,8203,12288],"qps-ploc":[160,173,8203,12288],"ru":[173,12288],"tr":[160,173,8203,12288],"zh-hans":[160,173,8203,12288],"zh-hant":[173,12288]}')}static{this._data=void 0}static getData(){return this._data||(this._data=new Set([...Object.values(o.getRawData())].flat())),this._data}static isInvisibleCharacter(r){return o.getData().has(r)}static containsInvisibleCharacter(r){for(let e=0;e<r.length;e++){let t=r.codePointAt(e);if(typeof t=="number"&&(o.isInvisibleCharacter(t)||t===32))return!0}return!1}static get codePoints(){return o.getData()}};var Hi,Am=globalThis.vscode;if(typeof Am<"u"&&typeof Am.process<"u"){let o=Am.process;Hi={get platform(){return o.platform},get arch(){return o.arch},get env(){return o.env},cwd(){return o.cwd()}}}else typeof process<"u"&&typeof process?.versions?.node=="string"?Hi={get platform(){return process.platform},get arch(){return process.arch},get env(){return process.env},cwd(){return process.env.VSCODE_CWD||process.cwd()}}:Hi={get platform(){return he?"win32":Gt?"darwin":"linux"},get arch(){},get env(){return{}},cwd(){return"/"}};var Yo=Hi.cwd,Fe=Hi.env,vd=Hi.platform,yd=Hi.arch;var RE=65,TE=97,CE=90,DE=122,Ji=46,qt=47,Sr=92,An=58,_E=63,Sd=class extends Error{constructor(r,e,t){let n;typeof e=="string"&&e.indexOf("not ")===0?(n="must not be",e=e.replace(/^not /,"")):n="must be";let i=r.indexOf(".")!==-1?"property":"argument",s=`The "${r}" ${i} ${n} of type ${e}`;s+=`. Received type ${typeof t}`,super(s),this.code="ERR_INVALID_ARG_TYPE"}};function kE(o,r){if(o===null||typeof o!="object")throw new Sd(r,"Object",o)}function yt(o,r){if(typeof o!="string")throw new Sd(r,"string",o)}var Ir=vd==="win32";function be(o){return o===qt||o===Sr}function Fm(o){return o===qt}function Fn(o){return o>=RE&&o<=CE||o>=TE&&o<=DE}function Id(o,r,e,t){let n="",i=0,s=-1,a=0,l=0;for(let c=0;c<=o.length;++c){if(c<o.length)l=o.charCodeAt(c);else{if(t(l))break;l=qt}if(t(l)){if(!(s===c-1||a===1))if(a===2){if(n.length<2||i!==2||n.charCodeAt(n.length-1)!==Ji||n.charCodeAt(n.length-2)!==Ji){if(n.length>2){let d=n.lastIndexOf(e);d===-1?(n="",i=0):(n=n.slice(0,d),i=n.length-1-n.lastIndexOf(e)),s=c,a=0;continue}else if(n.length!==0){n="",i=0,s=c,a=0;continue}}r&&(n+=n.length>0?`${e}..`:"..",i=2)}else n.length>0?n+=`${e}${o.slice(s+1,c)}`:n=o.slice(s+1,c),i=c-s-1;s=c,a=0}else l===Ji&&a!==-1?++a:a=-1}return n}function UE(o){return o?`${o[0]==="."?"":"."}${o}`:""}function fS(o,r){kE(r,"pathObject");let e=r.dir||r.root,t=r.base||`${r.name||""}${UE(r.ext)}`;return e?e===r.root?`${e}${t}`:`${e}${o}${t}`:t}var St={resolve(...o){let r="",e="",t=!1;for(let n=o.length-1;n>=-1;n--){let i;if(n>=0){if(i=o[n],yt(i,`paths[${n}]`),i.length===0)continue}else r.length===0?i=Yo():(i=Fe[`=${r}`]||Yo(),(i===void 0||i.slice(0,2).toLowerCase()!==r.toLowerCase()&&i.charCodeAt(2)===Sr)&&(i=`${r}\\`));let s=i.length,a=0,l="",c=!1,d=i.charCodeAt(0);if(s===1)be(d)&&(a=1,c=!0);else if(be(d))if(c=!0,be(i.charCodeAt(1))){let u=2,p=u;for(;u<s&&!be(i.charCodeAt(u));)u++;if(u<s&&u!==p){let m=i.slice(p,u);for(p=u;u<s&&be(i.charCodeAt(u));)u++;if(u<s&&u!==p){for(p=u;u<s&&!be(i.charCodeAt(u));)u++;(u===s||u!==p)&&(l=`\\\\${m}\\${i.slice(p,u)}`,a=u)}}}else a=1;else Fn(d)&&i.charCodeAt(1)===An&&(l=i.slice(0,2),a=2,s>2&&be(i.charCodeAt(2))&&(c=!0,a=3));if(l.length>0)if(r.length>0){if(l.toLowerCase()!==r.toLowerCase())continue}else r=l;if(t){if(r.length>0)break}else if(e=`${i.slice(a)}\\${e}`,t=c,c&&r.length>0)break}return e=Id(e,!t,"\\",be),t?`${r}\\${e}`:`${r}${e}`||"."},normalize(o){yt(o,"path");let r=o.length;if(r===0)return".";let e=0,t,n=!1,i=o.charCodeAt(0);if(r===1)return Fm(i)?"\\":o;if(be(i))if(n=!0,be(o.charCodeAt(1))){let a=2,l=a;for(;a<r&&!be(o.charCodeAt(a));)a++;if(a<r&&a!==l){let c=o.slice(l,a);for(l=a;a<r&&be(o.charCodeAt(a));)a++;if(a<r&&a!==l){for(l=a;a<r&&!be(o.charCodeAt(a));)a++;if(a===r)return`\\\\${c}\\${o.slice(l)}\\`;a!==l&&(t=`\\\\${c}\\${o.slice(l,a)}`,e=a)}}}else e=1;else Fn(i)&&o.charCodeAt(1)===An&&(t=o.slice(0,2),e=2,r>2&&be(o.charCodeAt(2))&&(n=!0,e=3));let s=e<r?Id(o.slice(e),!n,"\\",be):"";if(s.length===0&&!n&&(s="."),s.length>0&&be(o.charCodeAt(r-1))&&(s+="\\"),!n&&t===void 0&&o.includes(":")){if(s.length>=2&&Fn(s.charCodeAt(0))&&s.charCodeAt(1)===An)return`.\\${s}`;let a=o.indexOf(":");do if(a===r-1||be(o.charCodeAt(a+1)))return`.\\${s}`;while((a=o.indexOf(":",a+1))!==-1)}return t===void 0?n?`\\${s}`:s:n?`${t}\\${s}`:`${t}${s}`},isAbsolute(o){yt(o,"path");let r=o.length;if(r===0)return!1;let e=o.charCodeAt(0);return be(e)||r>2&&Fn(e)&&o.charCodeAt(1)===An&&be(o.charCodeAt(2))},join(...o){if(o.length===0)return".";let r,e;for(let i=0;i<o.length;++i){let s=o[i];yt(s,"path"),s.length>0&&(r===void 0?r=e=s:r+=`\\${s}`)}if(r===void 0)return".";let t=!0,n=0;if(typeof e=="string"&&be(e.charCodeAt(0))){++n;let i=e.length;i>1&&be(e.charCodeAt(1))&&(++n,i>2&&(be(e.charCodeAt(2))?++n:t=!1))}if(t){for(;n<r.length&&be(r.charCodeAt(n));)n++;n>=2&&(r=`\\${r.slice(n)}`)}return St.normalize(r)},relative(o,r){if(yt(o,"from"),yt(r,"to"),o===r)return"";let e=St.resolve(o),t=St.resolve(r);if(e===t||(o=e.toLowerCase(),r=t.toLowerCase(),o===r))return"";if(e.length!==o.length||t.length!==r.length){let h=e.split("\\"),v=t.split("\\");h[h.length-1]===""&&h.pop(),v[v.length-1]===""&&v.pop();let y=h.length,x=v.length,E=y<x?y:x,R;for(R=0;R<E&&h[R].toLowerCase()===v[R].toLowerCase();R++);return R===0?t:R===E?x>E?v.slice(R).join("\\"):y>E?"..\\".repeat(y-1-R)+"..":"":"..\\".repeat(y-R)+v.slice(R).join("\\")}let n=0;for(;n<o.length&&o.charCodeAt(n)===Sr;)n++;let i=o.length;for(;i-1>n&&o.charCodeAt(i-1)===Sr;)i--;let s=i-n,a=0;for(;a<r.length&&r.charCodeAt(a)===Sr;)a++;let l=r.length;for(;l-1>a&&r.charCodeAt(l-1)===Sr;)l--;let c=l-a,d=s<c?s:c,u=-1,p=0;for(;p<d;p++){let h=o.charCodeAt(n+p);if(h!==r.charCodeAt(a+p))break;h===Sr&&(u=p)}if(p!==d){if(u===-1)return t}else{if(c>d){if(r.charCodeAt(a+p)===Sr)return t.slice(a+p+1);if(p===2)return t.slice(a+p)}s>d&&(o.charCodeAt(n+p)===Sr?u=p:p===2&&(u=3)),u===-1&&(u=0)}let m="";for(p=n+u+1;p<=i;++p)(p===i||o.charCodeAt(p)===Sr)&&(m+=m.length===0?"..":"\\..");return a+=u,m.length>0?`${m}${t.slice(a,l)}`:(t.charCodeAt(a)===Sr&&++a,t.slice(a,l))},toNamespacedPath(o){if(typeof o!="string"||o.length===0)return o;let r=St.resolve(o);if(r.length<=2)return o;if(r.charCodeAt(0)===Sr){if(r.charCodeAt(1)===Sr){let e=r.charCodeAt(2);if(e!==_E&&e!==Ji)return`\\\\?\\UNC\\${r.slice(2)}`}}else if(Fn(r.charCodeAt(0))&&r.charCodeAt(1)===An&&r.charCodeAt(2)===Sr)return`\\\\?\\${r}`;return r},dirname(o){yt(o,"path");let r=o.length;if(r===0)return".";let e=-1,t=0,n=o.charCodeAt(0);if(r===1)return be(n)?o:".";if(be(n)){if(e=t=1,be(o.charCodeAt(1))){let a=2,l=a;for(;a<r&&!be(o.charCodeAt(a));)a++;if(a<r&&a!==l){for(l=a;a<r&&be(o.charCodeAt(a));)a++;if(a<r&&a!==l){for(l=a;a<r&&!be(o.charCodeAt(a));)a++;if(a===r)return o;a!==l&&(e=t=a+1)}}}}else Fn(n)&&o.charCodeAt(1)===An&&(e=r>2&&be(o.charCodeAt(2))?3:2,t=e);let i=-1,s=!0;for(let a=r-1;a>=t;--a)if(be(o.charCodeAt(a))){if(!s){i=a;break}}else s=!1;if(i===-1){if(e===-1)return".";i=e}return o.slice(0,i)},basename(o,r){r!==void 0&&yt(r,"suffix"),yt(o,"path");let e=0,t=-1,n=!0,i;if(o.length>=2&&Fn(o.charCodeAt(0))&&o.charCodeAt(1)===An&&(e=2),r!==void 0&&r.length>0&&r.length<=o.length){if(r===o)return"";let s=r.length-1,a=-1;for(i=o.length-1;i>=e;--i){let l=o.charCodeAt(i);if(be(l)){if(!n){e=i+1;break}}else a===-1&&(n=!1,a=i+1),s>=0&&(l===r.charCodeAt(s)?--s===-1&&(t=i):(s=-1,t=a))}return e===t?t=a:t===-1&&(t=o.length),o.slice(e,t)}for(i=o.length-1;i>=e;--i)if(be(o.charCodeAt(i))){if(!n){e=i+1;break}}else t===-1&&(n=!1,t=i+1);return t===-1?"":o.slice(e,t)},extname(o){yt(o,"path");let r=0,e=-1,t=0,n=-1,i=!0,s=0;o.length>=2&&o.charCodeAt(1)===An&&Fn(o.charCodeAt(0))&&(r=t=2);for(let a=o.length-1;a>=r;--a){let l=o.charCodeAt(a);if(be(l)){if(!i){t=a+1;break}continue}n===-1&&(i=!1,n=a+1),l===Ji?e===-1?e=a:s!==1&&(s=1):e!==-1&&(s=-1)}return e===-1||n===-1||s===0||s===1&&e===n-1&&e===t+1?"":o.slice(e,n)},format:fS.bind(null,"\\"),parse(o){yt(o,"path");let r={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return r;let e=o.length,t=0,n=o.charCodeAt(0);if(e===1)return be(n)?(r.root=r.dir=o,r):(r.base=r.name=o,r);if(be(n)){if(t=1,be(o.charCodeAt(1))){let u=2,p=u;for(;u<e&&!be(o.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&be(o.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&!be(o.charCodeAt(u));)u++;u===e?t=u:u!==p&&(t=u+1)}}}}else if(Fn(n)&&o.charCodeAt(1)===An){if(e<=2)return r.root=r.dir=o,r;if(t=2,be(o.charCodeAt(2))){if(e===3)return r.root=r.dir=o,r;t=3}}t>0&&(r.root=o.slice(0,t));let i=-1,s=t,a=-1,l=!0,c=o.length-1,d=0;for(;c>=t;--c){if(n=o.charCodeAt(c),be(n)){if(!l){s=c+1;break}continue}a===-1&&(l=!1,a=c+1),n===Ji?i===-1?i=c:d!==1&&(d=1):i!==-1&&(d=-1)}return a!==-1&&(i===-1||d===0||d===1&&i===a-1&&i===s+1?r.base=r.name=o.slice(s,a):(r.name=o.slice(s,i),r.base=o.slice(s,a),r.ext=o.slice(i,a))),s>0&&s!==t?r.dir=o.slice(0,s-1):r.dir=r.root,r},sep:"\\",delimiter:";",win32:null,posix:null},LE=(()=>{if(Ir){let o=/\\/g;return()=>{let r=Yo().replace(o,"/");return r.slice(r.indexOf("/"))}}return()=>Yo()})(),Te={resolve(...o){let r="",e=!1;for(let t=o.length-1;t>=0&&!e;t--){let n=o[t];yt(n,`paths[${t}]`),n.length!==0&&(r=`${n}/${r}`,e=n.charCodeAt(0)===qt)}if(!e){let t=LE();r=`${t}/${r}`,e=t.charCodeAt(0)===qt}return r=Id(r,!e,"/",Fm),e?`/${r}`:r.length>0?r:"."},normalize(o){if(yt(o,"path"),o.length===0)return".";let r=o.charCodeAt(0)===qt,e=o.charCodeAt(o.length-1)===qt;return o=Id(o,!r,"/",Fm),o.length===0?r?"/":e?"./":".":(e&&(o+="/"),r?`/${o}`:o)},isAbsolute(o){return yt(o,"path"),o.length>0&&o.charCodeAt(0)===qt},join(...o){if(o.length===0)return".";let r=[];for(let e=0;e<o.length;++e){let t=o[e];yt(t,"path"),t.length>0&&r.push(t)}return r.length===0?".":Te.normalize(r.join("/"))},relative(o,r){if(yt(o,"from"),yt(r,"to"),o===r||(o=Te.resolve(o),r=Te.resolve(r),o===r))return"";let e=1,t=o.length,n=t-e,i=1,s=r.length-i,a=n<s?n:s,l=-1,c=0;for(;c<a;c++){let u=o.charCodeAt(e+c);if(u!==r.charCodeAt(i+c))break;u===qt&&(l=c)}if(c===a)if(s>a){if(r.charCodeAt(i+c)===qt)return r.slice(i+c+1);if(c===0)return r.slice(i+c)}else n>a&&(o.charCodeAt(e+c)===qt?l=c:c===0&&(l=0));let d="";for(c=e+l+1;c<=t;++c)(c===t||o.charCodeAt(c)===qt)&&(d+=d.length===0?"..":"/..");return`${d}${r.slice(i+l)}`},toNamespacedPath(o){return o},dirname(o){if(yt(o,"path"),o.length===0)return".";let r=o.charCodeAt(0)===qt,e=-1,t=!0;for(let n=o.length-1;n>=1;--n)if(o.charCodeAt(n)===qt){if(!t){e=n;break}}else t=!1;return e===-1?r?"/":".":r&&e===1?"//":o.slice(0,e)},basename(o,r){r!==void 0&&yt(r,"suffix"),yt(o,"path");let e=0,t=-1,n=!0,i;if(r!==void 0&&r.length>0&&r.length<=o.length){if(r===o)return"";let s=r.length-1,a=-1;for(i=o.length-1;i>=0;--i){let l=o.charCodeAt(i);if(l===qt){if(!n){e=i+1;break}}else a===-1&&(n=!1,a=i+1),s>=0&&(l===r.charCodeAt(s)?--s===-1&&(t=i):(s=-1,t=a))}return e===t?t=a:t===-1&&(t=o.length),o.slice(e,t)}for(i=o.length-1;i>=0;--i)if(o.charCodeAt(i)===qt){if(!n){e=i+1;break}}else t===-1&&(n=!1,t=i+1);return t===-1?"":o.slice(e,t)},extname(o){yt(o,"path");let r=-1,e=0,t=-1,n=!0,i=0;for(let s=o.length-1;s>=0;--s){let a=o[s];if(a==="/"){if(!n){e=s+1;break}continue}t===-1&&(n=!1,t=s+1),a==="."?r===-1?r=s:i!==1&&(i=1):r!==-1&&(i=-1)}return r===-1||t===-1||i===0||i===1&&r===t-1&&r===e+1?"":o.slice(r,t)},format:fS.bind(null,"/"),parse(o){yt(o,"path");let r={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return r;let e=o.charCodeAt(0)===qt,t;e?(r.root="/",t=1):t=0;let n=-1,i=0,s=-1,a=!0,l=o.length-1,c=0;for(;l>=t;--l){let d=o.charCodeAt(l);if(d===qt){if(!a){i=l+1;break}continue}s===-1&&(a=!1,s=l+1),d===Ji?n===-1?n=l:c!==1&&(c=1):n!==-1&&(c=-1)}if(s!==-1){let d=i===0&&e?1:i;n===-1||c===0||c===1&&n===s-1&&n===i+1?r.base=r.name=o.slice(d,s):(r.name=o.slice(d,n),r.base=o.slice(d,s),r.ext=o.slice(n,s))}return i>0?r.dir=o.slice(0,i-1):e&&(r.dir="/"),r},sep:"/",delimiter:":",win32:null,posix:null};Te.win32=St.win32=St;Te.posix=St.posix=Te;var br=Ir?St.normalize:Te.normalize,Zo=Ir?St.isAbsolute:Te.isAbsolute,G=Ir?St.join:Te.join,en=Ir?St.resolve:Te.resolve,bd=Ir?St.relative:Te.relative,$e=Ir?St.dirname:Te.dirname,lt=Ir?St.basename:Te.basename,xd=Ir?St.extname:Te.extname,UD=Ir?St.format:Te.format,LD=Ir?St.parse:Te.parse,MD=Ir?St.toNamespacedPath:Te.toNamespacedPath,Ut=Ir?St.sep:Te.sep,ME=Ir?St.delimiter:Te.delimiter;var AE=/^\w[\w\d+.-]*$/,FE=/^\//,OE=/^\/\//;function NE(o,r){if(!o.scheme&&r)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${o.authority}", path: "${o.path}", query: "${o.query}", fragment: "${o.fragment}"}`);if(o.scheme&&!AE.test(o.scheme)){let e=[...o.scheme.matchAll(/[^\w\d+.-]/gu)],t=e.length>0?` Found '${e[0][0]}' at index ${e[0].index} (${e.length} total)`:"";throw new Error(`[UriError]: Scheme contains illegal characters.${t} (len:${o.scheme.length})`)}if(o.path){if(o.authority){if(!FE.test(o.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(OE.test(o.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}function VE(o,r){return!o&&!r?"file":o}function WE(o,r){switch(o){case"https":case"http":case"file":r?r[0]!==tn&&(r=tn+r):r=tn;break}return r}var rt="",tn="/",BE=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,P=class o{static isUri(r){return r instanceof o?!0:!r||typeof r!="object"?!1:typeof r.authority=="string"&&typeof r.fragment=="string"&&typeof r.path=="string"&&typeof r.query=="string"&&typeof r.scheme=="string"&&typeof r.fsPath=="string"&&typeof r.with=="function"&&typeof r.toString=="function"}constructor(r,e,t,n,i,s=!1){typeof r=="object"?(this.scheme=r.scheme||rt,this.authority=r.authority||rt,this.path=r.path||rt,this.query=r.query||rt,this.fragment=r.fragment||rt):(this.scheme=VE(r,s),this.authority=e||rt,this.path=WE(this.scheme,t||rt),this.query=n||rt,this.fragment=i||rt,NE(this,s))}get fsPath(){return Tl(this,!1)}with(r){if(!r)return this;let{scheme:e,authority:t,path:n,query:i,fragment:s}=r;return e===void 0?e=this.scheme:e===null&&(e=rt),t===void 0?t=this.authority:t===null&&(t=rt),n===void 0?n=this.path:n===null&&(n=rt),i===void 0?i=this.query:i===null&&(i=rt),s===void 0?s=this.fragment:s===null&&(s=rt),e===this.scheme&&t===this.authority&&n===this.path&&i===this.query&&s===this.fragment?this:new oi(e,t,n,i,s)}static parse(r,e=!1){let t=BE.exec(r);return t?new oi(t[2]||rt,Ed(t[4]||rt),Ed(t[5]||rt),Ed(t[7]||rt),Ed(t[9]||rt),e):new oi(rt,rt,rt,rt,rt)}static file(r){let e=rt;if(he&&(r=r.replace(/\\/g,tn)),r[0]===tn&&r[1]===tn){let t=r.indexOf(tn,2);t===-1?(e=r.substring(2),r=tn):(e=r.substring(2,t),r=r.substring(t)||tn)}return new oi("file",e,r,rt,rt)}static from(r,e){return new oi(r.scheme,r.authority,r.path,r.query,r.fragment,e)}static joinPath(r,...e){if(!r.path)throw new Error("[UriError]: cannot call joinPath on URI without path");let t;return he&&r.scheme==="file"?t=o.file(St.join(Tl(r,!0),...e)).path:t=Te.join(r.path,...e),r.with({path:t})}toString(r=!1){return Om(this,r)}toJSON(){return this}static revive(r){if(r){if(r instanceof o)return r;{let e=new oi(r);return e._formatted=r.external??null,e._fsPath=r._sep===vS?r.fsPath??null:null,e}}else return r}[Symbol.for("debug.description")](){return`URI(${this.toString()})`}};var vS=he?1:void 0,oi=class extends P{constructor(){super(...arguments);this._formatted=null;this._fsPath=null}get fsPath(){return this._fsPath||(this._fsPath=Tl(this,!1)),this._fsPath}toString(e=!1){return e?Om(this,!0):(this._formatted||(this._formatted=Om(this,!1)),this._formatted)}toJSON(){let e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=vS),this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),this.query&&(e.query=this.query),this.fragment&&(e.fragment=this.fragment),e}},yS={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function mS(o,r,e){let t,n=-1;for(let i=0;i<o.length;i++){let s=o.charCodeAt(i);if(s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||s===45||s===46||s===95||s===126||r&&s===47||e&&s===91||e&&s===93||e&&s===58)n!==-1&&(t+=encodeURIComponent(o.substring(n,i)),n=-1),t!==void 0&&(t+=o.charAt(i));else{t===void 0&&(t=o.substr(0,i));let a=yS[s];a!==void 0?(n!==-1&&(t+=encodeURIComponent(o.substring(n,i)),n=-1),t+=a):n===-1&&(n=i)}}return n!==-1&&(t+=encodeURIComponent(o.substring(n))),t!==void 0?t:o}function $E(o){let r;for(let e=0;e<o.length;e++){let t=o.charCodeAt(e);t===35||t===63?(r===void 0&&(r=o.substr(0,e)),r+=yS[t]):r!==void 0&&(r+=o[e])}return r!==void 0?r:o}function Tl(o,r){let e;return o.authority&&o.path.length>1&&o.scheme==="file"?e=`//${o.authority}${o.path}`:o.path.charCodeAt(0)===47&&(o.path.charCodeAt(1)>=65&&o.path.charCodeAt(1)<=90||o.path.charCodeAt(1)>=97&&o.path.charCodeAt(1)<=122)&&o.path.charCodeAt(2)===58?r?e=o.path.substr(1):e=o.path[1].toLowerCase()+o.path.substr(2):e=o.path,he&&(e=e.replace(/\//g,"\\")),e}function Om(o,r){let e=r?$E:mS,t="",{scheme:n,authority:i,path:s,query:a,fragment:l}=o;if(n&&(t+=n,t+=":"),(i||n==="file")&&(t+=tn,t+=tn),i){let c=i.indexOf("@");if(c!==-1){let d=i.substr(0,c);i=i.substr(c+1),c=d.lastIndexOf(":"),c===-1?t+=e(d,!1,!1):(t+=e(d.substr(0,c),!1,!1),t+=":",t+=e(d.substr(c+1),!1,!0)),t+="@"}i=i.toLowerCase(),c=i.lastIndexOf(":"),c===-1?t+=e(i,!1,!0):(t+=e(i.substr(0,c),!1,!0),t+=i.substr(c))}if(s){if(s.length>=3&&s.charCodeAt(0)===47&&s.charCodeAt(2)===58){let c=s.charCodeAt(1);c>=65&&c<=90&&(s=`/${String.fromCharCode(c+32)}:${s.substr(3)}`)}else if(s.length>=2&&s.charCodeAt(1)===58){let c=s.charCodeAt(0);c>=65&&c<=90&&(s=`${String.fromCharCode(c+32)}:${s.substr(2)}`)}t+=e(s,!0,!1)}return a&&(t+="?",t+=e(a,!1,!1)),l&&(t+="#",t+=r?l:mS(l,!1,!1)),t}function SS(o){try{return decodeURIComponent(o)}catch{return o.length>3?o.substr(0,3)+SS(o.substr(3)):o}}var gS=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function Ed(o){return o.match(gS)?o.replace(gS,r=>SS(r)):o}var re;(le=>(le.inMemory="inmemory",le.vscode="vscode",le.internal="private",le.walkThrough="walkThrough",le.walkThroughSnippet="walkThroughSnippet",le.http="http",le.https="https",le.file="file",le.mailto="mailto",le.untitled="untitled",le.data="data",le.command="command",le.vscodeRemote="vscode-remote",le.vscodeRemoteResource="vscode-remote-resource",le.vscodeManagedRemoteResource="vscode-managed-remote-resource",le.vscodeUserData="vscode-userdata",le.vscodeCustomEditor="vscode-custom-editor",le.vscodeNotebookCell="vscode-notebook-cell",le.vscodeNotebookCellMetadata="vscode-notebook-cell-metadata",le.vscodeNotebookCellMetadataDiff="vscode-notebook-cell-metadata-diff",le.vscodeNotebookCellOutput="vscode-notebook-cell-output",le.vscodeNotebookCellOutputDiff="vscode-notebook-cell-output-diff",le.vscodeNotebookMetadata="vscode-notebook-metadata",le.vscodeInteractiveInput="vscode-interactive-input",le.vscodeSettings="vscode-settings",le.vscodeWorkspaceTrust="vscode-workspace-trust",le.vscodeTerminal="vscode-terminal",le.vscodeChatCodeBlock="vscode-chat-code-block",le.vscodeChatCodeCompareBlock="vscode-chat-code-compare-block",le.vscodeChatEditor="vscode-chat-editor",le.vscodeChatInput="chatSessionInput",le.vscodeLocalChatSession="vscode-chat-session",le.webviewPanel="webview-panel",le.vscodeWebview="vscode-webview",le.vscodeBrowser="vscode-browser",le.extension="extension",le.vscodeFileResource="vscode-file",le.tmp="tmp",le.vsls="vsls",le.vscodeSourceControl="vscode-scm",le.commentsInput="comment",le.codeSetting="code-setting",le.outputChannel="output",le.accessibleView="accessible-view",le.chatEditingSnapshotScheme="chat-editing-snapshot-text-model",le.chatEditingModel="chat-editing-text-model",le.copilotPr="copilot-pr"))(re||={});var GE="tkn",Nm=class{constructor(){this._hosts=Object.create(null);this._ports=Object.create(null);this._connectionTokens=Object.create(null);this._preferredWebSchema="http";this._delegate=null;this._serverRootPath="/"}setPreferredWebSchema(r){this._preferredWebSchema=r}setDelegate(r){this._delegate=r}setServerRootPath(r,e){this._serverRootPath=Te.join(e??"/",qE(r))}getServerRootPath(){return this._serverRootPath}get _remoteResourcesPath(){return Te.join(this._serverRootPath,re.vscodeRemoteResource)}set(r,e,t){this._hosts[r]=e,this._ports[r]=t}setConnectionToken(r,e){this._connectionTokens[r]=e}getPreferredWebSchema(){return this._preferredWebSchema}rewrite(r){if(this._delegate)try{return this._delegate(r)}catch(a){return Me(a),r}let e=r.authority,t=this._hosts[e];t&&t.indexOf(":")!==-1&&t.indexOf("[")===-1&&(t=`[${t}]`);let n=this._ports[e],i=this._connectionTokens[e],s=`path=${encodeURIComponent(r.path)}`;return typeof i=="string"&&(s+=`&${GE}=${encodeURIComponent(i)}`),P.from({scheme:ze?this._preferredWebSchema:re.vscodeRemoteResource,authority:`${t}:${n}`,path:this._remoteResourcesPath,query:s})}},Wm=new Nm;function qE(o){return`${o.quality??"oss"}-${o.commit??"dev"}`}var IS="vs/../../node_modules",bS="vs/../../node_modules.asar";var Bm="vscode-app",Vm=class o{static{this.FALLBACK_AUTHORITY=Bm}asBrowserUri(r){let e=this.toUri(r);return this.uriToBrowserUri(e)}uriToBrowserUri(r){return r.scheme===re.vscodeRemote?Wm.rewrite(r):r.scheme===re.file&&(Jy||Qy===`${re.vscodeFileResource}://${o.FALLBACK_AUTHORITY}`)?r.with({scheme:re.vscodeFileResource,authority:r.authority||o.FALLBACK_AUTHORITY,query:null,fragment:null}):r}asFileUri(r){let e=this.toUri(r);return this.uriToFileUri(e)}uriToFileUri(r){return r.scheme===re.vscodeFileResource?r.with({scheme:re.file,authority:r.authority!==o.FALLBACK_AUTHORITY?r.authority:null,query:null,fragment:null}):r}toUri(r){if(P.isUri(r))return r;if(globalThis._VSCODE_FILE_ROOT){let e=globalThis._VSCODE_FILE_ROOT;if(/^\w[\w\d+.-]*:\/\//.test(e))return P.joinPath(P.parse(e,!0),r);let t=G(e,r);return P.file(t)}throw new Error("Cannot determine URI for module id!")}},dr=new Vm,BD=Object.freeze({"Cache-Control":"no-cache, no-store"}),$D=Object.freeze({"Document-Policy":"include-js-call-stacks-in-crash-reports"}),zE;(i=>{let o=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"}]]);i.CoopAndCoep=Object.freeze(o.get("3"));let e="vscode-coi";function t(s){let a;typeof s=="string"?a=new URL(s).searchParams:s instanceof URL?a=s.searchParams:P.isUri(s)&&(a=new URL(s.toString(!0)).searchParams);let l=a?.get(e);if(l)return o.get(l)}i.getHeadersFromQuery=t;function n(s,a,l){if(!globalThis.crossOriginIsolated)return;let c=a&&l?"3":l?"2":"1";s instanceof URLSearchParams?s.set(e,c):s[e]=c}i.addSearchParam=n})(zE||={});function si(o){return o===47||o===92}function $m(o){return o.replace(/[\\/]/g,Te.sep)}function xS(o){return o.indexOf("/")===-1&&(o=$m(o)),/^[a-zA-Z]:(\/|$)/.test(o)&&(o="/"+o),o}function Gm(o,r=Te.sep){if(!o)return"";let e=o.length,t=o.charCodeAt(0);if(si(t)){if(si(o.charCodeAt(1))&&!si(o.charCodeAt(2))){let i=3,s=i;for(;i<e&&!si(o.charCodeAt(i));i++);if(s!==i&&!si(o.charCodeAt(i+1))){for(i+=1;i<e;i++)if(si(o.charCodeAt(i)))return o.slice(0,i+1).replace(/[\\/]/g,r)}}return r}else if(ES(t)&&o.charCodeAt(1)===58)return si(o.charCodeAt(2))?o.slice(0,2)+r:o.slice(0,2);let n=o.indexOf("://");if(n!==-1){for(n+=3;n<e;n++)if(si(o.charCodeAt(n)))return o.slice(0,n+1)}return""}function es(o,r,e){let t=o===r;return!e||t?t:!o||!r?!1:yr(o,r)}function On(o,r,e,t=Ut){if(o===r)return!0;if(!o||!r||r.length>o.length)return!1;if(e){if(!ji(o,r))return!1;if(r.length===o.length)return!0;let i=r.length;return r.charAt(r.length-1)===t&&i--,o.charAt(i)===t}return r.charAt(r.length-1)!==t&&(r+=t),o.indexOf(r)===0}function ES(o){return o>=65&&o<=90||o>=97&&o<=122}function wS(o){return he?(o=Qo(o,Ut),o.endsWith(":")&&(o+=Ut)):(o=Qo(o,Ut),o||(o=Ut)),o}function qm(o){let r=br(o);return he?o.length>3?!1:KE(r)&&(o.length===2||r.charCodeAt(2)===92):r===Te.sep}function KE(o,r=he){return r?ES(o.charCodeAt(0))&&o.charCodeAt(1)===58:!1}var jE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",HE="BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";function PS(o,r,e=8){let t="";for(let i=0;i<e;i++){let s;i===0&&he&&!r&&(e===3||e===4)?s=HE:s=jE,t+=s.charAt(Math.floor(Math.random()*s.length))}let n;return r?n=`${r}-${t}`:n=t,o?G(o,n):n}function xn(o){return Tl(o,!0)}var Qi=class{constructor(r){this._ignorePathCasing=r}compare(r,e,t=!1){return r===e?0:zi(this.getComparisonKey(r,t),this.getComparisonKey(e,t))}isEqual(r,e,t=!1){return r===e?!0:!r||!e?!1:this.getComparisonKey(r,t)===this.getComparisonKey(e,t)}getComparisonKey(r,e=!1){return r.with({path:this._ignorePathCasing(r)?r.path.toLowerCase():void 0,fragment:e?null:void 0}).toString()}ignorePathCasing(r){return this._ignorePathCasing(r)}isEqualOrParent(r,e,t=!1){if(r.scheme===e.scheme){if(r.scheme===re.file)return On(xn(r),xn(e),this._ignorePathCasing(r))&&r.query===e.query&&(t||r.fragment===e.fragment);if(RS(r.authority,e.authority))return On(r.path,e.path,this._ignorePathCasing(r),"/")&&r.query===e.query&&(t||r.fragment===e.fragment)}return!1}joinPath(r,...e){return P.joinPath(r,...e)}basenameOrAuthority(r){return Nn(r)||r.authority}basename(r){return Te.basename(r.path)}extname(r){return Te.extname(r.path)}dirname(r){if(r.path.length===0)return r;let e;return r.scheme===re.file?e=P.file($e(xn(r))).path:(e=Te.dirname(r.path),r.authority&&e.length&&e.charCodeAt(0)!==47&&(console.error(`dirname("${r.toString})) resulted in a relative path`),e="/")),r.with({path:e})}normalizePath(r){if(!r.path.length)return r;let e;return r.scheme===re.file?e=P.file(br(xn(r))).path:e=Te.normalize(r.path),r.with({path:e})}relativePath(r,e){if(r.scheme!==e.scheme||!RS(r.authority,e.authority))return;if(r.scheme===re.file){let i=bd(xn(r),xn(e));return he?$m(i):i}let t=r.path||"/",n=e.path||"/";if(this._ignorePathCasing(r)){let i=0;for(let s=Math.min(t.length,n.length);i<s&&!(t.charCodeAt(i)!==n.charCodeAt(i)&&t.charAt(i).toLowerCase()!==n.charAt(i).toLowerCase());i++);t=n.substr(0,i)+t.substr(i)}return Te.relative(t,n)}resolvePath(r,e){if(r.scheme===re.file){let t=P.file(en(xn(r),e));return r.with({authority:t.authority,path:t.path})}return e=xS(e),r.with({path:Te.resolve(r.path,e)})}isAbsolutePath(r){return!!r.path&&r.path[0]==="/"}isEqualAuthority(r,e){return r===e||r!==void 0&&e!==void 0&&yr(r,e)}hasTrailingPathSeparator(r,e=Ut){if(r.scheme===re.file){let t=xn(r);return t.length>Gm(t).length&&t[t.length-1]===e}else{let t=r.path;return t.length>1&&t.charCodeAt(t.length-1)===47&&!/^[a-zA-Z]:(\/$|\\$)/.test(r.fsPath)}}removeTrailingPathSeparator(r,e=Ut){return TS(r,e)?r.with({path:r.path.substr(0,r.path.length-1)}):r}addTrailingPathSeparator(r,e=Ut){let t=!1;if(r.scheme===re.file){let n=xn(r);t=n!==void 0&&n.length===Gm(n).length&&n[n.length-1]===e}else{e="/";let n=r.path;t=n.length===1&&n.charCodeAt(n.length-1)===47}return!t&&!TS(r,e)?r.with({path:r.path+"/"}):r}},De=new Qi(()=>!1),Xi=new Qi(o=>o.scheme===re.file?!Be:!0),CS=new Qi(o=>!0),_r=De.isEqual.bind(De),zm=De.isEqualOrParent.bind(De),e_=De.getComparisonKey.bind(De),QE=De.basenameOrAuthority.bind(De),Nn=De.basename.bind(De),XE=De.extname.bind(De),wd=De.dirname.bind(De),$=De.joinPath.bind(De),DS=De.normalizePath.bind(De),_S=De.relativePath.bind(De),t_=De.resolvePath.bind(De),kS=De.isAbsolutePath.bind(De),RS=De.isEqualAuthority.bind(De),TS=De.hasTrailingPathSeparator.bind(De),r_=De.removeTrailingPathSeparator.bind(De),n_=De.addTrailingPathSeparator.bind(De);var YE;(i=>{i.META_DATA_LABEL="label",i.META_DATA_DESCRIPTION="description",i.META_DATA_SIZE="size",i.META_DATA_MIME="mime";function n(s){let a=new Map;s.path.substring(s.path.indexOf(";")+1,s.path.lastIndexOf(";")).split(";").forEach(d=>{let[u,p]=d.split(":");u&&p&&a.set(u,p)});let c=s.path.substring(0,s.path.indexOf(";"));return c&&a.set(i.META_DATA_MIME,c),a}i.parseMetaData=n})(YE||={});var US=Symbol("MicrotaskDelay");function Dd(o){return!!o&&typeof o.then=="function"}function Je(o){let r=new mt,e=o(r.token),t=!1,n=new Promise((i,s)=>{let a=r.token.onCancellationRequested(()=>{t=!0,a.dispose(),s(new We)});Promise.resolve(e).then(l=>{a.dispose(),r.dispose(),t?qo(l)&&l.dispose():i(l)},l=>{a.dispose(),r.dispose(),s(l)})});return new class{cancel(){r.cancel(),r.dispose()}then(i,s){return n.then(i,s)}catch(i){return this.then(void 0,i)}finally(i){return n.finally(i)}}}function AS(o){let r=-1,e=o.map((n,i)=>n.then(s=>(r=i,s))),t=Promise.race(e);return t.cancel=()=>{o.forEach((n,i)=>{i!==r&&n.cancel&&n.cancel()})},t.finally(()=>{t.cancel()}),t}function FS(){let o,r;return{promise:new Promise((t,n)=>{o=t,r=n}),resolve:o,reject:r}}var Km=class{constructor(){this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null,this.cancellationTokenSource=new mt}queue(r){if(this.cancellationTokenSource.token.isCancellationRequested)return Promise.reject(new Error("Throttler is disposed"));if(this.activePromise){if(this.queuedPromiseFactory=r,!this.queuedPromise){let e=()=>{if(this.queuedPromise=null,this.cancellationTokenSource.token.isCancellationRequested)return;let t=this.queue(this.queuedPromiseFactory);return this.queuedPromiseFactory=null,t};this.queuedPromise=new Promise(t=>{this.activePromise.then(e,e).then(t)})}return new Promise((e,t)=>{this.queuedPromise.then(e,t)})}return this.activePromise=r(this.cancellationTokenSource.token),new Promise((e,t)=>{this.activePromise.then(n=>{this.activePromise=null,e(n)},n=>{this.activePromise=null,t(n)})})}dispose(){this.cancellationTokenSource.cancel()}},Rd=class{constructor(){this.current=Promise.resolve(null)}queue(r){return this.current=this.current.then(()=>r(),()=>r())}};var ZE=(o,r)=>{let e=!0,t=setTimeout(()=>{e=!1,r()},o);return{isTriggered:()=>e,dispose:()=>{clearTimeout(t),e=!1}}},ew=o=>{let r=!0;return queueMicrotask(()=>{r&&(r=!1,o())}),{isTriggered:()=>r,dispose:()=>{r=!1}}},Yi=class{constructor(r){this.defaultDelay=r;this.deferred=null,this.completionPromise=null,this.doResolve=null,this.doReject=null,this.task=null}trigger(r,e=this.defaultDelay){this.task=r,this.cancelTimeout(),this.completionPromise||(this.completionPromise=new Promise((n,i)=>{this.doResolve=n,this.doReject=i}).then(()=>{if(this.completionPromise=null,this.doResolve=null,this.task){let n=this.task;return this.task=null,n()}}));let t=()=>{this.deferred=null,this.doResolve?.(null)};return this.deferred=e===US?ew(t):ZE(e,t),this.completionPromise}isTriggered(){return!!this.deferred?.isTriggered()}cancel(){this.cancelTimeout(),this.completionPromise&&(this.doReject?.(new We),this.completionPromise=null)}cancelTimeout(){this.deferred?.dispose(),this.deferred=null}dispose(){this.cancel()}},ur=class{constructor(r){this.delayer=new Yi(r),this.throttler=new Km}trigger(r,e){return this.delayer.trigger(()=>this.throttler.queue(r),e)}isTriggered(){return this.delayer.isTriggered()}cancel(){this.delayer.cancel()}dispose(){this.delayer.dispose(),this.throttler.dispose()}},Kr=class{constructor(){this._isOpen=!1,this._promise=new Promise((r,e)=>{this._completePromise=r})}isOpen(){return this._isOpen}open(){this._isOpen=!0,this._completePromise(!0)}wait(){return this._promise}};function Lr(o,r){return r?new Promise((e,t)=>{let n=setTimeout(()=>{i.dispose(),e()},o),i=r.onCancellationRequested(()=>{clearTimeout(n),i.dispose(),t(new We)})}):Je(e=>Lr(o,e))}function ai(o,r=0,e){let t=setTimeout(()=>{o(),e&&n.dispose()},r),n=oe(()=>{clearTimeout(t),e?.delete(n)});return e?.add(n),n}var Cl=class{constructor(r){this._size=0;this._isDisposed=!1;this.maxDegreeOfParalellism=r,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new w}whenIdle(){return this.size>0?k.toPromise(this.onDrained):Promise.resolve()}get onDrained(){return this._onDrained.event}get size(){return this._size}queue(r){if(this._isDisposed)throw new Error("Object has been disposed");return this._size++,new Promise((e,t)=>{this.outstandingPromises.push({factory:r,c:e,e:t}),this.consume()})}consume(){for(;this.outstandingPromises.length&&this.runningPromises<this.maxDegreeOfParalellism;){let r=this.outstandingPromises.shift();this.runningPromises++;let e=r.factory();e.then(r.c,r.e),e.then(()=>this.consumed(),()=>this.consumed())}}consumed(){this._isDisposed||(this.runningPromises--,--this._size===0&&this._onDrained.fire(),this.outstandingPromises.length>0&&this.consume())}clear(){if(this._isDisposed)throw new Error("Object has been disposed");this.outstandingPromises.length=0,this._size=this.runningPromises}dispose(){this._isDisposed=!0,this.outstandingPromises.length=0,this._size=0,this._onDrained.dispose()}},kr=class extends Cl{constructor(){super(1)}};var ts=class{constructor(){this.queues=new Map;this.drainers=new Set;this.drainListeners=void 0;this.drainListenerCount=0}async whenDrained(){if(this.isDrained())return;let r=new Ur;return this.drainers.add(r),r.p}isDrained(){for(let[,r]of this.queues)if(r.size>0)return!1;return!0}queueSize(r,e=De){let t=e.getComparisonKey(r);return this.queues.get(t)?.size??0}queueFor(r,e,t=De){let n=t.getComparisonKey(r),i=this.queues.get(n);if(!i){i=new kr;let s=this.drainListenerCount++,a=k.once(i.onDrained)(()=>{i?.dispose(),this.queues.delete(n),this.onDidQueueDrain(),this.drainListeners?.deleteAndDispose(s),this.drainListeners?.size===0&&(this.drainListeners.dispose(),this.drainListeners=void 0)});this.drainListeners||(this.drainListeners=new Gr),this.drainListeners.set(s,a),this.queues.set(n,i)}return i.queue(e)}onDidQueueDrain(){this.isDrained()&&this.releaseDrainers()}releaseDrainers(){for(let r of this.drainers)r.complete();this.drainers.clear()}dispose(){for(let[,r]of this.queues)r.dispose();this.queues.clear(),this.releaseDrainers(),this.drainListeners?.dispose()}};var It=class{constructor(r,e){this.timeoutToken=void 0,this.runner=r,this.timeout=e,this.timeoutHandler=this.onTimeout.bind(this)}dispose(){this.cancel(),this.runner=null}cancel(){this.isScheduled()&&(clearTimeout(this.timeoutToken),this.timeoutToken=void 0)}schedule(r=this.timeout){this.cancel(),this.timeoutToken=setTimeout(this.timeoutHandler,r)}get delay(){return this.timeout}set delay(r){this.timeout=r}isScheduled(){return this.timeoutToken!==void 0}flush(){this.isScheduled()&&(this.cancel(),this.doRun())}onTimeout(){this.timeoutToken=void 0,this.runner&&this.doRun()}doRun(){this.runner?.()}};var Td=class extends It{constructor(e,t){super(e,t);this.units=[]}work(e){this.units.push(e),this.isScheduled()||this.schedule()}doRun(){let e=this.units;this.units=[],this.runner?.(e)}dispose(){this.units=[],super.dispose()}},rs=class extends T{constructor(e,t){super();this.options=e;this.handler=t;this.pendingWork=[];this.throttler=this._register(new kt);this.disposed=!1;this.lastExecutionTime=0}get pending(){return this.pendingWork.length}work(e){if(this.disposed)return!1;if(typeof this.options.maxBufferedWork=="number"){if(this.throttler.value){if(this.pending+e.length>this.options.maxBufferedWork)return!1}else if(this.pending+e.length-this.options.maxWorkChunkSize>this.options.maxBufferedWork)return!1}for(let n of e)this.pendingWork.push(n);let t=Date.now()-this.lastExecutionTime;return!this.throttler.value&&(!this.options.waitThrottleDelayBetweenWorkUnits||t>=this.options.throttleDelay)?this.doWork():!this.throttler.value&&this.options.waitThrottleDelayBetweenWorkUnits&&this.scheduleThrottler(Math.max(this.options.throttleDelay-t,0)),!0}doWork(){this.lastExecutionTime=Date.now(),this.handler(this.pendingWork.splice(0,this.options.maxWorkChunkSize)),this.pendingWork.length>0&&this.scheduleThrottler()}scheduleThrottler(e=this.options.throttleDelay){this.throttler.value=new It(()=>{this.throttler.clear(),this.doWork()},e),this.throttler.value.schedule()}dispose(){super.dispose(),this.pendingWork.length=0,this.disposed=!0}},Jm,Pd;(function(){let o=globalThis;typeof o.requestIdleCallback!="function"||typeof o.cancelIdleCallback!="function"?Pd=(r,e,t)=>{Xy(()=>{if(n)return;let i=Date.now()+15;e(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,i-Date.now())}}))});let n=!1;return{dispose(){n||(n=!0)}}}:Pd=(r,e,t)=>{let n=r.requestIdleCallback(e,typeof t=="number"?{timeout:t}:void 0),i=!1;return{dispose(){i||(i=!0,r.cancelIdleCallback(n))}}},Jm=(r,e)=>Pd(globalThis,r,e)})();var jm=class{constructor(r,e){this._didRun=!1;this._executor=()=>{try{this._value=e()}catch(t){this._error=t}finally{this._didRun=!0}},this._handle=Pd(r,()=>this._executor())}dispose(){this._handle.dispose()}get value(){if(this._didRun||(this._handle.dispose(),this._executor()),this._error)throw this._error;return this._value}get isInitialized(){return this._didRun}},Cd=class extends jm{constructor(r){super(globalThis,r)}};async function OS(o,r,e){let t;for(let n=0;n<e;n++)try{return await o()}catch(i){t=i,await Lr(r)}throw t}var Ur=class o{static fromPromise(r){let e=new o;return e.settleWith(r),e}get isRejected(){return this.outcome?.outcome===1}get isResolved(){return this.outcome?.outcome===0}get isSettled(){return!!this.outcome}get value(){return this.outcome?.outcome===0?this.outcome?.value:void 0}constructor(){this.p=new Promise((r,e)=>{this.completeCallback=r,this.errorCallback=e})}complete(r){return this.isSettled?Promise.resolve():new Promise(e=>{this.completeCallback(r),this.outcome={outcome:0,value:r},e()})}error(r){return this.isSettled?Promise.resolve():new Promise(e=>{this.errorCallback(r),this.outcome={outcome:1,value:r},e()})}settleWith(r){return r.then(e=>this.complete(e),e=>this.error(e))}cancel(){return this.error(new We)}},Ke;(e=>{async function o(t){let n,i=await Promise.all(t.map(s=>s.then(a=>a,a=>{n||(n=a)})));if(typeof n<"u")throw n;return i}e.settled=o;function r(t){return new Promise(async(n,i)=>{try{await t(n,i)}catch(s){i(s)}})}e.withAsyncBody=r})(Ke||={});var LS=class o{static fromArray(r){return new o(e=>{e.emitMany(r)})}static fromPromise(r){return new o(async e=>{e.emitMany(await r)})}static fromPromisesResolveOrder(r){return new o(async e=>{await Promise.all(r.map(async t=>e.emitOne(await t)))})}static merge(r){return new o(async e=>{await Promise.all(r.map(async t=>{for await(let n of t)e.emitOne(n)}))})}static{this.EMPTY=o.fromArray([])}constructor(r,e){this._state=0,this._results=[],this._error=null,this._onReturn=e,this._onStateChanged=new w,queueMicrotask(async()=>{let t={emitOne:n=>this.emitOne(n),emitMany:n=>this.emitMany(n),reject:n=>this.reject(n)};try{await Promise.resolve(r(t)),this.resolve()}catch(n){this.reject(n)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let r=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(r<this._results.length)return{done:!1,value:this._results[r++]};if(this._state===1)return{done:!0,value:void 0};await k.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(r,e){return new o(async t=>{for await(let n of r)t.emitOne(e(n))})}map(r){return o.map(this,r)}static filter(r,e){return new o(async t=>{for await(let n of r)e(n)&&t.emitOne(n)})}filter(r){return o.filter(this,r)}static coalesce(r){return o.filter(r,e=>!!e)}coalesce(){return o.coalesce(this)}static async toPromise(r){let e=[];for await(let t of r)e.push(t);return e}toPromise(){return o.toPromise(this)}emitOne(r){this._state===0&&(this._results.push(r),this._onStateChanged.fire())}emitMany(r){this._state===0&&(this._results=this._results.concat(r),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(r){this._state===0&&(this._state=2,this._error=r,this._onStateChanged.fire())}};var Hm=class{constructor(){this._unsatisfiedConsumers=[];this._unconsumedValues=[]}get hasFinalValue(){return!!this._finalValue}produce(r){if(this._ensureNoFinalValue(),this._unsatisfiedConsumers.length>0){let e=this._unsatisfiedConsumers.shift();this._resolveOrRejectDeferred(e,r)}else this._unconsumedValues.push(r)}produceFinal(r){this._ensureNoFinalValue(),this._finalValue=r;for(let e of this._unsatisfiedConsumers)this._resolveOrRejectDeferred(e,r);this._unsatisfiedConsumers.length=0}_ensureNoFinalValue(){if(this._finalValue)throw new Xn("ProducerConsumer: cannot produce after final value has been set")}_resolveOrRejectDeferred(r,e){e.ok?r.complete(e.value):r.error(e.error)}consume(){if(this._unconsumedValues.length>0||this._finalValue){let r=this._unconsumedValues.length>0?this._unconsumedValues.shift():this._finalValue;return r.ok?Promise.resolve(r.value):Promise.reject(r.error)}else{let r=new Ur;return this._unsatisfiedConsumers.push(r),r.p}}},MS=class o{constructor(r,e){this._onReturn=e;this._producerConsumer=new Hm;this._iterator={next:()=>this._producerConsumer.consume(),return:()=>(this._onReturn?.(),Promise.resolve({done:!0,value:void 0})),throw:async r=>(this._finishError(r),{done:!0,value:void 0})};queueMicrotask(async()=>{let t=r({emitOne:n=>this._producerConsumer.produce({ok:!0,value:{done:!1,value:n}}),emitMany:n=>{for(let i of n)this._producerConsumer.produce({ok:!0,value:{done:!1,value:i}})},reject:n=>this._finishError(n)});if(!this._producerConsumer.hasFinalValue)try{await t,this._finishOk()}catch(n){this._finishError(n)}})}static fromArray(r){return new o(e=>{e.emitMany(r)})}static fromPromise(r){return new o(async e=>{e.emitMany(await r)})}static fromPromisesResolveOrder(r){return new o(async e=>{await Promise.all(r.map(async t=>e.emitOne(await t)))})}static merge(r){return new o(async e=>{await Promise.all(r.map(async t=>{for await(let n of t)e.emitOne(n)}))})}static{this.EMPTY=o.fromArray([])}static map(r,e){return new o(async t=>{for await(let n of r)t.emitOne(e(n))})}static tee(r){let e,t,n=new Ur,i=async()=>{if(!(!e||!t))try{for await(let l of r)e.emitOne(l),t.emitOne(l)}catch(l){e.reject(l),t.reject(l)}finally{n.complete()}},s=new o(async l=>(e=l,i(),n.p)),a=new o(async l=>(t=l,i(),n.p));return[s,a]}map(r){return o.map(this,r)}static coalesce(r){return o.filter(r,e=>!!e)}coalesce(){return o.coalesce(this)}static filter(r,e){return new o(async t=>{for await(let n of r)e(n)&&t.emitOne(n)})}filter(r){return o.filter(this,r)}_finishOk(){this._producerConsumer.hasFinalValue||this._producerConsumer.produceFinal({ok:!0,value:{done:!0,value:void 0}})}_finishError(r){this._producerConsumer.hasFinalValue||this._producerConsumer.produceFinal({ok:!1,error:r})}[Symbol.asyncIterator](){return this._iterator}};function Dl(o){let r=o;return r?[r.on,r.pause,r.resume,r.destroy].every(e=>typeof e=="function"):!1}function _d(o){let r=o;return r?Dl(r.stream)&&Array.isArray(r.buffer)&&typeof r.ended=="boolean":!1}function Vn(o,r){return new Qm(o,r)}var Qm=class{constructor(r,e){this.reducer=r;this.options=e;this.state={flowing:!1,ended:!1,destroyed:!1};this.buffer={data:[],error:[]};this.listeners={data:[],error:[],end:[]};this.pendingWritePromises=[]}pause(){this.state.destroyed||(this.state.flowing=!1)}resume(){this.state.destroyed||this.state.flowing||(this.state.flowing=!0,this.flowData(),this.flowErrors(),this.flowEnd())}write(r){if(!this.state.destroyed){if(this.state.flowing)this.emitData(r);else if(this.buffer.data.push(r),typeof this.options?.highWaterMark=="number"&&this.buffer.data.length>this.options.highWaterMark)return new Promise(e=>this.pendingWritePromises.push(e))}}error(r){this.state.destroyed||(this.state.flowing?this.emitError(r):this.buffer.error.push(r))}end(r){this.state.destroyed||(typeof r<"u"&&this.write(r),this.state.flowing?(this.emitEnd(),this.destroy()):this.state.ended=!0)}emitData(r){this.listeners.data.slice(0).forEach(e=>e(r))}emitError(r){this.listeners.error.length===0?Me(r):this.listeners.error.slice(0).forEach(e=>e(r))}emitEnd(){this.listeners.end.slice(0).forEach(r=>r())}on(r,e){if(!this.state.destroyed)switch(r){case"data":this.listeners.data.push(e),this.resume();break;case"end":this.listeners.end.push(e),this.state.flowing&&this.flowEnd()&&this.destroy();break;case"error":this.listeners.error.push(e),this.state.flowing&&this.flowErrors();break}}removeListener(r,e){if(this.state.destroyed)return;let t;switch(r){case"data":t=this.listeners.data;break;case"end":t=this.listeners.end;break;case"error":t=this.listeners.error;break}if(t){let n=t.indexOf(e);n>=0&&t.splice(n,1)}}flowData(){if(this.buffer.data.length===0)return;if(typeof this.reducer=="function"){let e=this.reducer(this.buffer.data);this.emitData(e)}else for(let e of this.buffer.data)this.emitData(e);this.buffer.data.length=0;let r=[...this.pendingWritePromises];this.pendingWritePromises.length=0,r.forEach(e=>e())}flowErrors(){if(this.listeners.error.length>0){for(let r of this.buffer.error)this.emitError(r);this.buffer.error.length=0}}flowEnd(){return this.state.ended?(this.emitEnd(),this.listeners.end.length>0):!1}destroy(){this.state.destroyed||(this.state.destroyed=!0,this.state.ended=!0,this.buffer.data.length=0,this.buffer.error.length=0,this.listeners.data.length=0,this.listeners.error.length=0,this.listeners.end.length=0,this.pendingWritePromises.length=0)}};function NS(o,r){let e=[],t;for(;(t=o.read())!==null;)e.push(t);return r(e)}function VS(o,r,e){let t=[],n;for(;(n=o.read())!==null&&t.length<e;)t.push(n);return n===null&&t.length>0?r(t):{read:()=>{if(t.length>0)return t.shift();if(typeof n<"u"){let i=n;return n=void 0,i}return o.read()}}}function kd(o,r){return new Promise((e,t)=>{let n=[];ns(o,{onData:i=>{r&&n.push(i)},onError:i=>{r?t(i):e(void 0)},onEnd:()=>{e(r?r(n):void 0)}})})}function ns(o,r,e){o.on("error",t=>{e?.isCancellationRequested||r.onError(t)}),o.on("end",()=>{e?.isCancellationRequested||r.onEnd()}),o.on("data",t=>{e?.isCancellationRequested||r.onData(t)})}function WS(o,r){return new Promise((e,t)=>{let n=new se,i=[],s=c=>{if(i.push(c),i.length>r)return n.dispose(),o.pause(),e({stream:o,buffer:i,ended:!1})},a=c=>(n.dispose(),t(c)),l=()=>(n.dispose(),e({stream:o,buffer:i,ended:!0}));n.add(oe(()=>o.removeListener("error",a))),o.on("error",a),n.add(oe(()=>o.removeListener("end",l))),o.on("end",l),n.add(oe(()=>o.removeListener("data",s))),o.on("data",s)})}function BS(o){let r=!1;return{read:()=>r?null:(r=!0,o)}}function Ud(o,r,e){let t=Vn(e);return ns(o,{onData:n=>t.write(r.data(n)),onError:n=>t.error(r.error?r.error(n):n),onEnd:()=>t.end()}),t}var _l=typeof Buffer<"u",rw=new cr(()=>new Uint8Array(256)),Xm,Ym,U=class o{static alloc(r){return _l?new o(Buffer.allocUnsafe(r)):new o(new Uint8Array(r))}static wrap(r){return _l&&!Buffer.isBuffer(r)&&(r=Buffer.from(r.buffer,r.byteOffset,r.byteLength)),new o(r)}static fromString(r,e){return!(e?.dontUseNodeBuffer||!1)&&_l?new o(Buffer.from(r)):(Xm||(Xm=new TextEncoder),new o(Xm.encode(r)))}static fromByteArray(r){let e=o.alloc(r.length);for(let t=0,n=r.length;t<n;t++)e.buffer[t]=r[t];return e}static concat(r,e){if(typeof e>"u"){e=0;for(let i=0,s=r.length;i<s;i++)e+=r[i].byteLength}let t=o.alloc(e),n=0;for(let i=0,s=r.length;i<s;i++){let a=r[i];t.set(a,n),n+=a.byteLength}return t}static isNativeBuffer(r){return _l&&Buffer.isBuffer(r)}constructor(r){this.buffer=r,this.byteLength=this.buffer.byteLength}clone(){let r=o.alloc(this.byteLength);return r.set(this),r}toString(){return _l?this.buffer.toString():(Ym||(Ym=new TextDecoder(void 0,{ignoreBOM:!0})),Ym.decode(this.buffer))}slice(r,e){return new o(this.buffer.subarray(r,e))}set(r,e){if(r instanceof o)this.buffer.set(r.buffer,e);else if(r instanceof Uint8Array)this.buffer.set(r,e);else if(r instanceof ArrayBuffer)this.buffer.set(new Uint8Array(r),e);else if(ArrayBuffer.isView(r))this.buffer.set(new Uint8Array(r.buffer,r.byteOffset,r.byteLength),e);else throw new Error("Unknown argument 'array'")}readUInt32BE(r){return nw(this.buffer,r)}writeUInt32BE(r,e){iw(this.buffer,r,e)}readUInt32LE(r){return ow(this.buffer,r)}writeUInt32LE(r,e){sw(this.buffer,r,e)}readUInt8(r){return aw(this.buffer,r)}writeUInt8(r,e){lw(this.buffer,r,e)}indexOf(r,e=0){return Zm(this.buffer,r instanceof o?r.buffer:r,e)}equals(r){return this===r?!0:this.byteLength!==r.byteLength?!1:this.buffer.every((e,t)=>e===r.buffer[t])}};function Zm(o,r,e=0){let t=r.byteLength,n=o.byteLength;if(t===0)return 0;if(t===1)return o.indexOf(r[0],e);if(t>n-e)return-1;let i=rw.value;i.fill(r.length);for(let c=0;c<r.length;c++)i[r[c]]=r.length-c-1;let s=e+r.length-1,a=s,l=-1;for(;s<n;)if(o[s]===r[a]){if(a===0){l=s;break}s--,a--}else s+=Math.max(r.length-a,i[o[s]]),a=r.length-1;return l}function nw(o,r){return o[r]*2**24+o[r+1]*2**16+o[r+2]*2**8+o[r+3]}function iw(o,r,e){o[e+3]=r,r=r>>>8,o[e+2]=r,r=r>>>8,o[e+1]=r,r=r>>>8,o[e]=r}function ow(o,r){return o[r+0]<<0>>>0|o[r+1]<<8>>>0|o[r+2]<<16>>>0|o[r+3]<<24>>>0}function sw(o,r,e){o[e+0]=r&255,r=r>>>8,o[e+1]=r&255,r=r>>>8,o[e+2]=r&255,r=r>>>8,o[e+3]=r&255}function aw(o,r){return o[r]}function lw(o,r,e){o[e]=r}function GS(o){return NS(o,r=>U.concat(r))}function qS(o){return BS(o)}function En(o){return kd(o,r=>U.concat(r))}async function zS(o){return o.ended?U.concat(o.buffer):U.concat([...o.buffer,await En(o.stream)])}function KS(o){return Ud(o,{data:r=>typeof r=="string"?U.fromString(r):U.wrap(r)},r=>U.concat(r))}function jS(o){return Vn(r=>U.concat(r),o)}var cw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",dw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function HS({buffer:o},r=!0,e=!1){let t=e?dw:cw,n="",i=o.byteLength%3,s=0;for(;s<o.byteLength-i;s+=3){let a=o[s+0],l=o[s+1],c=o[s+2];n+=t[a>>>2],n+=t[(a<<4|l>>>4)&63],n+=t[(l<<2|c>>>6)&63],n+=t[c&63]}if(i===1){let a=o[s+0];n+=t[a>>>2],n+=t[a<<4&63],r&&(n+="==")}else if(i===2){let a=o[s+0],l=o[s+1];n+=t[a>>>2],n+=t[(a<<4|l>>>4)&63],n+=t[l<<2&63],r&&(n+="=")}return n}var $S="0123456789abcdef";function JS({buffer:o}){let r="";for(let e=0;e<o.length;e++){let t=o[e];r+=$S[t>>>4],r+=$S[t&15]}return r}function Ue(o,r,e){let t=null,n=null;if(typeof e.value=="function"?(t="value",n=e.value,n.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof e.get=="function"&&(t="get",n=e.get),!n)throw new Error("not supported");let i=`$memoize$${r}`;e[t]=function(...s){return this.hasOwnProperty(i)||Object.defineProperty(this,i,{configurable:!1,enumerable:!1,writable:!1,value:n.apply(this,s)}),this[i]}}function QS(o){return JSON.stringify(o,uw)}function XS(o){let r=JSON.parse(o);return r=li(r),r}function uw(o,r){return r instanceof RegExp?{$mid:2,source:r.source,flags:r.flags}:r}function li(o,r=0){if(!o||r>200)return o;if(typeof o=="object"){switch(o.$mid){case 1:return P.revive(o);case 2:return new RegExp(o.source,o.flags);case 17:return new Date(o.source)}if(o instanceof U||o instanceof Uint8Array)return o;if(Array.isArray(o))for(let e=0;e<o.length;++e)o[e]=li(o[e],r+1);else for(let e in o)Object.hasOwnProperty.call(o,e)&&(o[e]=li(o[e],r+1))}return o}function ss(o){switch(o){case 100:return"req";case 101:return"cancel";case 102:return"subscribe";case 103:return"unsubscribe"}}function Ld(o){switch(o){case 200:return"init";case 201:return"reply:";case 202:case 203:return"replyErr:";case 204:return"event:"}}function is(o){let r=0;for(let e=0;;e+=7){let t=o.read(1);if(r|=(t.buffer[0]&127)<<e,!(t.buffer[0]&128))return r}}var pw=ci(0);function os(o,r){if(r===0){o.write(pw);return}let e=0;for(let n=r;n!==0;n=n>>>7)e++;let t=U.alloc(e);for(let n=0;r!==0;n++)t.buffer[n]=r&127,r=r>>>7,r>0&&(t.buffer[n]|=128);o.write(t)}var kl=class{constructor(r){this.buffer=r;this.pos=0}read(r){let e=this.buffer.slice(this.pos,this.pos+r);return this.pos+=e.byteLength,e}},Md=class{constructor(){this.buffers=[]}get buffer(){return U.concat(this.buffers)}write(r){this.buffers.push(r)}};function ci(o){let r=U.alloc(1);return r.writeUInt8(o,0),r}var Zi={Undefined:ci(0),String:ci(1),Buffer:ci(2),VSBuffer:ci(3),Array:ci(4),Object:ci(5),Uint:ci(6)};function Ul(o,r){if(typeof r>"u")o.write(Zi.Undefined);else if(typeof r=="string"){let e=U.fromString(r);o.write(Zi.String),os(o,e.byteLength),o.write(e)}else if(U.isNativeBuffer(r)){let e=U.wrap(r);o.write(Zi.Buffer),os(o,e.byteLength),o.write(e)}else if(r instanceof U)o.write(Zi.VSBuffer),os(o,r.byteLength),o.write(r);else if(Array.isArray(r)){o.write(Zi.Array),os(o,r.length);for(let e of r)Ul(o,e)}else if(typeof r=="number"&&(r|0)===r)o.write(Zi.Uint),os(o,r);else{let e=U.fromString(JSON.stringify(r));o.write(Zi.Object),os(o,e.byteLength),o.write(e)}}function ls(o){switch(o.read(1).readUInt8(0)){case 0:return;case 1:return o.read(is(o)).toString();case 2:return o.read(is(o)).buffer;case 3:return o.read(is(o));case 4:{let e=is(o),t=[];for(let n=0;n<e;n++)t.push(ls(o));return t}case 5:return JSON.parse(o.read(is(o)).toString());case 6:return is(o)}}var Ad=class{constructor(r,e,t=null,n=1e3){this.protocol=r;this.ctx=e;this.logger=t;this.timeoutDelay=n;this.channels=new Map;this.activeRequests=new Map;this.pendingRequests=new Map;this.protocolListener=this.protocol.onMessage(i=>this.onRawMessage(i)),this.sendResponse({type:200})}registerChannel(r,e){this.channels.set(r,e),setTimeout(()=>this.flushPendingRequests(r),0)}sendResponse(r){switch(r.type){case 200:{let e=this.send([r.type]);this.logger?.logOutgoing(e,0,1,Ld(r.type));return}case 201:case 202:case 204:case 203:{let e=this.send([r.type,r.id],r.data);this.logger?.logOutgoing(e,r.id,1,Ld(r.type),r.data);return}}}send(r,e=void 0){let t=new Md;return Ul(t,r),Ul(t,e),this.sendBuffer(t.buffer)}sendBuffer(r){try{return this.protocol.send(r),r.byteLength}catch{return 0}}onRawMessage(r){let e=new kl(r),t=ls(e),n=ls(e),i=t[0];switch(i){case 100:return this.logger?.logIncoming(r.byteLength,t[1],1,`${ss(i)}: ${t[2]}.${t[3]}`,n),this.onPromise({type:i,id:t[1],channelName:t[2],name:t[3],arg:n});case 102:return this.logger?.logIncoming(r.byteLength,t[1],1,`${ss(i)}: ${t[2]}.${t[3]}`,n),this.onEventListen({type:i,id:t[1],channelName:t[2],name:t[3],arg:n});case 101:return this.logger?.logIncoming(r.byteLength,t[1],1,`${ss(i)}`),this.disposeActiveRequest({type:i,id:t[1]});case 103:return this.logger?.logIncoming(r.byteLength,t[1],1,`${ss(i)}`),this.disposeActiveRequest({type:i,id:t[1]})}}onPromise(r){let e=this.channels.get(r.channelName);if(!e){this.collectPendingRequest(r);return}let t=new mt,n;try{n=e.call(this.ctx,r.name,r.arg,t.token)}catch(a){n=Promise.reject(a)}let i=r.id;n.then(a=>{this.sendResponse({id:i,data:a,type:201})},a=>{a instanceof Error?this.sendResponse({id:i,data:{message:a.message,name:a.name,stack:a.stack?a.stack.split(`
`):void 0},type:202}):this.sendResponse({id:i,data:a,type:203})}).finally(()=>{s.dispose(),this.activeRequests.delete(r.id)});let s=oe(()=>t.cancel());this.activeRequests.set(r.id,s)}onEventListen(r){let e=this.channels.get(r.channelName);if(!e){this.collectPendingRequest(r);return}let t=r.id,i=e.listen(this.ctx,r.name,r.arg)(s=>this.sendResponse({id:t,data:s,type:204}));this.activeRequests.set(r.id,i)}disposeActiveRequest(r){let e=this.activeRequests.get(r.id);e&&(e.dispose(),this.activeRequests.delete(r.id))}collectPendingRequest(r){let e=this.pendingRequests.get(r.channelName);e||(e=[],this.pendingRequests.set(r.channelName,e));let t=setTimeout(()=>{console.error(`Unknown channel: ${r.channelName}`),r.type===100&&this.sendResponse({id:r.id,data:{name:"Unknown channel",message:`Channel name '${r.channelName}' timed out after ${this.timeoutDelay}ms`,stack:void 0},type:202})},this.timeoutDelay);e.push({request:r,timeoutTimer:t})}flushPendingRequests(r){let e=this.pendingRequests.get(r);if(e){for(let t of e)switch(clearTimeout(t.timeoutTimer),t.request.type){case 100:this.onPromise(t.request);break;case 102:this.onEventListen(t.request);break}this.pendingRequests.delete(r)}}dispose(){this.protocolListener&&(this.protocolListener.dispose(),this.protocolListener=null),$t(this.activeRequests.values()),this.activeRequests.clear()}};var as=class{constructor(r,e=null){this.protocol=r;this.isDisposed=!1;this.state=0;this.activeRequests=new Set;this.handlers=new Map;this.lastRequestId=0;this._onDidInitialize=new w;this.onDidInitialize=this._onDidInitialize.event;this.protocolListener=this.protocol.onMessage(t=>this.onBuffer(t)),this.logger=e}getChannel(r){let e=this;return{call(t,n,i){return e.isDisposed?Promise.reject(new We):e.requestPromise(r,t,n,i)},listen(t,n){return e.isDisposed?k.None:e.requestEvent(r,t,n)}}}requestPromise(r,e,t,n=Y.None){let i=this.lastRequestId++,a={id:i,type:100,channelName:r,name:e,arg:t};if(n.isCancellationRequested)return Promise.reject(new We);let l,c;return new Promise((u,p)=>{if(n.isCancellationRequested)return p(new We);let m=()=>{let y=x=>{switch(x.type){case 201:this.handlers.delete(i),u(x.data);break;case 202:{this.handlers.delete(i);let E=new Error(x.data.message);E.stack=Array.isArray(x.data.stack)?x.data.stack.join(`
`):x.data.stack,E.name=x.data.name,p(E);break}case 203:this.handlers.delete(i),p(x.data);break}};this.handlers.set(i,y),this.sendRequest(a)},h=null;this.state===1?m():(h=Je(y=>this.whenInitialized()),h.then(()=>{h=null,m()}));let v=()=>{h?(h.cancel(),h=null):this.sendRequest({id:i,type:101}),p(new We)};l=n.onCancellationRequested(v),c={dispose:hl(()=>{v(),l.dispose()})},this.activeRequests.add(c)}).finally(()=>{l?.dispose(),this.activeRequests.delete(c)})}requestEvent(r,e,t){let n=this.lastRequestId++,s={id:n,type:102,channelName:r,name:e,arg:t},a=null,l=new w({onWillAddFirstListener:()=>{let d=()=>{this.activeRequests.add(l),this.sendRequest(s)};this.state===1?d():(a=Je(u=>this.whenInitialized()),a.then(()=>{a=null,d()}))},onDidRemoveLastListener:()=>{a?(a.cancel(),a=null):(this.activeRequests.delete(l),this.sendRequest({id:n,type:103})),this.handlers.delete(n)}}),c=d=>l.fire(d.data);return this.handlers.set(n,c),l.event}sendRequest(r){switch(r.type){case 100:case 102:{let e=this.send([r.type,r.id,r.channelName,r.name],r.arg);this.logger?.logOutgoing(e,r.id,0,`${ss(r.type)}: ${r.channelName}.${r.name}`,r.arg);return}case 101:case 103:{let e=this.send([r.type,r.id]);this.logger?.logOutgoing(e,r.id,0,ss(r.type));return}}}send(r,e=void 0){let t=new Md;return Ul(t,r),Ul(t,e),this.sendBuffer(t.buffer)}sendBuffer(r){try{return this.protocol.send(r),r.byteLength}catch{return 0}}onBuffer(r){let e=new kl(r),t=ls(e),n=ls(e),i=t[0];switch(i){case 200:return this.logger?.logIncoming(r.byteLength,0,0,Ld(i)),this.onResponse({type:t[0]});case 201:case 202:case 204:case 203:return this.logger?.logIncoming(r.byteLength,t[1],0,Ld(i),n),this.onResponse({type:t[0],id:t[1],data:n})}}onResponse(r){if(r.type===200){this.state=1,this._onDidInitialize.fire();return}this.handlers.get(r.id)?.(r)}get onDidInitializePromise(){return k.toPromise(this.onDidInitialize)}whenInitialized(){return this.state===1?Promise.resolve():this.onDidInitializePromise}dispose(){this.isDisposed=!0,this.protocolListener&&(this.protocolListener.dispose(),this.protocolListener=null),$t(this.activeRequests.values()),this.activeRequests.clear(),this._onDidInitialize.dispose()}};b([Ue],as.prototype,"onDidInitializePromise",1);var Ll=class{constructor(r,e,t){this.channels=new Map;this._connections=new Set;this._onDidAddConnection=new w;this.onDidAddConnection=this._onDidAddConnection.event;this._onDidRemoveConnection=new w;this.onDidRemoveConnection=this._onDidRemoveConnection.event;this.disposables=new se;this.disposables.add(r(({protocol:n,onDidClientDisconnect:i})=>{let s=k.once(n.onMessage);this.disposables.add(s(a=>{let l=new kl(a),c=ls(l),d=new Ad(n,c,e,t),u=new as(n,e);this.channels.forEach((m,h)=>d.registerChannel(h,m));let p={channelServer:d,channelClient:u,ctx:c};this._connections.add(p),this._onDidAddConnection.fire(p),this.disposables.add(i(()=>{d.dispose(),u.dispose(),this._connections.delete(p),this._onDidRemoveConnection.fire(p)}))}))}))}get connections(){let r=[];return this._connections.forEach(e=>r.push(e)),r}getChannel(r,e){let t=this;return{call(n,i,s){let a;if(gl(e)){let c=xy(t.connections.filter(e));a=c?Promise.resolve(c):k.toPromise(k.filter(t.onDidAddConnection,e))}else a=e.routeCall(t,n,i);let l=a.then(c=>c.channelClient.getChannel(r));return YS(l).call(n,i,s)},listen(n,i){if(gl(e))return t.getMulticastEvent(r,e,n,i);let s=e.routeEvent(t,n,i).then(a=>a.channelClient.getChannel(r));return YS(s).listen(n,i)}}}getMulticastEvent(r,e,t,n){let i=this,s,a=new w({onWillAddFirstListener:()=>{s=new se;let l=new fd,c=new Map,d=p=>{let h=p.channelClient.getChannel(r).listen(t,n),v=l.add(h);c.set(p,v)},u=p=>{let m=c.get(p);m&&(m.dispose(),c.delete(p))};i.connections.filter(e).forEach(d),k.filter(i.onDidAddConnection,e)(d,void 0,s),i.onDidRemoveConnection(u,void 0,s),l.event(a.fire,a,s),s.add(l)},onDidRemoveLastListener:()=>{s?.dispose(),s=void 0}});return i.disposables.add(a),a.event}registerChannel(r,e){this.channels.set(r,e);for(let t of this._connections)t.channelServer.registerChannel(r,e)}dispose(){this.disposables.dispose();for(let r of this._connections)r.channelClient.dispose(),r.channelServer.dispose();this._connections.clear(),this.channels.clear(),this._onDidAddConnection.dispose(),this._onDidRemoveConnection.dispose()}};function YS(o){return{call(r,e,t){return o.then(n=>n.call(r,e,t))},listen(r,e){let t=new wl;return o.then(n=>t.input=n.listen(r,e)),t.event}}}function ZS(o){let r=!1;return{call(e,t,n){return r?o.call(e,t,n):Lr(0).then(()=>r=!0).then(()=>o.call(e,t,n))},listen(e,t){if(r)return o.listen(e,t);let n=new wl;return Lr(0).then(()=>r=!0).then(()=>n.input=o.listen(e,t)),n.event}}}var Ml=class{constructor(r){this.fn=r}routeCall(r){return this.route(r)}routeEvent(r){return this.route(r)}async route(r){for(let e of r.connections)if(await Promise.resolve(this.fn(e.ctx)))return Promise.resolve(e);return await k.toPromise(r.onDidAddConnection),await this.route(r)}},Rt;(n=>{function o(i,s,a){let l=i,c=a?.disableMarshalling,d=new Map;for(let u in l)e(u)&&d.set(u,k.buffer(l[u],!0,void 0,s));return new class{listen(u,p,m){let h=d.get(p);if(h)return h;let v=l[p];if(typeof v=="function"){if(t(p))return v.call(l,m);if(e(p))return d.set(p,k.buffer(l[p],!0,void 0,s)),d.get(p)}throw new $r(`Event not found: ${p}`)}call(u,p,m){let h=l[p];if(typeof h=="function"){if(!c&&Array.isArray(m))for(let y=0;y<m.length;y++)m[y]=li(m[y]);let v=h.apply(l,m);return v instanceof Promise||(v=Promise.resolve(v)),v}throw new $r(`Method not found: ${p}`)}}}n.fromService=o;function r(i,s){let a=s?.disableMarshalling;return new Proxy({},{get(l,c){if(typeof c=="string")return s?.properties?.has(c)?s.properties.get(c):t(c)?function(d){return i.listen(c,d)}:e(c)?i.listen(c):async function(...d){let u;s&&!ft(s.context)?u=[s.context,...d]:u=d;let p=await i.call(c,u);return a?p:li(p)};throw new $r(`Property not found: ${String(c)}`)}})}n.toService=r;function e(i){return i[0]==="o"&&i[1]==="n"&&Lm(i.charCodeAt(2))}function t(i){return/^onDynamic/.test(i)&&Lm(i.charCodeAt(9))}})(Rt||={});function eI(o){return!!o.parentPort}var eg=class{constructor(r){this.port=r;this.onMessage=k.fromNodeEventEmitter(this.port,"message",e=>e.data?U.wrap(e.data):U.alloc(0)),r.start()}send(r){this.port.postMessage(r.buffer)}disconnect(){this.port.close()}},Fd=class o extends Ll{static getOnDidClientConnect(r){Dy(eI(process),"Electron Utility Process");let e=new w;return process.parentPort.on("message",t=>{if(r?.handledClientConnection(t))return;let n=t.ports.at(0);n&&e.fire(n)}),k.map(e.event,t=>({protocol:new eg(t),onDidClientDisconnect:k.fromNodeEventEmitter(t,"close")}))}constructor(r){super(o.getOnDidClientConnect(r))}};function tI(o,r,e){let t=n=>{n.data===r&&(o.removeListener("message",t),e())};o.on("message",t)}import{promises as Qw}from"fs";import*as ye from"fs";import{tmpdir as yw}from"os";import{promisify as Fl}from"util";var fw=new yn(1e4);function Al(o){return rI(o,"NFC",fw)}var mw=new yn(1e4);function gw(o){return rI(o,"NFD",mw)}var hw=/[^\u0000-\u0080]/;function rI(o,r,e){if(!o)return o;let t=e.get(o);if(t)return t;let n;return hw.test(o)?n=o.normalize(r):n=o,e.set(o,n),n}var vw=(function(){let o=new yn(1e4),r=/[\u0300-\u036f]/g;return function(e){let t=o.get(e);if(t)return t;let n=gw(e).replace(r,""),i=(n.length===e.length?n:e).toLowerCase();return o.set(e,i),i}})();async function oI(o,r=0,e){if(qm(o))throw new Error("rimraf - will refuse to recursively delete root");return r===0?tg(o):Sw(o,e)}async function Sw(o,r=PS(yw())){try{try{await ye.promises.rename(o,r)}catch(e){return e.code==="ENOENT"?void 0:tg(o)}tg(r).catch(()=>{})}catch(e){if(e.code!=="ENOENT")throw e}}async function tg(o){return ye.promises.rm(o,{recursive:!0,force:!0,maxRetries:3})}async function Od(o,r){try{return await nI(o,r)}catch(e){if(e.code==="ENOENT"&&he&&qm(o))try{return await nI(`${o}.`,r)}catch{}throw e}}async function nI(o,r){return bw(await(r?Iw(o):ye.promises.readdir(o)))}async function Iw(o){try{return await ye.promises.readdir(o,{withFileTypes:!0})}catch(t){t.code!=="ENOENT"&&console.warn("[node.js fs] readdir with filetypes failed with error: ",t)}let r=[],e=await Od(o);for(let t of e){let n=!1,i=!1,s=!1;try{let a=await ye.promises.lstat(G(o,t));n=a.isFile(),i=a.isDirectory(),s=a.isSymbolicLink()}catch(a){a.code!=="ENOENT"&&console.warn("[node.js fs] unexpected error from lstat after readdir: ",a)}r.push({name:t,isFile:()=>n,isDirectory:()=>i,isSymbolicLink:()=>s})}return r}function bw(o){return o.map(r=>typeof r=="string"?Gt?Al(r):r:(r.name=Gt?Al(r.name):r.name,r))}async function xw(o){let r=await Od(o),e=[];for(let t of r)await pr.existsDirectory(G(o,t))&&e.push(t);return e}var pr;(t=>{async function o(n){let i;try{if(i=await ye.promises.lstat(n),!i.isSymbolicLink())return{stat:i}}catch{}try{return{stat:await ye.promises.stat(n),symbolicLink:i?.isSymbolicLink()?{dangling:!1}:void 0}}catch(s){if(s.code==="ENOENT"&&i)return{stat:i,symbolicLink:{dangling:!0}};if(he&&s.code==="EACCES")try{return{stat:await ye.promises.stat(await ye.promises.readlink(n)),symbolicLink:{dangling:!1}}}catch(a){if(a.code==="ENOENT"&&i)return{stat:i,symbolicLink:{dangling:!0}};throw a}throw s}}t.stat=o;async function r(n){try{let{stat:i,symbolicLink:s}=await t.stat(n);return i.isFile()&&s?.dangling!==!0}catch{}return!1}t.existsFile=r;async function e(n){try{let{stat:i,symbolicLink:s}=await t.stat(n);return i.isDirectory()&&s?.dangling!==!0}catch{}return!1}t.existsDirectory=e})(pr||={});var Ew=new ts;function ww(o,r,e){return Ew.queueFor(P.file(o),()=>{let t=Tw(e);return new Promise((n,i)=>Rw(o,r,t,s=>s?i(s):n()))},Xi)}var sI=!0;function Pw(o){sI=o}function Rw(o,r,e,t){if(!sI)return ye.writeFile(o,r,{mode:e.mode,flag:e.flag},t);ye.open(o,e.flag,e.mode,(n,i)=>{if(n)return t(n);ye.writeFile(i,r,s=>{if(s)return ye.close(i,()=>t(s));ye.fdatasync(i,a=>(a&&(console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ",a),Pw(!1)),ye.close(i,l=>t(l))))})})}function Tw(o){return o?{mode:typeof o.mode=="number"?o.mode:438,flag:typeof o.flag=="string"?o.flag:"w"}:{mode:438,flag:"w"}}async function Cw(o,r,e=6e4){if(o!==r)try{he&&typeof e=="number"?await aI(o,r,Date.now(),e):await ye.promises.rename(o,r)}catch(t){if(o.toLowerCase()!==r.toLowerCase()&&t.code==="EXDEV"||o.endsWith("."))await lI(o,r,{preserveSymlinks:!1}),await oI(o,1);else throw t}}async function aI(o,r,e,t,n=0){try{return await ye.promises.rename(o,r)}catch(i){if(i.code!=="EACCES"&&i.code!=="EPERM"&&i.code!=="EBUSY")throw i;if(Date.now()-e>=t)throw console.error(`[node.js fs] rename failed after ${n} retries with error: ${i}`),i;if(n===0){let s=!1;try{let{stat:a}=await pr.stat(r);a.isFile()||(s=!0)}catch{}if(s)throw i}return await Lr(Math.min(100,n*10)),aI(o,r,e,t,n+1)}}async function lI(o,r,e){return cI(o,r,{root:{source:o,target:r},options:e,handledSourcePaths:new Set})}var iI=511;async function cI(o,r,e){if(e.handledSourcePaths.has(o))return;e.handledSourcePaths.add(o);let{stat:t,symbolicLink:n}=await pr.stat(o);if(n){if(e.options.preserveSymlinks)try{return await kw(o,r,e)}catch{}if(n.dangling)return}return t.isDirectory()?Dw(o,r,t.mode&iI,e):_w(o,r,t.mode&iI)}async function Dw(o,r,e,t){await ye.promises.mkdir(r,{recursive:!0,mode:e});let n=await Od(o);for(let i of n)await cI(G(o,i),G(r,i),t)}async function _w(o,r,e){await ye.promises.copyFile(o,r),await ye.promises.chmod(r,e)}async function kw(o,r,e){let t=await ye.promises.readlink(o);On(t,e.root.source,!Be)&&(t=G(e.root.target,t.substr(e.root.source.length+1))),await ye.promises.symlink(t,r)}async function Uw(o){try{return await Fl(ye.realpath)(o)}catch{let r=Lw(o);return await ye.promises.access(r,ye.constants.R_OK),r}}function Lw(o){return Qo(br(o),Ut)}var ce=new class{get read(){return(o,r,e,t,n)=>new Promise((i,s)=>{ye.read(o,r,e,t,n,(a,l,c)=>a?s(a):i({bytesRead:l,buffer:c}))})}get write(){return(o,r,e,t,n)=>new Promise((i,s)=>{ye.write(o,r,e,t,n,(a,l,c)=>a?s(a):i({bytesWritten:l,buffer:c}))})}get fdatasync(){return Fl(ye.fdatasync)}get open(){return Fl(ye.open)}get close(){return Fl(ye.close)}get ftruncate(){return Fl(ye.ftruncate)}async exists(o){try{return await ye.promises.access(o),!0}catch{return!1}}get readdir(){return Od}get readDirsInDir(){return xw}get writeFile(){return ww}get rm(){return oI}get rename(){return Cw}get copy(){return lI}get realpath(){return Uw}};function rn(o){return ig(o,0)}function ig(o,r){switch(typeof o){case"object":return o===null?Wn(349,r):Array.isArray(o)?Aw(o,r):Fw(o,r);case"string":return uI(o,r);case"boolean":return Mw(o,r);case"number":return Wn(o,r);case"undefined":return Wn(937,r);default:return Wn(617,r)}}function Wn(o,r){return(r<<5)-r+o|0}function Mw(o,r){return Wn(o?433:863,r)}function uI(o,r){r=Wn(149417,r);for(let e=0,t=o.length;e<t;e++)r=Wn(o.charCodeAt(e),r);return r}function Aw(o,r){return r=Wn(104579,r),o.reduce((e,t)=>ig(t,e),r)}function Fw(o,r){return r=Wn(181387,r),Object.keys(o).sort().reduce((e,t)=>(e=uI(t,e),ig(o[t],e)),r)}function ng(o,r,e=32){let t=e-r,n=~((1<<t)-1);return(o<<r|(n&o)>>>t)>>>0}function Ol(o,r=32){return o instanceof ArrayBuffer?JS(U.wrap(new Uint8Array(o))):(o>>>0).toString(16).padStart(r/4,"0")}var dI=class o{constructor(){this._h0=1732584193;this._h1=4023233417;this._h2=2562383102;this._h3=271733878;this._h4=3285377520;this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}static{this._bigBlock32=new DataView(new ArrayBuffer(320))}update(r){let e=r.length;if(e===0)return;let t=this._buff,n=this._buffLen,i=this._leftoverHighSurrogate,s,a;for(i!==0?(s=i,a=-1,i=0):(s=r.charCodeAt(0),a=0);;){let l=s;if(dS(s))if(a+1<e){let c=r.charCodeAt(a+1);Mm(c)?(a++,l=uS(s,c)):l=65533}else{i=s;break}else Mm(s)&&(l=65533);if(n=this._push(t,n,l),a++,a<e)s=r.charCodeAt(a);else break}this._buffLen=n,this._leftoverHighSurrogate=i}_push(r,e,t){return t<128?r[e++]=t:t<2048?(r[e++]=192|(t&1984)>>>6,r[e++]=128|(t&63)>>>0):t<65536?(r[e++]=224|(t&61440)>>>12,r[e++]=128|(t&4032)>>>6,r[e++]=128|(t&63)>>>0):(r[e++]=240|(t&1835008)>>>18,r[e++]=128|(t&258048)>>>12,r[e++]=128|(t&4032)>>>6,r[e++]=128|(t&63)>>>0),e>=64&&(this._step(),e-=64,this._totalLen+=64,r[0]=r[64],r[1]=r[65],r[2]=r[66]),e}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),Ol(this._h0)+Ol(this._h1)+Ol(this._h2)+Ol(this._h3)+Ol(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,this._buff.subarray(this._buffLen).fill(0),this._buffLen>56&&(this._step(),this._buff.fill(0));let r=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(r/4294967296),!1),this._buffDV.setUint32(60,r%4294967296,!1),this._step()}_step(){let r=o._bigBlock32,e=this._buffDV;for(let u=0;u<64;u+=4)r.setUint32(u,e.getUint32(u,!1),!1);for(let u=64;u<320;u+=4)r.setUint32(u,ng(r.getUint32(u-12,!1)^r.getUint32(u-32,!1)^r.getUint32(u-56,!1)^r.getUint32(u-64,!1),1),!1);let t=this._h0,n=this._h1,i=this._h2,s=this._h3,a=this._h4,l,c,d;for(let u=0;u<80;u++)u<20?(l=n&i|~n&s,c=1518500249):u<40?(l=n^i^s,c=1859775393):u<60?(l=n&i|n&s|i&s,c=2400959708):(l=n^i^s,c=3395469782),d=ng(t,5)+l+a+c+r.getUint32(u*4,!1)&4294967295,a=s,s=i,i=ng(n,30),n=t,t=d;this._h0=this._h0+t&4294967295,this._h1=this._h1+n&4294967295,this._h2=this._h2+i&4294967295,this._h3=this._h3+s&4294967295,this._h4=this._h4+a&4294967295}};function og(...o){switch(o.length){case 1:return S(1876,null,o[0]);case 2:return S(1877,null,o[0],o[1]);case 3:return S(1878,null,o[0],o[1],o[2]);default:return}}var Ow=S(1875,null),Nw=S(1874,null),di=class o{constructor(){this._input="";this._start=0;this._current=0;this._tokens=[];this._errors=[];this.stringRe=/[a-zA-Z0-9_<>\-\./\\:\*\?\+\[\]\^,#@;"%\$\p{L}-]+/uy}static getLexeme(r){switch(r.type){case 0:return"(";case 1:return")";case 2:return"!";case 3:return r.isTripleEq?"===":"==";case 4:return r.isTripleEq?"!==":"!=";case 5:return"<";case 6:return"<=";case 7:return">=";case 8:return">=";case 9:return"=~";case 10:return r.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 r.lexeme;case 18:return r.lexeme;case 19:return r.lexeme;case 20:return"EOF";default:throw Zc(`unhandled token type: ${JSON.stringify(r)}; have you forgotten to add a case?`)}}static{this._regexFlags=new Set(["i","g","s","m","y","u"].map(r=>r.charCodeAt(0)))}static{this._keywords=new Map([["not",14],["in",13],["false",12],["true",11]])}get errors(){return this._errors}reset(r){return this._input=r,this._start=0,this._current=0,this._tokens=[],this._errors=[],this}scan(){for(;!this._isAtEnd();)switch(this._start=this._current,this._advance()){case 40:this._addToken(0);break;case 41:this._addToken(1);break;case 33:if(this._match(61)){let e=this._match(61);this._tokens.push({type:4,offset:this._start,isTripleEq:e})}else this._addToken(2);break;case 39:this._quotedString();break;case 47:this._regex();break;case 61:if(this._match(61)){let e=this._match(61);this._tokens.push({type:3,offset:this._start,isTripleEq:e})}else this._match(126)?this._addToken(9):this._error(og("==","=~"));break;case 60:this._addToken(this._match(61)?6:5);break;case 62:this._addToken(this._match(61)?8:7);break;case 38:this._match(38)?this._addToken(15):this._error(og("&&"));break;case 124:this._match(124)?this._addToken(16):this._error(og("||"));break;case 32:case 13:case 9:case 10:case 160:break;default:this._string()}return this._start=this._current,this._addToken(20),Array.from(this._tokens)}_match(r){return this._isAtEnd()||this._input.charCodeAt(this._current)!==r?!1:(this._current++,!0)}_advance(){return this._input.charCodeAt(this._current++)}_peek(){return this._isAtEnd()?0:this._input.charCodeAt(this._current)}_addToken(r){this._tokens.push({type:r,offset:this._start})}_error(r){let e=this._start,t=this._input.substring(this._start,this._current),n={type:19,offset:this._start,lexeme:t};this._errors.push({offset:e,lexeme:t,additionalInfo:r}),this._tokens.push(n)}_string(){this.stringRe.lastIndex=this._start;let r=this.stringRe.exec(this._input);if(r){this._current=this._start+r[0].length;let e=this._input.substring(this._start,this._current),t=o._keywords.get(e);t?this._addToken(t):this._tokens.push({type:17,lexeme:e,offset:this._start})}}_quotedString(){for(;this._peek()!==39&&!this._isAtEnd();)this._advance();if(this._isAtEnd()){this._error(Ow);return}this._advance(),this._tokens.push({type:18,lexeme:this._input.substring(this._start+1,this._current-1),offset:this._start+1})}_regex(){let r=this._current,e=!1,t=!1;for(;;){if(r>=this._input.length){this._current=r,this._error(Nw);return}let i=this._input.charCodeAt(r);if(e)e=!1;else if(i===47&&!t){r++;break}else i===91?t=!0:i===92?e=!0:i===93&&(t=!1);r++}for(;r<this._input.length&&o._regexFlags.has(this._input.charCodeAt(r));)r++;this._current=r;let n=this._input.substring(this._start,this._current);this._tokens.push({type:10,lexeme:n,offset:this._start})}_isAtEnd(){return this._current>=this._input.length}};var nn;(n=>{n.serviceIds=new Map,n.DI_TARGET="$di$target",n.DI_DEPENDENCIES="$di$dependencies";function t(i){return i[n.DI_DEPENDENCIES]||[]}n.getServiceDependencies=t})(nn||={});var bt=L("instantiationService");function Vw(o,r,e){r[nn.DI_TARGET]===r?r[nn.DI_DEPENDENCIES].push({id:o,index:e}):(r[nn.DI_DEPENDENCIES]=[{id:o,index:e}],r[nn.DI_TARGET]=r)}function L(o){if(nn.serviceIds.has(o))return nn.serviceIds.get(o);let r=function(e,t,n){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Vw(r,e,n)};return r.toString=()=>o,nn.serviceIds.set(o,r),r}var Mt=new Map;Mt.set("false",!1);Mt.set("true",!0);Mt.set("isMac",Gt);Mt.set("isLinux",Be);Mt.set("isWindows",he);Mt.set("isWeb",ze);Mt.set("isMacNative",Gt&&!ze);Mt.set("isEdge",pd);Mt.set("isFirefox",dd);Mt.set("isChrome",xl);Mt.set("isSafari",ud);var Ww=Object.prototype.hasOwnProperty;var Bw={regexParsingWithErrorRecovery:!0},$w=S(1855,null),Gw=S(1856,null),qw=S(1858,null),pI=S(1854,null),zw=S(1861,null),Kw=S(1862,null),jw=S(1859,null),Hw=S(1860,null),sg=class o{constructor(r=Bw){this._config=r;this._scanner=new di;this._tokens=[];this._current=0;this._parsingErrors=[];this._flagsGYRe=/g|y/g}static{this._parseError=new Error}get lexingErrors(){return this._scanner.errors}get parsingErrors(){return this._parsingErrors}parse(r){if(r===""){this._parsingErrors.push({message:$w,offset:0,lexeme:"",additionalInfo:Gw});return}this._tokens=this._scanner.reset(r).scan(),this._current=0,this._parsingErrors=[];try{let e=this._expr();if(!this._isAtEnd()){let t=this._peek(),n=t.type===17?Kw:void 0;throw this._parsingErrors.push({message:zw,offset:t.offset,lexeme:di.getLexeme(t),additionalInfo:n}),o._parseError}return e}catch(e){if(e!==o._parseError)throw e;return}}_expr(){return this._or()}_or(){let r=[this._and()];for(;this._matchOne(16);){let e=this._and();r.push(e)}return r.length===1?r[0]:Tt.or(...r)}_and(){let r=[this._term()];for(;this._matchOne(15);){let e=this._term();r.push(e)}return r.length===1?r[0]:Tt.and(...r)}_term(){if(this._matchOne(2)){let r=this._peek();switch(r.type){case 11:return this._advance(),Jt.INSTANCE;case 12:return this._advance(),er.INSTANCE;case 0:{this._advance();let e=this._expr();return this._consume(1,pI),e?.negate()}case 17:return this._advance(),to.create(r.lexeme);default:throw this._errExpectedButGot("KEY | true | false | '(' expression ')'",r)}}return this._primary()}_primary(){let r=this._peek();switch(r.type){case 11:return this._advance(),Tt.true();case 12:return this._advance(),Tt.false();case 0:{this._advance();let e=this._expr();return this._consume(1,pI),e}case 17:{let e=r.lexeme;if(this._advance(),this._matchOne(9)){let n=this._peek();if(!this._config.regexParsingWithErrorRecovery){if(this._advance(),n.type!==10)throw this._errExpectedButGot("REGEX",n);let i=n.lexeme,s=i.lastIndexOf("/"),a=s===i.length-1?void 0:this._removeFlagsGY(i.substring(s+1)),l;try{l=new RegExp(i.substring(1,s),a)}catch{throw this._errExpectedButGot("REGEX",n)}return ql.create(e,l)}switch(n.type){case 10:case 19:{let i=[n.lexeme];this._advance();let s=this._peek(),a=0;for(let p=0;p<n.lexeme.length;p++)n.lexeme.charCodeAt(p)===40?a++:n.lexeme.charCodeAt(p)===41&&a--;for(;!this._isAtEnd()&&s.type!==15&&s.type!==16;){switch(s.type){case 0:a++;break;case 1:a--;break;case 10:case 18:for(let p=0;p<s.lexeme.length;p++)s.lexeme.charCodeAt(p)===40?a++:n.lexeme.charCodeAt(p)===41&&a--}if(a<0)break;i.push(di.getLexeme(s)),this._advance(),s=this._peek()}let l=i.join(""),c=l.lastIndexOf("/"),d=c===l.length-1?void 0:this._removeFlagsGY(l.substring(c+1)),u;try{u=new RegExp(l.substring(1,c),d)}catch{throw this._errExpectedButGot("REGEX",n)}return Tt.regex(e,u)}case 18:{let i=n.lexeme;this._advance();let s=null;if(!aS(i)){let a=i.indexOf("/"),l=i.lastIndexOf("/");if(a!==l&&a>=0){let c=i.slice(a+1,l),d=i[l+1]==="i"?"i":"";try{s=new RegExp(c,d)}catch{throw this._errExpectedButGot("REGEX",n)}}}if(s===null)throw this._errExpectedButGot("REGEX",n);return ql.create(e,s)}default:throw this._errExpectedButGot("REGEX",this._peek())}}if(this._matchOne(14)){this._consume(13,qw);let n=this._value();return Tt.notIn(e,n)}switch(this._peek().type){case 3:{this._advance();let n=this._value();if(this._previous().type===18)return Tt.equals(e,n);switch(n){case"true":return Tt.has(e);case"false":return Tt.not(e);default:return Tt.equals(e,n)}}case 4:{this._advance();let n=this._value();if(this._previous().type===18)return Tt.notEquals(e,n);switch(n){case"true":return Tt.not(e);case"false":return Tt.has(e);default:return Tt.notEquals(e,n)}}case 5:return this._advance(),$l.create(e,this._value());case 6:return this._advance(),Gl.create(e,this._value());case 7:return this._advance(),cs.create(e,this._value());case 8:return this._advance(),Bl.create(e,this._value());case 13:return this._advance(),Tt.in(e,this._value());default:return Tt.has(e)}}case 20:throw this._parsingErrors.push({message:jw,offset:r.offset,lexeme:"",additionalInfo:Hw}),o._parseError;default:throw this._errExpectedButGot(`true | false | KEY 
	| KEY '=~' REGEX 
	| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`,this._peek())}}_value(){let r=this._peek();switch(r.type){case 17:case 18:return this._advance(),r.lexeme;case 11:return this._advance(),"true";case 12:return this._advance(),"false";case 13:return this._advance(),"in";default:return""}}_removeFlagsGY(r){return r.replaceAll(this._flagsGYRe,"")}_previous(){return this._tokens[this._current-1]}_matchOne(r){return this._check(r)?(this._advance(),!0):!1}_advance(){return this._isAtEnd()||this._current++,this._previous()}_consume(r,e){if(this._check(r))return this._advance();throw this._errExpectedButGot(e,this._peek())}_errExpectedButGot(r,e,t){let n=S(1857,null,r,di.getLexeme(e)),i=e.offset,s=di.getLexeme(e);return this._parsingErrors.push({message:n,offset:i,lexeme:s,additionalInfo:t}),o._parseError}_check(r){return this._peek().type===r}_peek(){return this._tokens[this._current]}_isAtEnd(){return this._peek().type===20}},Tt=class{static false(){return Jt.INSTANCE}static true(){return er.INSTANCE}static has(r){return eo.create(r)}static equals(r,e){return Vl.create(r,e)}static notEquals(r,e){return Wl.create(r,e)}static regex(r,e){return ql.create(r,e)}static in(r,e){return Nd.create(r,e)}static notIn(r,e){return Vd.create(r,e)}static not(r){return to.create(r)}static and(...r){return Wd.create(r,null,!0)}static or(...r){return zl.create(r,null,!0)}static greater(r,e){return cs.create(r,e)}static greaterEquals(r,e){return Bl.create(r,e)}static smaller(r,e){return $l.create(r,e)}static smallerEquals(r,e){return Gl.create(r,e)}static{this._parser=new sg({regexParsingWithErrorRecovery:!1})}static deserialize(r){return r==null?void 0:this._parser.parse(r)}};function Nl(o,r){return o.cmp(r)}var Jt=class o{constructor(){this.type=0}static{this.INSTANCE=new o}cmp(r){return this.type-r.type}equals(r){return r.type===this.type}substituteConstants(){return this}evaluate(r){return!1}serialize(){return"false"}keys(){return[]}map(r){return this}negate(){return er.INSTANCE}},er=class o{constructor(){this.type=1}static{this.INSTANCE=new o}cmp(r){return this.type-r.type}equals(r){return r.type===this.type}substituteConstants(){return this}evaluate(r){return!0}serialize(){return"true"}keys(){return[]}map(r){return this}negate(){return Jt.INSTANCE}},eo=class o{constructor(r,e){this.key=r;this.negated=e;this.type=2}static create(r,e=null){let t=Mt.get(r);return typeof t=="boolean"?t?er.INSTANCE:Jt.INSTANCE:new o(r,e)}cmp(r){return r.type!==this.type?this.type-r.type:gI(this.key,r.key)}equals(r){return r.type===this.type?this.key===r.key:!1}substituteConstants(){let r=Mt.get(this.key);return typeof r=="boolean"?r?er.INSTANCE:Jt.INSTANCE:this}evaluate(r){return!!r.getValue(this.key)}serialize(){return this.key}keys(){return[this.key]}map(r){return r.mapDefined(this.key)}negate(){return this.negated||(this.negated=to.create(this.key,this)),this.negated}},Vl=class o{constructor(r,e,t){this.key=r;this.value=e;this.negated=t;this.type=4}static create(r,e,t=null){if(typeof e=="boolean")return e?eo.create(r,t):to.create(r,t);let n=Mt.get(r);return typeof n=="boolean"?e===(n?"true":"false")?er.INSTANCE:Jt.INSTANCE:new o(r,e,t)}cmp(r){return r.type!==this.type?this.type-r.type:ro(this.key,this.value,r.key,r.value)}equals(r){return r.type===this.type?this.key===r.key&&this.value===r.value:!1}substituteConstants(){let r=Mt.get(this.key);if(typeof r=="boolean"){let e=r?"true":"false";return this.value===e?er.INSTANCE:Jt.INSTANCE}return this}evaluate(r){return r.getValue(this.key)==this.value}serialize(){return`${this.key} == '${this.value}'`}keys(){return[this.key]}map(r){return r.mapEquals(this.key,this.value)}negate(){return this.negated||(this.negated=Wl.create(this.key,this.value,this)),this.negated}},Nd=class o{constructor(r,e){this.key=r;this.valueKey=e;this.type=10;this.negated=null}static create(r,e){return new o(r,e)}cmp(r){return r.type!==this.type?this.type-r.type:ro(this.key,this.valueKey,r.key,r.valueKey)}equals(r){return r.type===this.type?this.key===r.key&&this.valueKey===r.valueKey:!1}substituteConstants(){return this}evaluate(r){let e=r.getValue(this.valueKey),t=r.getValue(this.key);if(Array.isArray(e)){if(e.includes(t))return!0;if(he&&typeof t=="string"&&t.startsWith("file:///")){let n=t.toLowerCase();return e.some(i=>typeof i=="string"&&i.toLowerCase()===n)}return!1}if(typeof t=="string"&&typeof e=="object"&&e!==null){if(Ww.call(e,t))return!0;if(he&&t.startsWith("file:///")){let n=t.toLowerCase();return Object.keys(e).some(i=>i.toLowerCase()===n)}return!1}return!1}serialize(){return`${this.key} in '${this.valueKey}'`}keys(){return[this.key,this.valueKey]}map(r){return r.mapIn(this.key,this.valueKey)}negate(){return this.negated||(this.negated=Vd.create(this.key,this.valueKey)),this.negated}},Vd=class o{constructor(r,e){this.key=r;this.valueKey=e;this.type=11;this._negated=Nd.create(r,e)}static create(r,e){return new o(r,e)}cmp(r){return r.type!==this.type?this.type-r.type:this._negated.cmp(r._negated)}equals(r){return r.type===this.type?this._negated.equals(r._negated):!1}substituteConstants(){return this}evaluate(r){return!this._negated.evaluate(r)}serialize(){return`${this.key} not in '${this.valueKey}'`}keys(){return this._negated.keys()}map(r){return r.mapNotIn(this.key,this.valueKey)}negate(){return this._negated}},Wl=class o{constructor(r,e,t){this.key=r;this.value=e;this.negated=t;this.type=5}static create(r,e,t=null){if(typeof e=="boolean")return e?to.create(r,t):eo.create(r,t);let n=Mt.get(r);return typeof n=="boolean"?e===(n?"true":"false")?Jt.INSTANCE:er.INSTANCE:new o(r,e,t)}cmp(r){return r.type!==this.type?this.type-r.type:ro(this.key,this.value,r.key,r.value)}equals(r){return r.type===this.type?this.key===r.key&&this.value===r.value:!1}substituteConstants(){let r=Mt.get(this.key);if(typeof r=="boolean"){let e=r?"true":"false";return this.value===e?Jt.INSTANCE:er.INSTANCE}return this}evaluate(r){return r.getValue(this.key)!=this.value}serialize(){return`${this.key} != '${this.value}'`}keys(){return[this.key]}map(r){return r.mapNotEquals(this.key,this.value)}negate(){return this.negated||(this.negated=Vl.create(this.key,this.value,this)),this.negated}},to=class o{constructor(r,e){this.key=r;this.negated=e;this.type=3}static create(r,e=null){let t=Mt.get(r);return typeof t=="boolean"?t?Jt.INSTANCE:er.INSTANCE:new o(r,e)}cmp(r){return r.type!==this.type?this.type-r.type:gI(this.key,r.key)}equals(r){return r.type===this.type?this.key===r.key:!1}substituteConstants(){let r=Mt.get(this.key);return typeof r=="boolean"?r?Jt.INSTANCE:er.INSTANCE:this}evaluate(r){return!r.getValue(this.key)}serialize(){return`!${this.key}`}keys(){return[this.key]}map(r){return r.mapNot(this.key)}negate(){return this.negated||(this.negated=eo.create(this.key,this)),this.negated}};function $d(o,r){if(typeof o=="string"){let e=parseFloat(o);isNaN(e)||(o=e)}return typeof o=="string"||typeof o=="number"?r(o):Jt.INSTANCE}var cs=class o{constructor(r,e,t){this.key=r;this.value=e;this.negated=t;this.type=12}static create(r,e,t=null){return $d(e,n=>new o(r,n,t))}cmp(r){return r.type!==this.type?this.type-r.type:ro(this.key,this.value,r.key,r.value)}equals(r){return r.type===this.type?this.key===r.key&&this.value===r.value:!1}substituteConstants(){return this}evaluate(r){return typeof this.value=="string"?!1:parseFloat(r.getValue(this.key))>this.value}serialize(){return`${this.key} > ${this.value}`}keys(){return[this.key]}map(r){return r.mapGreater(this.key,this.value)}negate(){return this.negated||(this.negated=Gl.create(this.key,this.value,this)),this.negated}},Bl=class o{constructor(r,e,t){this.key=r;this.value=e;this.negated=t;this.type=13}static create(r,e,t=null){return $d(e,n=>new o(r,n,t))}cmp(r){return r.type!==this.type?this.type-r.type:ro(this.key,this.value,r.key,r.value)}equals(r){return r.type===this.type?this.key===r.key&&this.value===r.value:!1}substituteConstants(){return this}evaluate(r){return typeof this.value=="string"?!1:parseFloat(r.getValue(this.key))>=this.value}serialize(){return`${this.key} >= ${this.value}`}keys(){return[this.key]}map(r){return r.mapGreaterEquals(this.key,this.value)}negate(){return this.negated||(this.negated=$l.create(this.key,this.value,this)),this.negated}},$l=class o{constructor(r,e,t){this.key=r;this.value=e;this.negated=t;this.type=14}static create(r,e,t=null){return $d(e,n=>new o(r,n,t))}cmp(r){return r.type!==this.type?this.type-r.type:ro(this.key,this.value,r.key,r.value)}equals(r){return r.type===this.type?this.key===r.key&&this.value===r.value:!1}substituteConstants(){return this}evaluate(r){return typeof this.value=="string"?!1:parseFloat(r.getValue(this.key))<this.value}serialize(){return`${this.key} < ${this.value}`}keys(){return[this.key]}map(r){return r.mapSmaller(this.key,this.value)}negate(){return this.negated||(this.negated=Bl.create(this.key,this.value,this)),this.negated}},Gl=class o{constructor(r,e,t){this.key=r;this.value=e;this.negated=t;this.type=15}static create(r,e,t=null){return $d(e,n=>new o(r,n,t))}cmp(r){return r.type!==this.type?this.type-r.type:ro(this.key,this.value,r.key,r.value)}equals(r){return r.type===this.type?this.key===r.key&&this.value===r.value:!1}substituteConstants(){return this}evaluate(r){return typeof this.value=="string"?!1:parseFloat(r.getValue(this.key))<=this.value}serialize(){return`${this.key} <= ${this.value}`}keys(){return[this.key]}map(r){return r.mapSmallerEquals(this.key,this.value)}negate(){return this.negated||(this.negated=cs.create(this.key,this.value,this)),this.negated}},ql=class o{constructor(r,e){this.key=r;this.regexp=e;this.type=7;this.negated=null}static create(r,e){return new o(r,e)}cmp(r){if(r.type!==this.type)return this.type-r.type;if(this.key<r.key)return-1;if(this.key>r.key)return 1;let e=this.regexp?this.regexp.source:"",t=r.regexp?r.regexp.source:"";return e<t?-1:e>t?1:0}equals(r){if(r.type===this.type){let e=this.regexp?this.regexp.source:"",t=r.regexp?r.regexp.source:"";return this.key===r.key&&e===t}return!1}substituteConstants(){return this}evaluate(r){let e=r.getValue(this.key);return this.regexp?this.regexp.test(e):!1}serialize(){let r=this.regexp?`/${this.regexp.source}/${this.regexp.flags}`:"/invalid/";return`${this.key} =~ ${r}`}keys(){return[this.key]}map(r){return r.mapRegex(this.key,this.regexp)}negate(){return this.negated||(this.negated=ag.create(this)),this.negated}},ag=class o{constructor(r){this._actual=r;this.type=8}static create(r){return new o(r)}cmp(r){return r.type!==this.type?this.type-r.type:this._actual.cmp(r._actual)}equals(r){return r.type===this.type?this._actual.equals(r._actual):!1}substituteConstants(){return this}evaluate(r){return!this._actual.evaluate(r)}serialize(){return`!(${this._actual.serialize()})`}keys(){return this._actual.keys()}map(r){return new o(this._actual.map(r))}negate(){return this._actual}};function mI(o){let r=null;for(let e=0,t=o.length;e<t;e++){let n=o[e].substituteConstants();if(o[e]!==n&&r===null){r=[];for(let i=0;i<e;i++)r[i]=o[i]}r!==null&&(r[e]=n)}return r===null?o:r}var Wd=class o{constructor(r,e){this.expr=r;this.negated=e;this.type=6}static create(r,e,t){return o._normalizeArr(r,e,t)}cmp(r){if(r.type!==this.type)return this.type-r.type;if(this.expr.length<r.expr.length)return-1;if(this.expr.length>r.expr.length)return 1;for(let e=0,t=this.expr.length;e<t;e++){let n=Nl(this.expr[e],r.expr[e]);if(n!==0)return n}return 0}equals(r){if(r.type===this.type){if(this.expr.length!==r.expr.length)return!1;for(let e=0,t=this.expr.length;e<t;e++)if(!this.expr[e].equals(r.expr[e]))return!1;return!0}return!1}substituteConstants(){let r=mI(this.expr);return r===this.expr?this:o.create(r,this.negated,!1)}evaluate(r){for(let e=0,t=this.expr.length;e<t;e++)if(!this.expr[e].evaluate(r))return!1;return!0}static _normalizeArr(r,e,t){let n=[],i=!1;for(let s of r)if(s){if(s.type===1){i=!0;continue}if(s.type===0)return Jt.INSTANCE;if(s.type===6){n.push(...s.expr);continue}n.push(s)}if(n.length===0&&i)return er.INSTANCE;if(n.length!==0){if(n.length===1)return n[0];n.sort(Nl);for(let s=1;s<n.length;s++)n[s-1].equals(n[s])&&(n.splice(s,1),s--);if(n.length===1)return n[0];for(;n.length>1;){let s=n[n.length-1];if(s.type!==9)break;n.pop();let a=n.pop(),l=n.length===0,c=zl.create(s.expr.map(d=>o.create([d,a],null,t)),null,l);c&&(n.push(c),n.sort(Nl))}if(n.length===1)return n[0];if(t){for(let s=0;s<n.length;s++)for(let a=s+1;a<n.length;a++)if(n[s].negate().equals(n[a]))return Jt.INSTANCE;if(n.length===1)return n[0]}return new o(n,e)}}serialize(){return this.expr.map(r=>r.serialize()).join(" && ")}keys(){let r=[];for(let e of this.expr)r.push(...e.keys());return r}map(r){return new o(this.expr.map(e=>e.map(r)),null)}negate(){if(!this.negated){let r=[];for(let e of this.expr)r.push(e.negate());this.negated=zl.create(r,this,!0)}return this.negated}},zl=class o{constructor(r,e){this.expr=r;this.negated=e;this.type=9}static create(r,e,t){return o._normalizeArr(r,e,t)}cmp(r){if(r.type!==this.type)return this.type-r.type;if(this.expr.length<r.expr.length)return-1;if(this.expr.length>r.expr.length)return 1;for(let e=0,t=this.expr.length;e<t;e++){let n=Nl(this.expr[e],r.expr[e]);if(n!==0)return n}return 0}equals(r){if(r.type===this.type){if(this.expr.length!==r.expr.length)return!1;for(let e=0,t=this.expr.length;e<t;e++)if(!this.expr[e].equals(r.expr[e]))return!1;return!0}return!1}substituteConstants(){let r=mI(this.expr);return r===this.expr?this:o.create(r,this.negated,!1)}evaluate(r){for(let e=0,t=this.expr.length;e<t;e++)if(this.expr[e].evaluate(r))return!0;return!1}static _normalizeArr(r,e,t){let n=[],i=!1;if(r){for(let s=0,a=r.length;s<a;s++){let l=r[s];if(l){if(l.type===0){i=!0;continue}if(l.type===1)return er.INSTANCE;if(l.type===9){n=n.concat(l.expr);continue}n.push(l)}}if(n.length===0&&i)return Jt.INSTANCE;n.sort(Nl)}if(n.length!==0){if(n.length===1)return n[0];for(let s=1;s<n.length;s++)n[s-1].equals(n[s])&&(n.splice(s,1),s--);if(n.length===1)return n[0];if(t){for(let s=0;s<n.length;s++)for(let a=s+1;a<n.length;a++)if(n[s].negate().equals(n[a]))return er.INSTANCE;if(n.length===1)return n[0]}return new o(n,e)}}serialize(){return this.expr.map(r=>r.serialize()).join(" || ")}keys(){let r=[];for(let e of this.expr)r.push(...e.keys());return r}map(r){return new o(this.expr.map(e=>e.map(r)),null)}negate(){if(!this.negated){let r=[];for(let e of this.expr)r.push(e.negate());for(;r.length>1;){let e=r.shift(),t=r.shift(),n=[];for(let i of fI(e))for(let s of fI(t))n.push(Wd.create([i,s],null,!1));r.unshift(o.create(n,null,!1))}this.negated=o.create(r,this,!0)}return this.negated}},Bd=class o extends eo{static{this._info=[]}static all(){return o._info.values()}constructor(r,e,t){super(r,null),this._defaultValue=e,typeof t=="object"?o._info.push({...t,key:r}):t!==!0&&o._info.push({key:r,description:t,type:e!=null?typeof e:void 0})}bindTo(r){return r.createKey(this.key,this._defaultValue)}getValue(r){return r.getContextKeyValue(this.key)}toNegated(){return this.negate()}isEqualTo(r){return Vl.create(this.key,r)}notEqualsTo(r){return Wl.create(this.key,r)}greater(r){return cs.create(this.key,r)}},qk=L("contextKeyService");function gI(o,r){return o<r?-1:o>r?1:0}function ro(o,r,e,t){return o<e?-1:o>e?1:r<t?-1:r>t?1:0}function fI(o){return o.type===9?o.expr:[o]}var V=L("logService"),wn=L("loggerService");function hI(o){return Un(o)}var cg=3;function Jw(o,r){return o!==0&&o<=r}function ds(o,r=!1){let e="";for(let t=0;t<o.length;t++){let n=o[t];if(n instanceof Error&&(n=_t(n,r)),typeof n=="object")try{n=JSON.stringify(n)}catch{}e+=(t>0?" ":"")+n}return e}var ui=class extends T{constructor(){super(...arguments);this.level=cg;this._onDidChangeLogLevel=this._register(new w)}get onDidChangeLogLevel(){return this._onDidChangeLogLevel.event}setLevel(e){this.level!==e&&(this.level=e,this._onDidChangeLogLevel.fire(this.level))}getLevel(){return this.level}checkLogLevel(e){return Jw(this.level,e)}canLog(e){return this._store.isDisposed?!1:this.checkLogLevel(e)}},Gd=class extends ui{constructor(e){super();this.logAlways=e}checkLogLevel(e){return this.logAlways||super.checkLogLevel(e)}trace(e,...t){this.canLog(1)&&this.log(1,ds([e,...t],!0))}debug(e,...t){this.canLog(2)&&this.log(2,ds([e,...t]))}info(e,...t){this.canLog(3)&&this.log(3,ds([e,...t]))}warn(e,...t){this.canLog(4)&&this.log(4,ds([e,...t]))}error(e,...t){if(this.canLog(5))if(e instanceof Error){let n=Array.prototype.slice.call(arguments);n[0]=e.stack,this.log(5,ds(n))}else this.log(5,ds([e,...t]))}flush(){}};var qd=class extends ui{constructor(e=cg,t=!0){super();this.useColors=t;this.setLevel(e)}trace(e,...t){this.canLog(1)&&(this.useColors?console.log("%cTRACE","color: #888",e,...t):console.log(e,...t))}debug(e,...t){this.canLog(2)&&(this.useColors?console.log("%cDEBUG","background: #eee; color: #888",e,...t):console.log(e,...t))}info(e,...t){this.canLog(3)&&(this.useColors?console.log("%c INFO","color: #33f",e,...t):console.log(e,...t))}warn(e,...t){this.canLog(4)&&(this.useColors?console.warn("%c WARN","color: #993",e,...t):console.log(e,...t))}error(e,...t){this.canLog(5)&&(this.useColors?console.error("%c  ERR","color: #f33",e,...t):console.error(e,...t))}flush(){}},zd=class extends ui{constructor(e,t=cg){super();this.adapter=e;this.setLevel(t)}trace(e,...t){this.canLog(1)&&this.adapter.log(1,[this.extractMessage(e),...t])}debug(e,...t){this.canLog(2)&&this.adapter.log(2,[this.extractMessage(e),...t])}info(e,...t){this.canLog(3)&&this.adapter.log(3,[this.extractMessage(e),...t])}warn(e,...t){this.canLog(4)&&this.adapter.log(4,[this.extractMessage(e),...t])}error(e,...t){this.canLog(5)&&this.adapter.log(5,[this.extractMessage(e),...t])}extractMessage(e){return typeof e=="string"?e:_t(e,this.canLog(1))}flush(){}},Kd=class extends ui{constructor(e){super();this.loggers=e;e.length&&this.setLevel(e[0].getLevel())}setLevel(e){for(let t of this.loggers)t.setLevel(e);super.setLevel(e)}trace(e,...t){for(let n of this.loggers)n.trace(e,...t)}debug(e,...t){for(let n of this.loggers)n.debug(e,...t)}info(e,...t){for(let n of this.loggers)n.info(e,...t)}warn(e,...t){for(let n of this.loggers)n.warn(e,...t)}error(e,...t){for(let n of this.loggers)n.error(e,...t)}flush(){for(let e of this.loggers)e.flush()}dispose(){for(let e of this.loggers)e.dispose();super.dispose()}},jd=class extends T{constructor(e,t,n){super();this.logLevel=e;this.logsHome=t;this._loggers=new He;this._onDidChangeLoggers=this._register(new w);this.onDidChangeLoggers=this._onDidChangeLoggers.event;this._onDidChangeLogLevel=this._register(new w);this.onDidChangeLogLevel=this._onDidChangeLogLevel.event;this._onDidChangeVisibility=this._register(new w);this.onDidChangeVisibility=this._onDidChangeVisibility.event;if(n)for(let i of n)this._loggers.set(i.resource,{logger:void 0,info:i})}getLoggerEntry(e){return ue(e)?[...this._loggers.values()].find(t=>t.info.id===e):this._loggers.get(e)}getLogger(e){return this.getLoggerEntry(e)?.logger}createLogger(e,t){let n=this.toResource(e),i=ue(e)?e:t?.id??rn(n.toString()).toString(16),s=this._loggers.get(n)?.logger,a=t?.logLevel==="always"?1:t?.logLevel;s||(s=this.doCreateLogger(n,a??this.getLogLevel(n)??this.logLevel,{...t,id:i}));let l={logger:s,info:{resource:n,id:i,logLevel:a,name:t?.name,hidden:t?.hidden,group:t?.group,extensionId:t?.extensionId,when:t?.when}};return this.registerLogger(l.info),this._loggers.set(n,l),s}toResource(e){return ue(e)?$(this.logsHome,`${e.replace(/[\\/:\*\?"<>\|]/g,"")}.log`):e}setLogLevel(e,t){if(P.isUri(e)){let n=e,i=t,s=this._loggers.get(n);s&&i!==s.info.logLevel&&(s.info.logLevel=i===this.logLevel?void 0:i,s.logger?.setLevel(i),this._loggers.set(s.info.resource,s),this._onDidChangeLogLevel.fire([n,i]))}else{this.logLevel=e;for(let[n,i]of this._loggers.entries())this._loggers.get(n)?.info.logLevel===void 0&&i.logger?.setLevel(this.logLevel);this._onDidChangeLogLevel.fire(this.logLevel)}}setVisibility(e,t){let n=this.getLoggerEntry(e);n&&t!==!n.info.hidden&&(n.info.hidden=!t,this._loggers.set(n.info.resource,n),this._onDidChangeVisibility.fire([n.info.resource,t]))}getLogLevel(e){let t;return e&&(t=this._loggers.get(e)?.info.logLevel),t??this.logLevel}registerLogger(e){let t=this._loggers.get(e.resource);t?t.info.hidden!==e.hidden&&this.setVisibility(e.resource,!e.hidden):(this._loggers.set(e.resource,{info:e,logger:void 0}),this._onDidChangeLoggers.fire({added:[e],removed:[]}))}deregisterLogger(e){let t=this.toResource(e),n=this._loggers.get(t);n&&(n.logger&&n.logger.dispose(),this._loggers.delete(t),this._onDidChangeLoggers.fire({added:[],removed:[n.info]}))}*getRegisteredLoggers(){for(let e of this._loggers.values())yield e.info}getRegisteredLogger(e){return this._loggers.get(e)?.info}dispose(){this._loggers.forEach(e=>e.logger?.dispose()),this._loggers.clear(),super.dispose()}},lg=class{constructor(){this.onDidChangeLogLevel=new w().event}setLevel(r){}getLevel(){return 3}trace(r,...e){}debug(r,...e){}info(r,...e){}warn(r,...e){}error(r,...e){}critical(r,...e){}dispose(){}flush(){}},Hd=class extends lg{};function Kl(o){switch(o){case 1:return"trace";case 2:return"debug";case 3:return"info";case 4:return"warn";case 5:return"error";case 0:return"off"}}var s2=new Bd("logLevel",Kl(3));var ne=L("productService");var us=class extends T{constructor(e,t,n){super();this.logService=n;this.dataMaxAge=t.quality!=="stable"?1e3*60*60*24*7:1e3*60*60*24*30*3,e&&this._register(new It(()=>{this.cleanUpCodeCaches(e)},3e4)).schedule()}async cleanUpCodeCaches(e){this.logService.trace("[code cache cleanup]: Starting to clean up old code cache folders.");try{let t=Date.now(),n=$e(e),i=lt(e),s=await ce.readdir(n);await Promise.all(s.map(async a=>{if(a===i)return;let l=G(n,a),c=await Qw.stat(l);if(c.isDirectory()&&t-c.mtime.getTime()>this.dataMaxAge)return this.logService.trace(`[code cache cleanup]: Removing code cache folder ${a}.`),ce.rm(l)}))}catch(t){Me(t)}}};us=b([g(1,ne),g(2,V)],us);import{promises as vI}from"fs";var X=L("environmentService"),nt=X;var ps=class extends T{constructor(e,t,n){super();this.environmentService=e;this.logService=t;this.dataMaxAge=n.quality!=="stable"?1e3*60*60*24*7:1e3*60*60*24*30*3,this.environmentService.isBuilt&&this._register(new It(()=>{this.cleanUpLanguagePackCache()},4e4)).schedule()}async cleanUpLanguagePackCache(){this.logService.trace("[language pack cache cleanup]: Starting to clean up unused language packs.");try{let e=Object.create(null),t=JSON.parse(await vI.readFile(G(this.environmentService.userDataPath,"languagepacks.json"),"utf8"));for(let l of Object.keys(t)){let c=t[l];e[`${c.hash}.${l}`]=!0}let n=G(this.environmentService.userDataPath,"clp");if(!await ce.exists(n))return;let s=await ce.readdir(n);for(let l of s){if(e[l]){this.logService.trace(`[language pack cache cleanup]: Skipping folder ${l}. Language pack still in use.`);continue}this.logService.trace(`[language pack cache cleanup]: Removing unused language pack: ${l}`),await ce.rm(G(n,l))}let a=Date.now();for(let l of Object.keys(e)){let c=G(n,l),d=await ce.readdir(c);for(let u of d){if(u==="tcf.json")continue;let p=G(c,u),m=await vI.stat(p);m.isDirectory()&&a-m.mtime.getTime()>this.dataMaxAge&&(this.logService.trace(`[language pack cache cleanup]: Removing language pack cache folder: ${G(l,u)}`),await ce.rm(p))}}}catch(e){Me(e)}}};ps=b([g(0,nt),g(1,V),g(2,ne)],ps);var M2={Extensions:{name:{key:"extensionsConfigurationTitle",value:S(141,null)}},IntegratedTerminal:{name:{key:"terminalIntegratedConfigurationTitle",value:S(144,null)}},InteractiveSession:{name:{key:"interactiveSessionConfigurationTitle",value:S(142,null)}},Telemetry:{name:{key:"telemetryConfigurationTitle",value:S(143,null)}},Update:{name:{key:"updateConfigurationTitle",value:S(145,null)}}};var Q=L("configurationService");function Jd(o){let r=o;return r&&typeof r=="object"&&(!r.overrideIdentifier||typeof r.overrideIdentifier=="string")&&(!r.resource||r.resource instanceof P)}function yI(o){let r=o;return r&&typeof r=="object"&&(!r.overrideIdentifiers||Array.isArray(r.overrideIdentifiers))&&!r.overrideIdentifier&&(!r.resource||r.resource instanceof P)}function SI(o){switch(o){case 1:return"APPLICATION";case 2:return"USER";case 3:return"USER_LOCAL";case 4:return"USER_REMOTE";case 5:return"WORKSPACE";case 6:return"WORKSPACE_FOLDER";case 7:return"DEFAULT";case 8:return"MEMORY"}}function Qd(o,r){let e=Object.create(null);for(let t in o)dg(e,t,o[t],r);return e}function dg(o,r,e,t){let n=r.split("."),i=n.pop(),s=o;for(let a=0;a<n.length;a++){let l=n[a],c=s[l];switch(typeof c){case"undefined":c=s[l]=Object.create(null);break;case"object":if(c===null){t(`Ignoring ${r} as ${n.slice(0,a+1).join(".")} is null`);return}break;default:t(`Ignoring ${r} as ${n.slice(0,a+1).join(".")} is ${JSON.stringify(c)}`);return}s=c}if(typeof s=="object"&&s!==null)try{s[i]=e}catch{t(`Ignoring ${r} as ${n.join(".")} is ${JSON.stringify(s)}`)}else t(`Ignoring ${r} as ${n.join(".")} is ${JSON.stringify(s)}`)}function II(o,r){let e=r.split(".");bI(o,e)}function bI(o,r){if(!o)return;let e=o,t=r.shift();if(r.length===0){delete e[t];return}if(Object.keys(e).indexOf(t)!==-1){let n=e[t];typeof n=="object"&&!Array.isArray(n)&&(bI(n,r),Object.keys(n).length===0&&delete e[t])}}function jl(o,r,e){function t(s,a){let l=s;for(let c of a){if(typeof l!="object"||l===null)return;l=l[c]}return l}let n=r.split("."),i=t(o,n);return typeof i>"u"?e:i}function xI(o){return o.replace(/^\[/,"").replace(/]$/g,"").replace(/\]\[/g,", ")}function EI(o){let r=!1,e=new Map,t=new Map;if(Yw(o,d=>{if(o===d)return!0;let u=JSON.stringify(d);if(u.length<30)return!0;let p=e.get(u);if(!p){let m={schemas:[d]};return e.set(u,m),t.set(d,m),!0}return p.schemas.push(d),t.set(d,p),r=!0,!1}),e.clear(),!r)return JSON.stringify(o);let i="$defs";for(;o.hasOwnProperty(i);)i+="_";let s=[];function a(d){return JSON.stringify(d,(u,p)=>{if(p!==d){let m=t.get(p);if(m&&m.schemas.length>1)return m.id||(m.id=`_${s.length}`,s.push(m.schemas[0])),{$ref:`#/${i}/${m.id}`}}return p})}let l=a(o),c=[];for(let d=0;d<s.length;d++)c.push(`"_${d}":${a(s[d])}`);return c.length?`${l.substring(0,l.length-1)},"${i}":{${c.join(",")}}}`:l}function fs(o){return typeof o=="object"&&o!==null}function Yw(o,r){if(!o||typeof o!="object")return;let e=(...l)=>{for(let c of l)fs(c)&&s.push(c)},t=(...l)=>{for(let c of l)if(fs(c))for(let d in c){let u=c[d];fs(u)&&s.push(u)}},n=(...l)=>{for(let c of l)if(Array.isArray(c))for(let d of c)fs(d)&&s.push(d)},i=l=>{if(Array.isArray(l))for(let c of l)fs(c)&&s.push(c);else fs(l)&&s.push(l)},s=[o],a=s.pop();for(;a;)r(a)&&(e(a.additionalItems,a.additionalProperties,a.not,a.contains,a.propertyNames,a.if,a.then,a.else,a.unevaluatedItems,a.unevaluatedProperties),t(a.definitions,a.$defs,a.properties,a.patternProperties,a.dependencies,a.dependentSchemas),n(a.anyOf,a.allOf,a.oneOf,a.prefixItems),i(a.items)),a=s.pop()}var ug=class{constructor(){this.data=new Map}add(r,e){td(ue(r)),td(Re(e)),td(!this.data.has(r),"There is already an extension with this id"),this.data.set(r,e)}knows(r){return this.data.has(r)}as(r){return this.data.get(r)||null}dispose(){this.data.forEach(r=>{gl(r.dispose)&&r.dispose()}),this.data.clear()}},gt=new ug;var Hl={JSONContribution:"base.contributions.json"};function wI(o){return o.length>0&&o.charAt(o.length-1)==="#"?o.substring(0,o.length-1):o}var pg=class extends T{constructor(){super(...arguments);this.schemasById={};this.schemaAssociations={};this._onDidChangeSchema=this._register(new w);this.onDidChangeSchema=this._onDidChangeSchema.event;this._onDidChangeSchemaAssociations=this._register(new w);this.onDidChangeSchemaAssociations=this._onDidChangeSchemaAssociations.event}registerSchema(e,t,n){let i=wI(e);this.schemasById[i]=t,this._onDidChangeSchema.fire(e),n&&n.add(oe(()=>{delete this.schemasById[i],this._onDidChangeSchema.fire(e)}))}registerSchemaAssociation(e,t){let n=wI(e);return this.schemaAssociations[n]||(this.schemaAssociations[n]=[]),this.schemaAssociations[n].includes(t)||(this.schemaAssociations[n].push(t),this._onDidChangeSchemaAssociations.fire()),oe(()=>{let i=this.schemaAssociations[n];if(i){let s=i.indexOf(t);s!==-1&&(i.splice(s,1),i.length===0&&delete this.schemaAssociations[n],this._onDidChangeSchemaAssociations.fire())}})}notifySchemaChanged(e){this._onDidChangeSchema.fire(e)}getSchemaContributions(){return{schemas:this.schemasById}}getSchemaContent(e){let t=this.schemasById[e];return t?EI(t):void 0}hasSchemaContent(e){return!!this.schemasById[e]}getSchemaAssociations(){return this.schemaAssociations}},eP=new pg;gt.add(Hl.JSONContribution,eP);var xr,fg=globalThis.vscode;if(typeof fg<"u"&&typeof fg.context<"u"){let o=fg.context.configuration();if(o)xr=o.product;else throw new Error("Sandbox: unable to resolve product configuration from preload script.")}else if(globalThis._VSCODE_PRODUCT_JSON&&globalThis._VSCODE_PACKAGE_JSON){if(xr=globalThis._VSCODE_PRODUCT_JSON,Fe.VSCODE_DEV&&Object.assign(xr,{nameShort:`${xr.nameShort} Dev`,nameLong:`${xr.nameLong} Dev`,dataFolderName:`${xr.dataFolderName}-dev`,serverDataFolderName:xr.serverDataFolderName?`${xr.serverDataFolderName}-dev`:void 0}),!xr.version){let o=globalThis._VSCODE_PACKAGE_JSON;Object.assign(xr,{version:o.version})}}else xr={nameShort:"Devin",nameLong:"Devin",applicationName:"devin-desktop",aliasName:"surf",dataFolderName:".devin",oldDataFolderName:".windsurf",oldNameShort:"Windsurf",win32MutexName:"devin-desktop",licenseName:"MIT",licenseUrl:"https://windsurf.com/terms-of-service-individual",serverLicenseUrl:"https://windsurf.com/terms-of-service-individual",serverGreeting:[],serverLicense:[],serverLicensePrompt:"",serverApplicationName:"devin-server",serverDataFolderName:".devin-server",tunnelApplicationName:"devin-tunnel",win32DirName:"Devin",win32NameVersion:"Devin",win32RegValueName:"Devin",win32x64AppId:"{{A71B58E9-CEFB-4424-8A1D-A0E49CF18EBB}",win32arm64AppId:"{{9B0AE7D1-5CD0-43E6-B7B0-EE4B79723A25}",win32x64UserAppId:"{{5A8B7D94-9B5F-4D1F-93FC-5609F7159349}",win32arm64UserAppId:"{{1A69CEA0-8DA8-4B3E-950C-23FA9F850651}",win32AppUserModelId:"Exafunction.Windsurf",win32ShellNameShort:"Devin",win32TunnelServiceMutex:"devin-tunnelservice",win32TunnelMutex:"devin-tunnel",darwinBundleIdentifier:"com.exafunction.windsurf",darwinProfileUUID:"35631911-548E-4245-8C30-A1A0C65DCF7E",darwinProfilePayloadUUID:"53671443-8AE4-4FCA-B901-991F8B03A158",linuxIconName:"devin-desktop",snapName:"windsurf",licenseFileName:"LICENSE.txt",reportIssueUrl:"https://windsurf.com/redirect/windsurf/feedback?referrer=extension",nodejsRepository:"https://nodejs.org",urlProtocol:"devin",oldUrlProtocol:"windsurf",webviewContentExternalBaseUrlTemplate:"https://{{uuid}}.vscode-cdn.net/insider/ef65ac1ba57f57f2a3961bfe94aa20481caca4c6/out/vs/workbench/contrib/webview/browser/pre/",extensionsGallery:{serviceUrl:"https://marketplace.windsurf.com/vscode/gallery",itemUrl:"https://marketplace.windsurf.com/vscode/item",controlUrl:"https://marketplace.windsurf.com/vscode/extensions-control"},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.110.0",sha256:"ad3f7d935b64f4ee123853c464b47b3cba13e5018edef831770ae9c3eb218f5b",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"}}],____________EXTRA_WINDSURF_KEYS_START_HERE_______________:{},zendeskTicketApiKey:"1d83db0009861157cacd3279a927855f53279e48c84bd26d2ba48d241699773d",enableTelemetry:!0,aiConfig:{ariaKey:"windsurf"},aiGeneratedWorkspaceTrust:{title:"This workspace was generated by GitHub Copilot",checkboxText:"Trust the contents of all files in this workspace",trustOption:"Yes, I trust the contents",dontTrustOption:"No, I don't trust the contents",startupTrustRequestLearnMore:"If you don't trust the contents of the files generated by GitHub Copilot, we recommend continuing in restricted mode. See [our docs](https://aka.ms/vscode-workspace-trust) to learn more. "},extensionUntrustedWorkspaceSupport:{"codeium.windsurf":{override:!0}},chatParticipantRegistry:"https://main.vscode-cdn.net/extensions/chat.json",commandPaletteSuggestedCommandIds:["windsurf.prioritized.chat.open"],commonlyUsedSettings:["files.autoSave","editor.fontSize","editor.fontFamily","editor.tabSize","editor.renderWhitespace","editor.cursorStyle","editor.multiCursorModifier","editor.insertSpaces","editor.wordWrap","files.exclude","files.associations","workbench.editor.enablePreview"],defaultChatAgent:{extensionId:"GitHub.copilot",chatExtensionId:"GitHub.copilot-chat",chatExtensionOutputId:"GitHub.copilot-chat.GitHub Copilot Chat.log",chatExtensionOutputExtensionStateCommand:"github.copilot.debug.extensionState",documentationUrl:"https://aka.ms/github-copilot-overview",termsStatementUrl:"https://aka.ms/github-copilot-terms-statement",privacyStatementUrl:"https://aka.ms/github-copilot-privacy-statement",skusDocumentationUrl:"https://aka.ms/github-copilot-plans",publicCodeMatchesUrl:"https://aka.ms/github-copilot-match-public-code",manageSettingsUrl:"https://aka.ms/github-copilot-settings",managePlanUrl:"https://aka.ms/github-copilot-manage-plan",manageOverageUrl:"https://aka.ms/github-copilot-manage-overage",upgradePlanUrl:"https://aka.ms/github-copilot-upgrade-plan",signUpUrl:"https://aka.ms/github-sign-up",provider:{default:{id:"github",name:"GitHub"},enterprise:{id:"github-enterprise",name:"GHE.com"},google:{id:"google",name:"Google"},apple:{id:"apple",name:"Apple"}},providerExtensionId:"vscode.github-authentication",providerUriSetting:"github-enterprise.uri",providerScopes:[["read:user","user:email","repo","workflow"],["user:email"],["read:user"]],entitlementUrl:"",entitlementSignupLimitedUrl:"",chatQuotaExceededContext:"github.copilot.chat.quotaExceeded",completionsQuotaExceededContext:"github.copilot.completions.quotaExceeded",walkthroughCommand:"github.copilot.open.walkthrough",completionsMenuCommand:"github.copilot.toggleStatusMenu",completionsRefreshTokenCommand:"github.copilot.signIn",chatRefreshTokenCommand:"github.copilot.refreshToken",generateCommitMessageCommand:"github.copilot.git.generateCommitMessage",resolveMergeConflictsCommand:"github.copilot.git.resolveMergeConflicts",completionsAdvancedSetting:"github.copilot.advanced",completionsEnablementSetting:"github.copilot.enable",nextEditSuggestionsSetting:"github.copilot.nextEditSuggestions.enabled",tokenEntitlementUrl:"",mcpRegistryDataUrl:""},configBasedExtensionTips:{git:{configPath:".git/config",configName:"Git",recommendations:{"github.vscode-pull-request-github":{name:"GitHub Pull Request",contentPattern:"^\\s*url\\s*=\\s*https:\\/\\/github\\.com.*$"},"eamodio.gitlens":{name:"GitLens"}}},maven:{configPath:"pom.xml",configName:"Maven",recommendations:{"vscjava.vscode-java-pack":{name:"Java",important:!0,isExtensionPack:!0,whenNotInstalled:["ASF.apache-netbeans-java","Oracle.oracle-java"]},"vmware.vscode-boot-dev-pack":{name:"Spring Boot Extension Pack",isExtensionPack:!0}}},gradle:{configPath:"build.gradle",configName:"Gradle",recommendations:{"vscjava.vscode-java-pack":{name:"Java",important:!0,isExtensionPack:!0,whenNotInstalled:["ASF.apache-netbeans-java","Oracle.oracle-java"]}}},"github-pull-request":{configPath:".vscode/.github-pull-request.rec",configName:"GitHub",configScheme:"vscode-vfs",recommendations:{"github.vscode-pull-request-github":{name:"GitHub Pull Request",important:!0}}},"pyproject-formatter":{configPath:"pyproject.toml",configName:"Python Formatter",recommendations:{"ms-python.black-formatter":{name:"Black Formatter",contentPattern:'(^\\s*\\[\\[?\\s*"?tool"?\\s*\\.\\s*"?black"?\\s*[\\].])|("black\\s*["[(<=>!~;@])'},"ms-python.autopep8":{name:"Autopep8",contentPattern:'(^\\s*\\[\\[?\\s*"?tool"?\\s*\\.\\s*"?autopep8"?\\s*[\\].])|("autopep8\\s*["[(<=>!~;@])'}}},"pep8-formatter":{configPath:".pep8",configName:"Python Formatter",recommendations:{"ms-python.autopep8":{name:"Autopep8"}}},"python-setup-cgf-formatter":{configPath:"setup.cfg",configName:"Python Formatter",recommendations:{"ms-python.autopep8":{name:"Autopep8",contentPattern:"^\\[pep8\\]"}}},"tox-ini-formatter":{configPath:"tox.ini",configName:"Python Formatter",recommendations:{"ms-python.autopep8":{name:"Autopep8",contentPattern:"^\\[pep8\\]"}}},"pyproject-linter":{configPath:"pyproject.toml",configName:"Python Linter",recommendations:{"ms-python.pylint":{name:"Pylint",contentPattern:'(^\\s*\\[\\[?\\s*"?tool"?\\s*\\.\\s*"?pylint"?\\s*[\\].])|("pylint\\s*["[(<=>!~;@])'},"charliermarsh.ruff":{name:"Ruff",contentPattern:'(^\\s*\\[\\[?\\s*"?tool"?\\s*\\.\\s*"?ruff"?\\s*[\\].])|("ruff\\s*["[(<=>!~;@])'},"ms-python.mypy-type-checker":{name:"Mypy Type Checker",contentPattern:'(^\\s*\\[\\[?\\s*"?tool"?\\s*\\.\\s*"?mypy"?\\s*[\\].])|("mypy\\s*["[(<=>!~;@])'},"ms-python.flake8":{name:"Flake8",contentPattern:'(^\\s*\\[\\[?\\s*"?tool"?\\s*\\.\\s*"?flake8"?\\s*[\\].])|("flake8\\s*["[(<=>!~;@])'}}},".pylintrc-linter":{configPath:".pylintrc",configName:"Python Linter",recommendations:{"ms-python.pylint":{name:"Pylint"}}},"pylintrc-linter":{configPath:"pylintrc",configName:"Python Linter",recommendations:{"ms-python.pylint":{name:"Pylint"}}},"mypy-ini-linter":{configPath:".mypy.ini",configName:"Python Linter",recommendations:{"ms-python.mypy-type-checker":{name:"Mypy Type Checker"}}},"tox-ini-linter":{configPath:"tox.ini",configName:"Python Linter",recommendations:{"ms-python.flake8":{name:"Flake8",contentPattern:"^\\[flake8\\]"}}},".flake8-linter":{configPath:".flake8",configName:"Python Linter",recommendations:{"ms-python.flake8":{name:"Flake8"}}},"python-setup-cgf-linter":{configPath:"setup.cfg",configName:"Python Linter",recommendations:{"ms-python.flake8":{name:"Flake8",contentPattern:"^\\[flake8\\]"}}}},crashReporter:{productName:"Devin",companyName:"Exafunction"},enabledTelemetryLevels:{error:!0,usage:!0},exeBasedExtensionTips:{az:{friendlyName:"Azure CLI",windowsPath:"%ProgramFiles(x86)%\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd",recommendations:{"ms-vscode.azurecli":{name:"Azure CLI Tools"}}},azd:{friendlyName:"Azure Dev CLI",windowsPath:"%USERPROFILE%\\AppData\\Local\\Programs\\Azure Dev CLI\\azd.exe",recommendations:{"ms-azuretools.vscode-azureresourcegroups":{name:"Azure Resources"}}},"azd-user":{friendlyName:"Azure Dev CLI",windowsPath:"%ProgramFiles%\\Azure Dev CLI\\azd.exe",recommendations:{"ms-azuretools.vscode-azureresourcegroups":{name:"Azure Resources"}}},heroku:{friendlyName:"Heroku CLI",windowsPath:"%ProgramFiles%\\Heroku\\bin\\heroku.cmd",recommendations:{"ms-azuretools.vscode-azureappservice":{name:"Azure App Service"}}},mongo:{friendlyName:"Mongo",windowsPath:"%ProgramFiles%\\MongoDB\\Server\\3.6\\bin\\mongod.exe",recommendations:{}},serverless:{friendlyName:"Serverless framework",windowsPath:"%APPDATA%\\npm\\serverless.cmd",recommendations:{"ms-azuretools.vscode-azurefunctions":{name:"Azure Functions"}}},func:{friendlyName:"Azure Function SDK",windowsPath:"%APPDATA%\\npm\\func.cmd",recommendations:{"ms-azuretools.vscode-azurefunctions":{name:"Azure Functions"}}},mysql:{friendlyName:"MySQL",windowsPath:"%ProgramFiles%\\MySQL\\MySQL Server 8.0\\bin\\mysqld.exe",recommendations:{"mtxr.sqltools":{name:"SQLTools"}}},postgres:{friendlyName:"PostgreSQL",windowsPath:"%ProgramFiles%\\PostgreSQL\\11\\bin\\psql.exe",recommendations:{"mtxr.sqltools":{name:"SQLTools"}}},sqlcmd:{friendlyName:"SQL CLI",recommendations:{"ms-mssql.mssql":{name:"SQL Server (mssql)"}}},now:{friendlyName:"Now CLI",windowsPath:"%APPDATA%\\npm\\now.cmd",recommendations:{"ms-azuretools.vscode-azureappservice":{name:"Azure App Service"},"ms-azuretools.vscode-docker":{name:"Docker"}}},docker:{friendlyName:"Docker",windowsPath:"%ProgramFiles%\\Docker\\Docker\\Resources\\bin\\docker.exe",recommendations:{"ms-azuretools.vscode-docker":{name:"Docker",important:!0},"ms-kubernetes-tools.vscode-kubernetes-tools":{name:"Kubernetes"}}},kubectl:{friendlyName:"Kubernetes",windowsPath:"%ProgramFiles%\\Docker\\Docker\\Resources\\bin\\kubectl.exe",recommendations:{"ms-azuretools.vscode-docker":{name:"Docker"},"ms-kubernetes-tools.vscode-kubernetes-tools":{name:"Kubernetes"}}},ng:{friendlyName:"Angular CLI",windowsPath:"%APPDATA%\\npmexit\\ng.cmd",recommendations:{"johnpapa.Angular2":{name:"Angular Snippets"}}},"create-react-app":{friendlyName:"Create React App",windowsPath:"%APPDATA%\\npm\\create-react-app.cmd",recommendations:{"msjsdiag.vscode-react-native":{name:"React Native Tools"}}},"react-native":{friendlyName:"React Native",windowsPath:"%APPDATA%\\npm\\react-native-cli",recommendations:{"msjsdiag.vscode-react-native":{name:"React Native Tools"}}},p4:{friendlyName:"Perforce",recommendations:{}},hg:{friendlyName:"Mercurial",recommendations:{"mrcrowl.hg":{name:"Hg"}}},git:{friendlyName:"Git",windowsPath:"%ProgramFiles%\\Git\\git-bash.exe",recommendations:{"eamodio.gitlens":{name:"GitLens"}}},svn:{friendlyName:"Subversion",windowsPath:"%ProgramFiles%\\TortoiseSVN\\bin\\TortoiseProc.exe",recommendations:{"johnstoncode.svn-scm":{name:"SVN"}}},subl:{friendlyName:"Sublime",windowsPath:"%ProgramFiles%\\Sublime Text3\\sublime_text.exe",recommendations:{"ms-vscode.sublime-keybindings":{name:"Sublime Text Keymap and Settings Importer"}}},atom:{friendlyName:"Atom",windowsPath:"%USERPROFILE%\\AppData\\Local\\atom\\bin\\atom.cmd",recommendations:{"ms-vscode.atom-keybindings":{name:"Atom Keymap"}}},brackets:{friendlyName:"Brackets",windowsPath:"%ProgramFiles(x86)%\\Brackets\\Brackets.exe",recommendations:{"ms-vscode.brackets-keybindings":{name:"Brackets Keymap"}}},notepadplusplus:{friendlyName:"Notepad++",windowsPath:"%ProgramFiles%\\Notepad++\\Notepad++.exe",recommendations:{"ms-vscode.notepadplusplus-keybindings":{name:"Notepad++ keymap"}}},vi:{friendlyName:"VIM",windowsPath:"%ProgramFiles(x86)%\\Vim\\vim80\\gvim.exe",recommendations:{"vscodevim.vim":{name:"Vim"}}},mvn:{friendlyName:"Maven",recommendations:{"vscjava.vscode-java-pack":{name:"Java",important:!0,isExtensionPack:!0,whenNotInstalled:["ASF.apache-netbeans-java","Oracle.oracle-java"]}}},gradle:{friendlyName:"Gradle",recommendations:{"vscjava.vscode-java-pack":{name:"Java",important:!0,isExtensionPack:!0,whenNotInstalled:["ASF.apache-netbeans-java","Oracle.oracle-java"]}}},"Microsoft Edge":{friendlyName:"Microsoft Edge",windowsPath:"%USERPROFILE%\\AppData\\Local\\Microsoft\\Edge\\Application\\msedge.exe",recommendations:{"ms-edgedevtools.vscode-edge-devtools":{name:"Microsoft Edge Developer Tools"}}},"Microsoft Edge Dev":{friendlyName:"Microsoft Edge Dev",windowsPath:"%USERPROFILE%\\AppData\\Local\\Microsoft\\Edge Dev\\Application\\msedge.exe",recommendations:{"ms-edgedevtools.vscode-edge-devtools":{name:"Microsoft Edge Developer Tools"}}},"Microsoft Edge Beta":{friendlyName:"Microsoft Edge Beta",windowsPath:"%USERPROFILE%\\AppData\\Local\\Microsoft\\Edge Beta\\Application\\msedge.exe",recommendations:{"ms-edgedevtools.vscode-edge-devtools":{name:"Microsoft Edge Developer Tools"}}},"Microsoft Edge Canary":{friendlyName:"Microsoft Edge Canary",windowsPath:"%USERPROFILE%\\AppData\\Local\\Microsoft\\Edge SxS\\Application\\msedge.exe",recommendations:{"ms-edgedevtools.vscode-edge-devtools":{name:"Microsoft Edge Developer Tools"}}},"Mozilla Firefox (x86)":{friendlyName:"Mozilla Firefox",windowsPath:"%ProgramFiles(x86)%\\Mozilla Firefox\\firefox.exe",recommendations:{"firefox-devtools.vscode-firefox-debug":{name:"Debugger for Firefox"}}},"Mozilla Firefox Developer Edition (x86)":{friendlyName:"Mozilla Firefox Developer Edition",windowsPath:"%ProgramFiles(x86)%\\Firefox Developer Edition\\firefox.exe",recommendations:{"firefox-devtools.vscode-firefox-debug":{name:"Debugger for Firefox"}}},"Mozilla Firefox":{friendlyName:"Mozilla Firefox",windowsPath:"%ProgramFiles%\\Mozilla Firefox\\firefox.exe",recommendations:{"firefox-devtools.vscode-firefox-debug":{name:"Debugger for Firefox"}}},"Mozilla Firefox Developer Edition":{friendlyName:"Mozilla Firefox Developer Edition",windowsPath:"%ProgramFiles%\\Firefox Developer Edition\\firefox.exe",recommendations:{"firefox-devtools.vscode-firefox-debug":{name:"Debugger for Firefox"}}},cordova:{friendlyName:"Cordova",windowsPath:"%APPDATA%\\npm\\cordova",recommendations:{}},gcloud:{friendlyName:"Google GCloud CLI",windowsPath:"%ProgramFiles(x86)%\\Google\\Cloud SDK\\google-cloud-sdk\\bin\\gcloud.cmd",recommendations:{"GoogleCloudTools.cloudcode":{name:"Cloud Code"}}},skaffold:{friendlyName:"Skaffold Code to Cluster",recommendations:{"ms-azuretools.vscode-docker":{name:"Docker"},"ms-kubernetes-tools.vscode-kubernetes-tools":{name:"Kubernetes"}}},minikube:{friendlyName:"MiniKube Local Kubernetes Cluster",recommendations:{"ms-azuretools.vscode-docker":{name:"Docker"},"ms-kubernetes-tools.vscode-kubernetes-tools":{name:"Kubernetes"}}},podman:{friendlyName:"Podman",recommendations:{}},wsl:{friendlyName:"Windows Subsystem for Linux (WSL)",windowsPath:"%WINDIR%\\system32\\lxss\\LxssManager.dll",important:!0,recommendations:{}}},extensionAllowedBadgeProviders:["api.bintray.com","api.travis-ci.com","api.travis-ci.org","app.fossa.io","badge.buildkite.com","badge.fury.io","badge.waffle.io","badgen.net","badges.frapsoft.com","badges.gitter.im","badges.greenkeeper.io","cdn.travis-ci.com","cdn.travis-ci.org","ci.appveyor.com","circleci.com","cla.opensource.microsoft.com","codacy.com","codeclimate.com","codecov.io","coveralls.io","david-dm.org","deepscan.io","dev.azure.com","docs.rs","flat.badgen.net","gemnasium.com","githost.io","gitlab.com","godoc.org","goreportcard.com","img.shields.io","isitmaintained.com","marketplace.visualstudio.com","nodesecurity.io","opencollective.com","snyk.io","travis-ci.com","travis-ci.org","visualstudio.com","vsmarketplacebadge.apphb.com","www.bithound.io","www.versioneye.com"],extensionAllowedBadgeProvidersRegex:["^https:\\/\\/github\\.com\\/[^/]+\\/[^/]+\\/(actions\\/)?workflows\\/.*badge\\.svg"],extensionEnabledApiProposals:{"mrleemurray.theme-2026":["css"],"ms-azuretools.vscode-containers":["authenticationChallenges"],"ms-azuretools.vscode-azureresourcegroups":["authenticationChallenges"],"ms-azuretools.vscode-azure-github-copilot":["authenticationChallenges"],"ms-azuretools.vscode-dev-azurecloudshell":["contribEditSessions","authenticationChallenges"],"ms-toolsai.vscode-ai":["authenticationChallenges"],"TeamsDevApp.vscode-ai-foundry":["authenticationChallenges"],"ms-vscode.vscode-selfhost-test-provider":["testObserver","testRelatedCode"],"VisualStudioExptTeam.vscodeintellicode-completions":["inlineCompletionsAdditions"],"ms-vsliveshare.vsliveshare":["contribMenuBarHome","contribShareMenu","contribStatusBarItems","diffCommand","documentFiltersExclusive","fileSearchProvider","findTextInFiles","notebookLiveShare","terminalDimensions","terminalDataWriteEvent","textSearchProvider"],"ms-vscode.js-debug":["portsAttributes","findTextInFiles","workspaceTrust","tunnels"],"ms-toolsai.vscode-ai-remote":["resolvers","authenticationChallenges"],"ms-python.python":["codeActionAI","contribEditorContentMenu","quickPickSortByLabel","portsAttributes","testObserver","quickPickItemTooltip","terminalDataWriteEvent","terminalExecuteCommandEvent","notebookReplDocument","notebookVariableProvider","terminalShellEnv"],"ms-python.vscode-python-envs":["terminalShellEnv","terminalDataWriteEvent","taskExecutionTerminal"],"ms-dotnettools.dotnet-interactive-vscode":["notebookMessaging"],"GitHub.codespaces":["contribEditSessions","contribMenuBarHome","contribRemoteHelp","contribViewsRemote","resolvers","tunnels","terminalDataWriteEvent","treeViewReveal","notebookKernelSource"],"ms-vscode.azure-repos":["extensionRuntime","fileSearchProvider","textSearchProvider"],"ms-vscode.remote-repositories":["canonicalUriProvider","contribEditSessions","contribRemoteHelp","contribMenuBarHome","contribViewsRemote","contribViewsWelcome","contribShareMenu","documentFiltersExclusive","editSessionIdentityProvider","extensionRuntime","fileSearchProvider","quickPickSortByLabel","workspaceTrust","shareProvider","scmActionButton","scmSelectedProvider","scmValidation","textSearchProvider","timeline"],"ms-vscode-remote.remote-wsl":["resolvers","contribRemoteHelp","contribViewsRemote","telemetry"],"ms-vscode-remote.remote-ssh":["resolvers","tunnels","terminalDataWriteEvent","contribRemoteHelp","contribViewsRemote","telemetry"],"ms-vscode.remote-server":["resolvers","tunnels","contribViewsWelcome"],"ms-vscode.remote-explorer":["contribRemoteHelp","contribViewsRemote","extensionsAny"],"ms-vscode-remote.remote-containers":["contribEditSessions","resolvers","portsAttributes","tunnels","workspaceTrust","terminalDimensions","contribRemoteHelp","contribViewsRemote"],"ms-vscode.js-debug-nightly":["portsAttributes","findTextInFiles","workspaceTrust","tunnels"],"ms-vscode.lsif-browser":["documentFiltersExclusive"],"ms-vscode.vscode-speech":["speech"],"GitHub.vscode-pull-request-github":["activeComment","chatContextProvider","chatParticipantAdditions","chatParticipantPrivate","chatSessionsProvider","codiconDecoration","codeActionRanges","commentingRangeHint","commentReactor","commentReveal","commentsDraftState","commentThreadApplicability","contribAccessibilityHelpContent","contribCommentEditorActionsMenu","contribCommentPeekContext","contribCommentThreadAdditionalMenu","contribCommentsViewThreadMenus","contribEditorContentMenu","contribMultiDiffEditorMenus","contribShareMenu","diffCommand","languageModelToolResultAudience","markdownAlertSyntax","quickDiffProvider","shareProvider","tabInputMultiDiff","tabInputTextMerge","tokenInformation","treeItemMarkdownLabel","treeViewMarkdownMessage"],"GitHub.copilot":["inlineCompletionsAdditions","devDeviceId"],"GitHub.copilot-nightly":["inlineCompletionsAdditions","devDeviceId"],"GitHub.copilot-chat":["agentSessionsWorkspace","interactive","terminalDataWriteEvent","terminalExecuteCommandEvent","terminalSelection","terminalQuickFixProvider","chatParticipantAdditions","defaultChatParticipant","embeddings","chatProvider","mappedEditsProvider","aiRelatedInformation","aiSettingsSearch","codeActionAI","findTextInFiles","findTextInFiles2","textSearchProvider","textSearchProvider2","activeComment","commentReveal","contribSourceControlInputBoxMenu","contribCommentEditorActionsMenu","contribCommentThreadAdditionalMenu","contribCommentsViewThreadMenus","contribChatEditorInlineGutterMenu","extensionAffinity","newSymbolNamesProvider","findFiles2","chatReferenceDiagnostic","extensionsAny","authLearnMore","testObserver","aiTextSearchProvider","documentFiltersExclusive","chatParticipantPrivate","contribDebugCreateConfiguration","inlineCompletionsAdditions","chatReferenceBinaryData","languageModelSystem","languageModelCapabilities","languageModelThinkingPart","languageModelToolSupportsModel","chatStatusItem","taskProblemMatcherStatus","contribLanguageModelToolSets","textDocumentChangeReason","resolvers","taskExecutionTerminal","dataChannels","chatSessionsProvider","devDeviceId","contribEditorContentMenu","tokenInformation","chatPromptFiles","mcpServerDefinitions","tabInputMultiDiff","workspaceTrust","chatHooks","chatDebug","environmentPower","terminalTitle"],"GitHub.remotehub":["contribRemoteHelp","contribMenuBarHome","contribViewsRemote","contribViewsWelcome","documentFiltersExclusive","extensionRuntime","fileSearchProvider","quickPickSortByLabel","workspaceTrust","scmSelectedProvider","scmValidation","textSearchProvider","timeline"],"ms-python.vscode-pylance":["terminalShellEnv","portsAttributes","codeActionAI"],"ms-python.debugpy":["contribViewsWelcome","debugVisualization","portsAttributes"],"ms-toolsai.jupyter-renderers":["contribNotebookStaticPreloads"],"ms-toolsai.jupyter":["notebookDeprecated","notebookMessaging","notebookMime","portsAttributes","quickPickSortByLabel","notebookKernelSource","interactiveWindow","notebookControllerAffinityHidden","contribNotebookStaticPreloads","quickPickItemTooltip","notebookExecution","notebookCellExecution","notebookVariableProvider","notebookReplDocument"],"donjayamanne.kusto":["notebookVariableProvider"],"ms-toolsai.tensorboard":["portsAttributes"],"dbaeumer.vscode-eslint":[],"ms-vscode.azure-sphere-tools-ui":["tunnels"],"ms-azuretools.vscode-azureappservice":["terminalDataWriteEvent"],"ms-vscode.anycode":["extensionsAny"],"ms-vscode.cpptools":["terminalDataWriteEvent","chatParticipantAdditions"],"vscjava.vscode-java-pack":[],"ms-dotnettools.csdevkit":["inlineCompletionsAdditions"],"ms-dotnettools.vscodeintellicode-csharp":["inlineCompletionsAdditions"],"ms-dotnettools.vscode-dotnet-modernize":["chatParticipantAdditions","chatPromptFiles"],"microsoft-IsvExpTools.powerplatform-vscode":["fileSearchProvider","textSearchProvider"],"microsoft-IsvExpTools.powerplatform-vscode-preview":["fileSearchProvider","textSearchProvider"],"TeamsDevApp.ms-teams-vscode-extension":["chatParticipantAdditions","languageModelSystem"],"ms-toolsai.datawrangler":[],"ms-vscode.vscode-commander":[],"ms-vscode.vscode-websearchforcopilot":[],"ms-vscode.vscode-copilot-vision":["chatReferenceBinaryData","codeActionAI"],"ms-autodev.vscode-autodev":["chatParticipantAdditions"],"vscjava.vscode-java-upgrade":["chatParticipantAdditions","chatParticipantPrivate"],"FoundryLocal.foundry-local-chat":["chatProvider"],"Microsoft.foundry-local-chat":["chatProvider"],"ms-wmcp.windows-mcp-server-extension":["mcpToolDefinitions"],"openai.chatgpt":["languageModelProxy","chatSessionsProvider"],"TypeScriptTeam.native-preview":["editorHoverVerbosityLevel","multiDocumentHighlightProvider"],"ms-vscode.vscode-eng-codereview":["chatContextProvider"],"ms-python.gather":[]},extensionKeywords:{md:["Markdown"],js:["JavaScript"],jsx:["JavaScript"],es6:["JavaScript"],html:["Html"],ts:["TypeScript"],tsx:["TypeScript"],css:["CSS"],scss:["SASS"],txt:["Text"],php:["PHP"],php3:["PHP"],php4:["PHP"],ph3:["PHP"],ph4:["PHP"],xml:["XML"],py:["Python"],pyc:["Python"],pyd:["Python"],pyo:["Python"],pyw:["Python"],pyz:["Python"],java:["Java"],class:["Java"],jar:["Java"],c:["c","objective c","objective-c"],m:["objective c","objective-c"],mm:["objective c","objective-c"],cpp:["cpp","c plus plus","c","c++"],cc:["cpp","c plus plus","c","c++"],cxx:["cpp","c plus plus","c++"],hh:["cpp","c plus plus","c++"],hpp:["cpp","c++"],h:["cpp","c plus plus","c++","c","objective c","objective-c"],sql:["sql"],sh:["bash"],bash:["bash"],zsh:["bash","zshell"],cs:["c#","csharp"],csproj:["c#","csharp"],sln:["c#","csharp"],go:["go"],sty:["latex"],tex:["latex"],ps:["powershell"],ps1:["powershell"],rs:["rust"],rslib:["rust"],hs:["haskell"],lhs:["haskell"],scm:["scheme"],ss:["scheme"],clj:["clojure"],cljs:["clojure"],cljc:["clojure"],edn:["clojure"],erl:["erlang"],hrl:["erlang"],scala:["scala"],sc:["scala"],pl:["perl"],pm:["perl"],t:["perl"],pod:["perl"],groovy:["groovy"],swift:["swift"],rb:["ruby"],rbw:["ruby"],jl:["julia"],f:["fortran"],for:["fortran"],f90:["fortran"],f95:["fortran"],coffee:["CoffeeScript"],litcoffee:["CoffeeScript"],yaml:["yaml"],yml:["yaml"],dart:["dart"],json:["json"]},extensionKind:{"Shan.code-settings-sync":["ui"],"shalldie.background":["ui"],"techer.open-in-browser":["ui"],"CoenraadS.bracket-pair-colorizer-2":["ui"],"CoenraadS.bracket-pair-colorizer":["ui","workspace"],"hiro-sun.vscode-emacs":["ui","workspace"],"hnw.vscode-auto-open-markdown-preview":["ui","workspace"],"wayou.vscode-todo-highlight":["ui","workspace"],"aaron-bond.better-comments":["ui","workspace"],"vscodevim.vim":["ui"],"ollyhayes.colmak-vim":["ui"]},extensionPointExtensionKind:{typescriptServerPlugins:["workspace"]},extensionSyncedKeys:{"ritwickdey.liveserver":["liveServer.setup.version"]},extensionVirtualWorkspacesSupport:{"esbenp.prettier-vscode":{default:!1},"msjsdiag.debugger-for-chrome":{default:!1},"redhat.java":{default:!1},"HookyQR.beautify":{default:!1},"ritwickdey.LiveServer":{default:!1},"VisualStudioExptTeam.vscodeintellicode":{default:!1},"octref.vetur":{default:!1},"formulahendry.code-runner":{default:!1},"xdebug.php-debug":{default:!1},"ms-mssql.mssql":{default:!1},"christian-kohler.path-intellisense":{default:!1},"eg2.tslint":{default:!1},"eg2.vscode-npm-script":{default:!1},"donjayamanne.githistory":{default:!1},"Zignd.html-css-class-completion":{default:!1},"christian-kohler.npm-intellisense":{default:!1},"EditorConfig.EditorConfig":{default:!1},"austin.code-gnu-global":{default:!1},"johnpapa.Angular2":{default:!1},"ms-vscode.vscode-typescript-tslint-plugin":{default:!1},"DotJoshJohnson.xml":{default:!1},"techer.open-in-browser":{default:!1},"tht13.python":{default:!1},"bmewburn.vscode-intelephense-client":{default:!1},"Angular.ng-template":{default:!1},"xdebug.php-pack":{default:!1},"dbaeumer.jshint":{default:!1},"yzhang.markdown-all-in-one":{default:!1},"Dart-Code.flutter":{default:!1},"streetsidesoftware.code-spell-checker":{default:!1},"rebornix.Ruby":{default:!1},"ms-vscode.sublime-keybindings":{default:!1},"mitaki28.vscode-clang":{default:!1},"steoates.autoimport":{default:!1},"donjayamanne.python-extension-pack":{default:!1},"shd101wyy.markdown-preview-enhanced":{default:!1},"mikestead.dotenv":{default:!1},"pranaygp.vscode-css-peek":{default:!1},"ikappas.phpcs":{default:!1},"platformio.platformio-ide":{default:!1},"jchannon.csharpextensions":{default:!1},"gruntfuggly.todo-tree":{default:!1}},extensionRecommendations:{"ms-python.python":{onFileOpen:[{pathGlob:"{**/*.py}",important:!0},{languages:["python"],important:!0},{pathGlob:"{**/*.ipynb}"}]},"ms-toolsai.jupyter":{onFileOpen:[{pathGlob:"{**/*.py}",contentPattern:"^#\\s*%%$",important:!0,whenInstalled:["ms-python.python"]},{pathGlob:"{**/*.ipynb}"}]},"golang.Go":{onFileOpen:[{pathGlob:"**/*.go",important:!0},{languages:["go"],important:!0}]},"vscjava.vscode-java-pack":{onFileOpen:[{pathGlob:"{**/*.java}",important:!0,whenNotInstalled:["ASF.apache-netbeans-java","Oracle.oracle-java"]},{languages:["java"],important:!0,whenNotInstalled:["ASF.apache-netbeans-java","Oracle.oracle-java"]}]},"ms-vscode.PowerShell":{onFileOpen:[{pathGlob:"{**/*.ps1,**/*.psd1,**/*.psm1}",important:!0},{languages:["powershell"],important:!0},{pathGlob:"{**/*.ps.config,**/*.ps1.config}"}]},"ms-azuretools.vscode-docker":{onFileOpen:[{pathGlob:"{**/dockerfile,**/Dockerfile,**/docker-compose.yml,**/docker-compose.*.yml}",important:!0},{languages:["dockerfile"],important:!0},{pathGlob:"{**/*.cs,**/project.json,**/global.json,**/*.csproj,**/*.cshtml,**/*.sln,**/appsettings.json,**/*.py,**/*.ipynb,**/*.js,**/*.ts,**/package.json}"}]},"vue.volar":{onFileOpen:[{pathGlob:"{**/*.vue}",important:!0},{languages:["vue"],important:!0}]},"ms-vscode.makefile-tools":{onFileOpen:[{pathGlob:"{**/makefile,**/Makefile}",important:!0},{languages:["makefile"],important:!0}]},"ms-vscode.cmake-tools":{onFileOpen:[{pathGlob:"{**/CMakeLists.txt}",important:!0}]},"svelte.svelte-vscode":{onFileOpen:[{pathGlob:"{**/*.svelte}",important:!0}]},"ms-vscode.vscode-github-issue-notebooks":{onFileOpen:[{pathGlob:"{**/*.github-issues}",important:!0}]},"ms-playwright.playwright":{onFileOpen:[{pathGlob:"{**/*playwright*.config.ts,**/*playwright*.config.js,**/*playwright*.config.mjs}",important:!0}]},"vscjava.vscode-gradle":{onFileOpen:[{pathGlob:"{**/gradlew,**/gradlew.bat,**/build.gradle,**/build.gradle.kts,**/settings.gradle,**/settings.gradle.kts}",important:!0}]},"REditorSupport.r":{onFileOpen:[{pathGlob:"{**/*.r}",important:!0},{languages:["r"],important:!0}]},"firefox-devtools.vscode-firefox-debug":{onFileOpen:[{pathGlob:"{**/*.ts,**/*.tsx,**/*.js,**/*.jsx,**/*.es6,**/.babelrc}"}]},"ms-edgedevtools.vscode-edge-devtools":{onFileOpen:[{pathGlob:"{**/*.ts,**/*.tsx,**/*.js,**/*.css,**/*.html}"}]},"Ionide.Ionide-fsharp":{onFileOpen:[{pathGlob:"{**/*.fsx,**/*.fsi,**/*.fs,**/*.ml,**/*.mli}"}]},"dbaeumer.vscode-eslint":{onFileOpen:[{pathGlob:"{**/*.js,**/*.jsx,**/*.es6,**/.eslintrc.*,**/.eslintrc,**/.babelrc,**/jsconfig.json}"}]},"bmewburn.vscode-intelephense-client":{onFileOpen:[{pathGlob:"{**/*.php,**/php.ini}"}]},"xdebug.php-debug":{onFileOpen:[{pathGlob:"{**/*.php,**/php.ini}"}]},"rust-lang.rust-analyzer":{onFileOpen:[{pathGlob:"{**/*.rs,**/*.rslib}"}]},"DavidAnson.vscode-markdownlint":{onFileOpen:[{pathGlob:"{**/*.md}"}]},"EditorConfig.EditorConfig":{onFileOpen:[{pathGlob:"{**/.editorconfig}"}]},"HookyQR.beautify":{onFileOpen:[{pathGlob:"{**/.jsbeautifyrc}"}]},"donjayamanne.githistory":{onFileOpen:[{pathGlob:"{**/.gitignore,**/.git}"}]},"eamodio.gitlens":{onFileOpen:[{pathGlob:"{**/.gitignore,**/.git}"}]},"Shopify.ruby-lsp":{onFileOpen:[{pathGlob:"{**/*.rb,**/*.erb,**/*.reek,**/.fasterer.yml,**/ruby-lint.yml,**/.rubocop.yml}"}]},"DotJoshJohnson.xml":{onFileOpen:[{pathGlob:"{**/*.xml}"}]},"stylelint.vscode-stylelint":{onFileOpen:[{pathGlob:"{**/.stylelintrc,**/stylelint.config.js}"}]},"ms-mssql.mssql":{onFileOpen:[{pathGlob:"{**/*.sql}"}]},"mtxr.sqltools":{onFileOpen:[{pathGlob:"{**/*.sql}"}]},"ms-vscode.sublime-keybindings":{onFileOpen:[{pathGlob:"{**/.sublime-project,**/.sublime-workspace}"}]},"k--kato.intellij-idea-keybindings":{onFileOpen:[{pathGlob:"{**/.idea}"}]},"christian-kohler.npm-intellisense":{onFileOpen:[{pathGlob:"{**/package.json}"}]},"Angular.ng-template":{onFileOpen:[{pathGlob:"{**/.angular-cli.json,**/angular.json,**/*.ng.html,**/*.ng,**/*.ngml}"}]},"vscjava.vscode-maven":{onFileOpen:[{pathGlob:"**/pom.xml"}]},"HashiCorp.terraform":{onFileOpen:[{pathGlob:"**/*.tf"}]},"ms-kubernetes-tools.vscode-kubernetes-tools":{onFileOpen:[{pathGlob:"{**/Chart.yaml}"}]},"betterthantomorrow.calva":{onFileOpen:[{pathGlob:"{**/*.clj,**/*.cljs}"}]},"vmware.vscode-boot-dev-pack":{onFileOpen:[{pathGlob:"{**/application.properties}"}]},"GitHub.vscode-github-actions":{onFileOpen:[{pathGlob:"{**/.github/workflows/*.yml}",important:!0}]},"circleci.circleci":{onFileOpen:[{pathGlob:"{**/.circleci/config.yml}"}]},"mechatroner.rainbow-csv":{onFileOpen:[{pathGlob:"**/*.csv",important:!0}]},"tomoki1207.pdf":{onFileOpen:[{pathGlob:"**/*.pdf",important:!0}]}},keymapExtensionTips:["vscodevim.vim","ms-vscode.sublime-keybindings","ms-vscode.atom-keybindings","ms-vscode.brackets-keybindings","ms-vscode.vs-keybindings","ms-vscode.notepadplusplus-keybindings","k--kato.intellij-idea-keybindings","alphabotsec.vscode-eclipse-keybindings","alefragnani.delphi-keybindings"],languageExtensionTips:["ms-python.python","codeium.windsurfpyright","ms-toolsai.jupyter","vscjava.vscode-java-pack","ecmel.vscode-html-css","vue.volar","bmewburn.vscode-intelephense-client","dsznajder.es7-react-js-snippets","golang.go","ms-vscode.powershell","dart-code.dart-code","rust-lang.rust-analyzer","Shopify.ruby-lsp"],linkProtectionTrustedDomains:["https://open-vsx.org","https://marketplace.windsurf.com","https://*.visualstudio.com","https://*.microsoft.com","https://aka.ms","https://*.gallerycdn.vsassets.io","https://*.github.com","https://login.microsoftonline.com","https://*.vscode.dev","https://*.github.dev","https://gh.io","https://portal.azure.com","https://raw.githubusercontent.com","https://private-user-images.githubusercontent.com","https://avatars.githubusercontent.com","https://*.codeium.com","https://*.windsurf.com","https://windsurf.com","https://codeium-staging-exafunction.vercel.app","https://staging.itsdev.in","https://app.devin.ai","https://app.beta.devin.ai","https://*.devinenterprise.com","https://beta.devinenterprise.com"],showTelemetryOptOut:!0,trustedExtensionAuthAccess:{github:["vscode.github","github.remotehub","ms-vscode.remote-server","github.vscode-pull-request-github","github.codespaces","github.copilot","github.copilot-chat","ms-vsliveshare.vsliveshare"],"github-enterprise":["vscode.github","github.remotehub","ms-vscode.remote-server","github.vscode-pull-request-github","github.codespaces","github.copilot","github.copilot-chat","ms-vsliveshare.vsliveshare"],microsoft:["ms-vscode.azure-repos","ms-vscode.remote-server","ms-vsliveshare.vsliveshare","ms-azuretools.vscode-azureresourcegroups","ms-edu.vscode-learning","ms-toolsai.vscode-ai","ms-toolsai.vscode-ai-remote"],"microsoft-sovereign-cloud":["ms-vscode.azure-repos","ms-vscode.remote-server","ms-vsliveshare.vsliveshare","ms-azuretools.vscode-azureresourcegroups","ms-edu.vscode-learning","ms-toolsai.vscode-ai","ms-toolsai.vscode-ai-remote"],windsurf_auth:["codeium.windsurf"]},verifiedExtensionPublishers:{codeium:"https://windsurf.com"},extensionPublisherDisplayNameOverrides:{codeium:"Windsurf"},trustedExtensionPublishers:["meta"],trustedExtensionProtocolHandlers:["vscode.git","vscode.github-authentication","vscode.microsoft-authentication","codeium.windsurf"],webExtensionTips:["codespaces-contrib.codeswing","ms-vscode.vscode-github-issue-notebooks","esbenp.prettier-vscode","hediet.vscode-drawio"],tunnelServerQualities:{stable:{serverApplicationName:"windsurf-server"},next:{serverApplicationName:"windsurf-server-next"},insider:{serverApplicationName:"windsurf-server-insiders"}},quality:"stable",codeiumVersion:"1.48.2",codeiumCommit:"0d4bf12ed4a7597cb8ae9016fe8474468aad98a2",windsurfVersion:"3.4.27",win32ContextMenu:{x64:{clsid:"79B67B12-BD17-4CE4-B89B-F5F1AD10609A"},arm64:{clsid:"848C41FC-A2D0-4E67-9728-2AF87E61C814"}},updateUrl:"https://windsurf-stable.codeium.com",version:"1.110.1",commit:"0d4bf12ed4a7597cb8ae9016fe8474468aad98a2",date:"2026-07-06T08:10:26.411Z"},Object.keys(xr).length===0&&Object.assign(xr,{version:"1.104.2-dev",nameShort:"Devin Dev",nameLong:"Devin 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",defaultChatAgent:{extensionId:"GitHub.copilot",chatExtensionId:"GitHub.copilot-chat",provider:{default:{id:"github",name:"GitHub"},enterprise:{id:"github-enterprise",name:"GitHub Enterprise"}},providerScopes:[]}});var fr=xr;var zt={Configuration:"base.contributions.configuration"};function tP(o,r){return o===r?!0:!o||!r?!1:typeof o=="string"||typeof r=="string"?o===r:o.id===r.id}var ms={properties:{},patternProperties:{}},Xd={properties:{},patternProperties:{}},Yd={properties:{},patternProperties:{}},Zd={properties:{},patternProperties:{}},eu={properties:{},patternProperties:{}},tu={properties:{},patternProperties:{}},Jl={properties:{},patternProperties:{}},no="vscode://schemas/settings/resourceLanguage";var ru=gt.as(Hl.JSONContribution),mg=class extends T{constructor(){super();this.registeredConfigurationDefaults=[];this.overrideIdentifiers=new Set;this._onDidSchemaChange=this._register(new w);this.onDidSchemaChange=this._onDidSchemaChange.event;this._onDidUpdateConfiguration=this._register(new w);this.onDidUpdateConfiguration=this._onDidUpdateConfiguration.event;this.configurationDefaultsOverrides=new Map,this.defaultLanguageConfigurationOverridesNode={id:"defaultOverrides",title:S(1850,null),properties:{}},this.configurationContributors=[this.defaultLanguageConfigurationOverridesNode],this.resourceLanguageSettingsSchema={properties:{},patternProperties:{},additionalProperties:!0,allowTrailingCommas:!0,allowComments:!0},this.configurationProperties={},this.policyConfigurations=new Map,this.excludedConfigurationProperties={},ru.registerSchema(no,this.resourceLanguageSettingsSchema),this.registerOverridePropertyPatternKey()}registerConfiguration(e,t=!0){return this.registerConfigurations([e],t),e}registerConfigurations(e,t=!0){let n=new Set;this.doRegisterConfigurations(e,t,n),ru.registerSchema(no,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:n})}deregisterConfigurations(e){let t=new Set;this.doDeregisterConfigurations(e,t),ru.registerSchema(no,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:t})}updateConfigurations({add:e,remove:t}){let n=new Set;this.doDeregisterConfigurations(t,n),this.doRegisterConfigurations(e,!1,n),ru.registerSchema(no,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:n})}registerDefaultConfigurations(e){let t=new Set;this.doRegisterDefaultConfigurations(e,t),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:t,defaultsOverrides:!0})}doRegisterDefaultConfigurations(e,t){this.registeredConfigurationDefaults.push(...e);let n=[];for(let{overrides:i,source:s}of e)for(let a in i){t.add(a);let l=this.configurationDefaultsOverrides.get(a)??this.configurationDefaultsOverrides.set(a,{configurationDefaultOverrides:[]}).get(a),c=i[a];if(l.configurationDefaultOverrides.push({value:c,source:s}),Pn.test(a)){let d=this.mergeDefaultConfigurationsForOverrideIdentifier(a,c,s,l.configurationDefaultOverrideValue);if(!d)continue;l.configurationDefaultOverrideValue=d,this.updateDefaultOverrideProperty(a,d,s),n.push(...gs(a))}else{let d=this.mergeDefaultConfigurationsForConfigurationProperty(a,c,s,l.configurationDefaultOverrideValue);if(!d)continue;l.configurationDefaultOverrideValue=d;let u=this.configurationProperties[a];u&&(this.updatePropertyDefaultValue(a,u),this.updateSchema(a,u))}}this.doRegisterOverrideIdentifiers(n)}deregisterDefaultConfigurations(e){let t=new Set;this.doDeregisterDefaultConfigurations(e,t),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:t,defaultsOverrides:!0})}doDeregisterDefaultConfigurations(e,t){for(let n of e){let i=this.registeredConfigurationDefaults.indexOf(n);i!==-1&&this.registeredConfigurationDefaults.splice(i,1)}for(let{overrides:n,source:i}of e)for(let s in n){let a=this.configurationDefaultsOverrides.get(s);if(!a)continue;let l=a.configurationDefaultOverrides.findIndex(c=>i?tP(c.source,i):c.value===n[s]);if(l!==-1){if(a.configurationDefaultOverrides.splice(l,1),a.configurationDefaultOverrides.length===0&&this.configurationDefaultsOverrides.delete(s),Pn.test(s)){let c;for(let d of a.configurationDefaultOverrides)c=this.mergeDefaultConfigurationsForOverrideIdentifier(s,d.value,d.source,c);c&&!nd(c.value)?(a.configurationDefaultOverrideValue=c,this.updateDefaultOverrideProperty(s,c,i)):(this.configurationDefaultsOverrides.delete(s),delete this.configurationProperties[s],delete this.defaultLanguageConfigurationOverridesNode.properties[s])}else{let c;for(let u of a.configurationDefaultOverrides)c=this.mergeDefaultConfigurationsForConfigurationProperty(s,u.value,u.source,c);a.configurationDefaultOverrideValue=c;let d=this.configurationProperties[s];d&&(this.updatePropertyDefaultValue(s,d),this.updateSchema(s,d))}t.add(s)}}this.updateOverridePropertyPatternKey()}updateDefaultOverrideProperty(e,t,n){let i={section:{id:this.defaultLanguageConfigurationOverridesNode.id,title:this.defaultLanguageConfigurationOverridesNode.title,order:this.defaultLanguageConfigurationOverridesNode.order,extensionInfo:this.defaultLanguageConfigurationOverridesNode.extensionInfo},type:"object",default:t.value,description:S(1849,null,xI(e)),$ref:no,defaultDefaultValue:t.value,source:n,defaultValueSource:n};this.configurationProperties[e]=i,this.defaultLanguageConfigurationOverridesNode.properties[e]=i}mergeDefaultConfigurationsForOverrideIdentifier(e,t,n,i){let s=i?.value||{},a=i?.source??new Map;if(!(a instanceof Map)){console.error("objectConfigurationSources is not a Map");return}for(let l of Object.keys(t)){let c=t[l];if(Re(c)&&(st(s[l])||Re(s[l]))){if(s[l]={...s[l]??{},...c},n)for(let u in c)a.set(`${l}.${u}`,n)}else s[l]=c,n?a.set(l,n):a.delete(l)}return{value:s,source:a}}mergeDefaultConfigurationsForConfigurationProperty(e,t,n,i){let s=this.configurationProperties[e],a=i?.value??s?.defaultDefaultValue,l=n;if(Re(t)&&(s!==void 0&&s.type==="object"||s===void 0&&(st(a)||Re(a)))){if(l=i?.source??new Map,!(l instanceof Map)){console.error("defaultValueSource is not a Map");return}for(let d in t)n&&l.set(`${e}.${d}`,n);t={...Re(a)?a:{},...t}}return{value:t,source:l}}deltaConfiguration(e){let t=!1,n=new Set;e.removedDefaults&&(this.doDeregisterDefaultConfigurations(e.removedDefaults,n),t=!0),e.addedDefaults&&(this.doRegisterDefaultConfigurations(e.addedDefaults,n),t=!0),e.removedConfigurations&&this.doDeregisterConfigurations(e.removedConfigurations,n),e.addedConfigurations&&this.doRegisterConfigurations(e.addedConfigurations,!1,n),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:n,defaultsOverrides:t})}notifyConfigurationSchemaUpdated(...e){this._onDidSchemaChange.fire()}registerOverrideIdentifiers(e){this.doRegisterOverrideIdentifiers(e),this._onDidSchemaChange.fire()}doRegisterOverrideIdentifiers(e){for(let t of e)this.overrideIdentifiers.add(t);this.updateOverridePropertyPatternKey()}doRegisterConfigurations(e,t,n){e.forEach(i=>{this.validateAndRegisterProperties(i,t,i.extensionInfo,i.restrictedProperties,void 0,n),this.configurationContributors.push(i),this.registerJSONConfiguration(i)})}doDeregisterConfigurations(e,t){let n=i=>{if(i.properties)for(let s in i.properties){t.add(s);let a=this.configurationProperties[s];a?.policy?.name&&this.policyConfigurations.delete(a.policy.name),delete this.configurationProperties[s],this.removeFromSchema(s,i.properties[s])}i.allOf?.forEach(s=>n(s))};for(let i of e){n(i);let s=this.configurationContributors.indexOf(i);s!==-1&&this.configurationContributors.splice(s,1)}}validateAndRegisterProperties(e,t=!0,n,i,s=4,a){s=ft(e.scope)?s:e.scope;let l=e.properties;if(l)for(let d in l){let u=l[d];if(u.section={id:e.id,title:e.title,order:e.order,extensionInfo:e.extensionInfo},t&&nP(d,u,n?.id)){delete l[d];continue}u.source=n,u.defaultDefaultValue=l[d].default,this.updatePropertyDefaultValue(d,u),Pn.test(d)?u.scope=void 0:(u.scope=ft(u.scope)?s:u.scope,u.restricted=ft(u.restricted)?!!i?.includes(d):u.restricted),u.experiment?u.tags?.some(h=>h.toLowerCase()==="onexp")||(u.tags=u.tags??[],u.tags.push("onExP")):u.tags?.some(h=>h.toLowerCase()==="onexp")&&(console.error(`Invalid tag 'onExP' found for property '${d}'. Please use 'experiment' property instead.`),u.experiment={mode:"startup"});let p=l[d].hasOwnProperty("included")&&!l[d].included,m=l[d].policy?.name;p?(this.excludedConfigurationProperties[d]=l[d],m&&(this.policyConfigurations.set(m,d),a.add(d)),delete l[d]):(a.add(d),m&&this.policyConfigurations.set(m,d),this.configurationProperties[d]=l[d],!l[d].deprecationMessage&&l[d].markdownDeprecationMessage&&(l[d].deprecationMessage=l[d].markdownDeprecationMessage))}let c=e.allOf;if(c)for(let d of c)this.validateAndRegisterProperties(d,t,n,i,s,a)}getConfigurations(){return this.configurationContributors}getConfigurationProperties(){return this.configurationProperties}getPolicyConfigurations(){return this.policyConfigurations}getExcludedConfigurationProperties(){return this.excludedConfigurationProperties}getRegisteredDefaultConfigurations(){return[...this.registeredConfigurationDefaults]}getConfigurationDefaultsOverrides(){let e=new Map;for(let[t,n]of this.configurationDefaultsOverrides)n.configurationDefaultOverrideValue&&e.set(t,n.configurationDefaultOverrideValue);return e}registerJSONConfiguration(e){let t=n=>{let i=n.properties;if(i)for(let a in i)this.updateSchema(a,i[a]);n.allOf?.forEach(t)};t(e)}updateSchema(e,t){switch(ms.properties[e]=t,t.scope){case 1:Xd.properties[e]=t;break;case 2:Zd.properties[e]=t;break;case 3:Yd.properties[e]=t;break;case 7:eu.properties[e]=t;break;case 4:tu.properties[e]=t;break;case 5:Jl.properties[e]=t;break;case 6:Jl.properties[e]=t,this.resourceLanguageSettingsSchema.properties[e]=t;break}}removeFromSchema(e,t){switch(delete ms.properties[e],t.scope){case 1:delete Xd.properties[e];break;case 2:delete Zd.properties[e];break;case 3:delete Yd.properties[e];break;case 7:delete eu.properties[e];break;case 4:delete tu.properties[e];break;case 5:case 6:delete Jl.properties[e],delete this.resourceLanguageSettingsSchema.properties[e];break}}updateOverridePropertyPatternKey(){for(let e of this.overrideIdentifiers.values()){let t=`[${e}]`,n={type:"object",description:S(1851,null),errorMessage:S(1852,null),$ref:no};this.updatePropertyDefaultValue(t,n),ms.properties[t]=n,Xd.properties[t]=n,Yd.properties[t]=n,Zd.properties[t]=n,eu.properties[t]=n,tu.properties[t]=n,Jl.properties[t]=n}}registerOverridePropertyPatternKey(){let e={type:"object",description:S(1851,null),errorMessage:S(1852,null),$ref:no};ms.patternProperties[pi]=e,Xd.patternProperties[pi]=e,Yd.patternProperties[pi]=e,Zd.patternProperties[pi]=e,eu.patternProperties[pi]=e,tu.patternProperties[pi]=e,Jl.patternProperties[pi]=e,this._onDidSchemaChange.fire()}updatePropertyDefaultValue(e,t){let n=this.configurationDefaultsOverrides.get(e)?.configurationDefaultOverrideValue,i,s;n&&(!t.disallowConfigurationDefault||!n.source)&&(i=n.value,s=n.source),st(i)&&(i=t.defaultDefaultValue,s=void 0),st(i)&&(i=rP(t.type)),t.default=i,t.defaultValueSource=s}},RI="\\[([^\\]]+)\\]",PI=new RegExp(RI,"g"),pi=`^(${RI})+$`,Pn=new RegExp(pi);function gs(o){let r=[];if(Pn.test(o)){let e=PI.exec(o);for(;e?.length;){let t=e[1].trim();t&&r.push(t),e=PI.exec(o)}}return dt(r)}function TI(o){return o.reduce((r,e)=>`${r}[${e}]`,"")}function rP(o){switch(Array.isArray(o)?o[0]:o){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};default:return null}}var nu=new mg;gt.add(zt.Configuration,nu);function nP(o,r,e){return o.trim()?Pn.test(o)?S(1848,null,o):nu.getConfigurationProperties()[o]!==void 0&&(!e||!iP.has(e.toLowerCase()))?S(1846,null,o):r.policy?.name&&nu.getPolicyConfigurations().get(r.policy?.name)!==void 0?S(1845,null,o,r.policy?.name,nu.getPolicyConfigurations().get(r.policy?.name)):null:S(1847,null)}function gg(o){let r={};for(let e of o){let t=e.properties;if(Re(t))for(let n in t)r[n]=t[n];e.allOf&&Object.assign(r,gg(e.allOf))}return r}function CI(o){switch(o){case"application":return 1;case"machine":return 2;case"resource":return 5;case"machine-overridable":return 7;case"language-overridable":return 6;default:return 4}}var iP=new Set(fr.defaultChatAgent?[fr.defaultChatAgent.extensionId,fr.defaultChatAgent.chatExtensionId].map(o=>o.toLowerCase()):[]);var ou="extensions.user.cache",DI="extensions.builtin.cache",su="undefined_publisher";var on=class{constructor(r){this.value=r,this._lower=r.toLowerCase()}static equals(r,e){if(typeof r>"u"||r===null)return typeof e>"u"||e===null;if(typeof e>"u"||e===null)return!1;if(typeof r=="string"||typeof e=="string"){let t=typeof r=="string"?r:r.value,n=typeof e=="string"?e:e.value;return yr(t,n)}return r._lower===e._lower}static toKey(r){return typeof r=="string"?r.toLowerCase():r._lower}};var iu=class{constructor(){this._map=new Map}clear(){this._map.clear()}delete(r){this._map.delete(on.toKey(r))}get(r){return this._map.get(on.toKey(r))}has(r){return this._map.has(on.toKey(r))}set(r,e){this._map.set(on.toKey(r),e)}values(){return this._map.values()}forEach(r){this._map.forEach(r)}[Symbol.iterator](){return this._map[Symbol.iterator]()}};function Ql(o){return sP(o)}function sP(o){return o.contributes&&o.contributes.localizations?o.contributes.localizations.length>0:!1}function _I(o){return o.map(r=>{let[e,t]=r.split("@");return{proposalName:e,version:t?parseInt(t):void 0}})}function kI(o){return o.map(r=>r.split("@")[0])}var pU=L("IBuiltinExtensionsScannerService");var hg=class{constructor(){this._value="";this._pos=0}reset(r){return this._value=r,this._pos=0,this}next(){return this._pos+=1,this}hasNext(){return this._pos<this._value.length-1}cmp(r){let e=r.charCodeAt(0),t=this._value.charCodeAt(this._pos);return e-t}value(){return this._value[this._pos]}},vg=class{constructor(r=!0){this._caseSensitive=r}reset(r){return this._value=r,this._from=0,this._to=0,this.next()}hasNext(){return this._to<this._value.length}next(){this._from=this._to;let r=!0;for(;this._to<this._value.length;this._to++)if(this._value.charCodeAt(this._to)===46)if(r)this._from++;else break;else r=!1;return this}cmp(r){return this._caseSensitive?hd(r,this._value,0,r.length,this._from,this._to):Ki(r,this._value,0,r.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}},au=class{constructor(r=!0,e=!0){this._splitOnBackslash=r;this._caseSensitive=e}reset(r){this._from=0,this._to=0,this._value=r,this._valueLen=r.length;for(let e=r.length-1;e>=0;e--,this._valueLen--){let t=this._value.charCodeAt(e);if(!(t===47||this._splitOnBackslash&&t===92))break}return this.next()}hasNext(){return this._to<this._valueLen}next(){this._from=this._to;let r=!0;for(;this._to<this._valueLen;this._to++){let e=this._value.charCodeAt(this._to);if(e===47||this._splitOnBackslash&&e===92)if(r)this._from++;else break;else r=!1}return this}cmp(r){return this._caseSensitive?hd(r,this._value,0,r.length,this._from,this._to):Ki(r,this._value,0,r.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}};var yg=class{constructor(r,e){this._ignorePathCasing=r;this._ignoreQueryAndFragment=e;this._states=[];this._stateIdx=0}reset(r){return this._value=r,this._states=[],this._value.scheme&&this._states.push(1),this._value.authority&&this._states.push(2),this._value.path&&(this._pathIterator=new au(!1,!this._ignorePathCasing(r)),this._pathIterator.reset(r.path),this._pathIterator.value()&&this._states.push(3)),this._ignoreQueryAndFragment(r)||(this._value.query&&this._states.push(4),this._value.fragment&&this._states.push(5)),this._stateIdx=0,this}next(){return this._states[this._stateIdx]===3&&this._pathIterator.hasNext()?this._pathIterator.next():this._stateIdx+=1,this}hasNext(){return this._states[this._stateIdx]===3&&this._pathIterator.hasNext()||this._stateIdx<this._states.length-1}cmp(r){if(this._states[this._stateIdx]===1)return Xo(r,this._value.scheme);if(this._states[this._stateIdx]===2)return Xo(r,this._value.authority);if(this._states[this._stateIdx]===3)return this._pathIterator.cmp(r);if(this._states[this._stateIdx]===4)return zi(r,this._value.query);if(this._states[this._stateIdx]===5)return zi(r,this._value.fragment);throw new Error}value(){if(this._states[this._stateIdx]===1)return this._value.scheme;if(this._states[this._stateIdx]===2)return this._value.authority;if(this._states[this._stateIdx]===3)return this._pathIterator.value();if(this._states[this._stateIdx]===4)return this._value.query;if(this._states[this._stateIdx]===5)return this._value.fragment;throw new Error}},Bn=class o{static{this.Val=Symbol("undefined_placeholder")}static wrap(r){return r===void 0?o.Val:r}static unwrap(r){return r===o.Val?void 0:r}},hs=class{constructor(){this.height=1;this.value=void 0;this.key=void 0;this.left=void 0;this.mid=void 0;this.right=void 0}isEmpty(){return!this.left&&!this.mid&&!this.right&&this.value===void 0}rotateLeft(){let r=this.right;return this.right=r.left,r.left=this,this.updateHeight(),r.updateHeight(),r}rotateRight(){let r=this.left;return this.left=r.right,r.right=this,this.updateHeight(),r.updateHeight(),r}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 Mr=class o{static forUris(r=()=>!1,e=()=>!1){return new o(new yg(r,e))}static forPaths(r=!1){return new o(new au(void 0,!r))}static forStrings(){return new o(new hg)}static forConfigKeys(){return new o(new vg)}constructor(r){this._iter=r}clear(){this._root=void 0}fill(r,e){if(e){let t=e.slice(0);hm(t);for(let n of t)this.set(n,r)}else{let t=r.slice(0);hm(t);for(let n of t)this.set(n[0],n[1])}}set(r,e){let t=this._iter.reset(r),n;this._root||(this._root=new hs,this._root.segment=t.value());let i=[];for(n=this._root;;){let a=t.cmp(n.segment);if(a>0)n.left||(n.left=new hs,n.left.segment=t.value()),i.push([-1,n]),n=n.left;else if(a<0)n.right||(n.right=new hs,n.right.segment=t.value()),i.push([1,n]),n=n.right;else if(t.hasNext())t.next(),n.mid||(n.mid=new hs,n.mid.segment=t.value()),i.push([0,n]),n=n.mid;else break}let s=Bn.unwrap(n.value);n.value=Bn.wrap(e),n.key=r;for(let a=i.length-1;a>=0;a--){let l=i[a][1];l.updateHeight();let c=l.balanceFactor();if(c<-1||c>1){let d=i[a][0],u=i[a+1][0];if(d===1&&u===1)i[a][1]=l.rotateLeft();else if(d===-1&&u===-1)i[a][1]=l.rotateRight();else if(d===1&&u===-1)l.right=i[a+1][1]=i[a+1][1].rotateRight(),i[a][1]=l.rotateLeft();else if(d===-1&&u===1)l.left=i[a+1][1]=i[a+1][1].rotateLeft(),i[a][1]=l.rotateRight();else throw new Error;if(a>0)switch(i[a-1][0]){case-1:i[a-1][1].left=i[a][1];break;case 1:i[a-1][1].right=i[a][1];break;case 0:i[a-1][1].mid=i[a][1];break}else this._root=i[0][1]}}return s}get(r){return Bn.unwrap(this._getNode(r)?.value)}_getNode(r){let e=this._iter.reset(r),t=this._root;for(;t;){let n=e.cmp(t.segment);if(n>0)t=t.left;else if(n<0)t=t.right;else if(e.hasNext())e.next(),t=t.mid;else break}return t}has(r){let e=this._getNode(r);return!(e?.value===void 0&&e?.mid===void 0)}delete(r){return this._delete(r,!1)}deleteSuperstr(r){return this._delete(r,!0)}_delete(r,e){let t=this._iter.reset(r),n=[],i=this._root;for(;i;){let s=t.cmp(i.segment);if(s>0)n.push([-1,i]),i=i.left;else if(s<0)n.push([1,i]),i=i.right;else if(t.hasNext())t.next(),n.push([0,i]),i=i.mid;else break}if(i){if(e?(i.left=void 0,i.mid=void 0,i.right=void 0,i.height=1):(i.key=void 0,i.value=void 0),!i.mid&&!i.value)if(i.left&&i.right){let s=[[1,i]],a=this._min(i.right,s);if(a.key){i.key=a.key,i.value=a.value,i.segment=a.segment;let l=a.right;if(s.length>1){let[d,u]=s[s.length-1];switch(d){case-1:u.left=l;break;case 0:Bo(!1);case 1:Bo(!1)}}else i.right=l;let c=this._balanceByStack(s);if(n.length>0){let[d,u]=n[n.length-1];switch(d){case-1:u.left=c;break;case 0:u.mid=c;break;case 1:u.right=c;break}}else this._root=c}}else{let s=i.left??i.right;if(n.length>0){let[a,l]=n[n.length-1];switch(a){case-1:l.left=s;break;case 0:l.mid=s;break;case 1:l.right=s;break}}else this._root=s}this._root=this._balanceByStack(n)??this._root}}_min(r,e){for(;r.left;)e.push([-1,r]),r=r.left;return r}_balanceByStack(r){for(let e=r.length-1;e>=0;e--){let t=r[e][1];t.updateHeight();let n=t.balanceFactor();if(n>1?(t.right.balanceFactor()>=0||(t.right=t.right.rotateRight()),r[e][1]=t.rotateLeft()):n<-1&&(t.left.balanceFactor()<=0||(t.left=t.left.rotateLeft()),r[e][1]=t.rotateRight()),e>0)switch(r[e-1][0]){case-1:r[e-1][1].left=r[e][1];break;case 1:r[e-1][1].right=r[e][1];break;case 0:r[e-1][1].mid=r[e][1];break}else return r[0][1]}}findSubstr(r){let e=this._iter.reset(r),t=this._root,n;for(;t;){let i=e.cmp(t.segment);if(i>0)t=t.left;else if(i<0)t=t.right;else if(e.hasNext())e.next(),n=Bn.unwrap(t.value)||n,t=t.mid;else break}return t&&Bn.unwrap(t.value)||n}findSuperstr(r){return this._findSuperstrOrElement(r,!1)}_findSuperstrOrElement(r,e){let t=this._iter.reset(r),n=this._root;for(;n;){let i=t.cmp(n.segment);if(i>0)n=n.left;else if(i<0)n=n.right;else if(t.hasNext())t.next(),n=n.mid;else return n.mid?this._entries(n.mid):e?Bn.unwrap(n.value):void 0}}hasElementOrSubtree(r){return this._findSuperstrOrElement(r,!0)!==void 0}forEach(r){for(let[e,t]of this)r(t,e)}*[Symbol.iterator](){yield*this._entries(this._root)}_entries(r){let e=[];return this._dfsEntries(r,e),e[Symbol.iterator]()}_dfsEntries(r,e){r&&(r.left&&this._dfsEntries(r.left,e),r.value!==void 0&&e.push([r.key,Bn.unwrap(r.value)]),r.mid&&this._dfsEntries(r.mid,e),r.right&&this._dfsEntries(r.right,e))}_isBalanced(){let r=e=>{if(!e)return!0;let t=e.balanceFactor();return t<-1||t>1?!1:r(e.left)&&r(e.right)};return r(this._root)}};var W=L("fileService");function io(o){return o.create===!0}function Ar(o){return!!(o.capabilities&2)}function UI(o){return!!(o.capabilities&524288)}function Xl(o){return!!(o.capabilities&8)}function cu(o){return!!(o.capabilities&131072)}function LI(o){return!!(o.capabilities&262144)}function Gn(o){return!!(o.capabilities&4)}function du(o){return!!(o.capabilities&16)}function uu(o){return Ar(o)?!!(o.capabilities&16384):!1}function Sg(o){return Ar(o)?!!(o.capabilities&32768):!1}function MI(o){return!!(o.capabilities&65536)}var vs=class o extends Error{constructor(e,t){super(e);this.code=t}static create(e,t){let n=new o(e.toString(),t);return aP(n,t),n}};function Fr(o,r){return vs.create(o,r)}function qn(o){return o||Fr(S(2068,null),"Unknown")}function aP(o,r){return o.name=r?`${r} (FileSystemError)`:"FileSystemError",o}function Yl(o){if(!o)return"Unknown";if(o instanceof vs)return o.code;let r=/^(.+) \(FileSystemError\)$/.exec(o.name);if(!r)return"Unknown";switch(r[1]){case"EntryExists":return"EntryExists";case"EntryIsADirectory":return"EntryIsADirectory";case"EntryNotADirectory":return"EntryNotADirectory";case"EntryNotFound":return"EntryNotFound";case"EntryTooLarge":return"EntryTooLarge";case"EntryWriteLocked":return"EntryWriteLocked";case"NoPermissions":return"NoPermissions";case"Unavailable":return"Unavailable"}return"Unknown"}function _e(o){if(o instanceof et)return o.fileOperationResult;switch(Yl(o)){case"EntryNotFound":return 1;case"EntryIsADirectory":return 0;case"EntryNotADirectory":return 9;case"EntryWriteLocked":return 5;case"NoPermissions":return 6;case"EntryExists":return 4;case"EntryTooLarge":return 7;default:return 10}}var $n=class{constructor(r,e,t){this.resource=r;this.operation=e;this.target=t}isOperation(r){return this.operation===r}};var lu=class o{constructor(r,e){this.ignorePathCasing=e;this.correlationId=void 0;this.added=new cr(()=>{let r=Mr.forUris(()=>this.ignorePathCasing);return r.fill(this.rawAdded.map(e=>[e,!0])),r});this.updated=new cr(()=>{let r=Mr.forUris(()=>this.ignorePathCasing);return r.fill(this.rawUpdated.map(e=>[e,!0])),r});this.deleted=new cr(()=>{let r=Mr.forUris(()=>this.ignorePathCasing);return r.fill(this.rawDeleted.map(e=>[e,!0])),r});this.rawAdded=[];this.rawUpdated=[];this.rawDeleted=[];for(let t of r){switch(t.type){case 1:this.rawAdded.push(t.resource);break;case 0:this.rawUpdated.push(t.resource);break;case 2:this.rawDeleted.push(t.resource);break}this.correlationId!==o.MIXED_CORRELATION&&(typeof t.cId=="number"?this.correlationId===void 0?this.correlationId=t.cId:this.correlationId!==t.cId&&(this.correlationId=o.MIXED_CORRELATION):this.correlationId!==void 0&&(this.correlationId=o.MIXED_CORRELATION))}}static{this.MIXED_CORRELATION=null}contains(r,...e){return this.doContains(r,{includeChildren:!1},...e)}affects(r,...e){return this.doContains(r,{includeChildren:!0},...e)}doContains(r,e,...t){if(!r)return!1;let n=t.length>0;return!!((!n||t.includes(1))&&(this.added.value.get(r)||e.includeChildren&&this.added.value.findSuperstr(r))||(!n||t.includes(0))&&(this.updated.value.get(r)||e.includeChildren&&this.updated.value.findSuperstr(r))||(!n||t.includes(2))&&(this.deleted.value.findSubstr(r)||e.includeChildren&&this.deleted.value.findSuperstr(r)))}gotAdded(){return this.rawAdded.length>0}gotDeleted(){return this.rawDeleted.length>0}gotUpdated(){return this.rawUpdated.length>0}correlates(r){return this.correlationId===r}hasCorrelation(){return typeof this.correlationId=="number"}};function AI(o,r,e){return!o||!r||o===r||r.length>o.length?!1:(r.charAt(r.length-1)!==Ut&&(r+=Ut),e?ji(o,r):o.indexOf(r)===0)}var et=class extends Error{constructor(e,t,n){super(e);this.fileOperationResult=t;this.options=n}},ys=class extends et{constructor(e,t,n,i){super(e,t,i);this.fileOperationResult=t;this.size=n}},Ss=class extends et{constructor(e,t,n){super(e,2,n);this.stat=t}};var pu="";function Ig(o){if(!(typeof o.size!="number"||typeof o.mtime!="number"))return o.mtime.toString(29)+o.size.toString(31)}var fi=class o{static{this.KB=1024}static{this.MB=o.KB*o.KB}static{this.GB=o.MB*o.KB}static{this.TB=o.GB*o.KB}static formatSize(r){return Un(r)||(r=0),r<o.KB?S(2063,null,r.toFixed(0)):r<o.MB?S(2065,null,(r/o.KB).toFixed(2)):r<o.GB?S(2066,null,(r/o.MB).toFixed(2)):r<o.TB?S(2064,null,(r/o.GB).toFixed(2)):S(2067,null,(r/o.TB).toFixed(2))}};var xg="^([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$",Eg=new RegExp(xg),FI="__web_extension",OI="skipWalkthrough",ec="skipPublisherTrust",tc="extensionInstallSource",NI="dependecyOrPackExtensionInstall",VI="clientTargetPlatform";function wg(o){switch(o){case"win32-x64":return"Windows 64 bit";case"win32-arm64":return"Windows ARM";case"linux-x64":return"Linux 64 bit";case"linux-arm64":return"Linux ARM 64";case"linux-armhf":return"Linux ARM";case"alpine-x64":return"Alpine Linux 64 bit";case"alpine-arm64":return"Alpine ARM 64";case"darwin-x64":return"Mac";case"darwin-arm64":return"Mac Silicon";case"web":return"Web";case"universal":return"universal";case"unknown":return"unknown";case"undefined":return"undefined"}}function WI(o){switch(o){case"win32-x64":return"win32-x64";case"win32-arm64":return"win32-arm64";case"linux-x64":return"linux-x64";case"linux-arm64":return"linux-arm64";case"linux-armhf":return"linux-armhf";case"alpine-x64":return"alpine-x64";case"alpine-arm64":return"alpine-arm64";case"darwin-x64":return"darwin-x64";case"darwin-arm64":return"darwin-arm64";case"web":return"web";case"universal":return"universal";default:return"unknown"}}function mu(o,r){switch(o){case 3:return r==="x64"?"win32-x64":r==="arm64"?"win32-arm64":"unknown";case 2:return r==="x64"?"linux-x64":r==="arm64"?"linux-arm64":r==="arm"?"linux-armhf":"unknown";case"alpine":return r==="x64"?"alpine-x64":r==="arm64"?"alpine-arm64":"unknown";case 1:return r==="x64"?"darwin-x64":r==="arm64"?"darwin-arm64":"unknown";case 0:return"web"}}function Is(o,r){return r==="web"&&!o.includes("web")}function rc(o,r,e){return Is(r,e)?!1:o==="undefined"||o==="universal"?!0:o==="unknown"?!1:o===e}function BI(o){let r=o;return!!r&&typeof r=="object"&&typeof r.id=="string"&&(!r.uuid||typeof r.uuid=="string")}var At=L("extensionGalleryService");var Or=class extends Error{constructor(e,t){super(e);this.code=t;this.name=t}};var Ge=class extends Error{constructor(e,t){super(e);this.code=t;this.name=t}},rr=L("extensionManagementService"),nc="extensionsIdentifiers/disabled";var gu=L("IGlobalExtensionEnablementService"),Pg=L("IExtensionTipsService"),sn=L("IAllowedExtensionsService");async function hu(o,r){let e;try{e=await r.resolve(o)}catch(t){if(t.fileOperationResult===1)return 0;throw t}return e.children?(await Promise.all(e.children.map(n=>hu(n.resource,r)))).reduce((n,i)=>n+i,0):e.size??0}var zU=Sm(1971,"Extensions"),KU=Sm(1988,"Preferences"),vu="extensions.allowed",$I="extensions.verifySignature",GI="extensions.requestTimeout";gt.as(zt.Configuration).registerConfiguration({id:"extensions",order:30,title:S(1987,null),type:"object",properties:{[vu]:{type:"object",markdownDescription:S(1977,null),default:"*",defaultSnippets:[{body:{},description:S(1982,null)},{body:{"*":!0},description:S(1978,null)}],scope:1,policy:{name:"AllowedExtensions",category:"Extensions",minimumVersion:"1.96",localization:{description:{key:"extensions.allowed.policy",value:S(1983,null)}}},additionalProperties:!1,patternProperties:{"([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$":{anyOf:[{type:["boolean","string"],enum:[!0,!1,"stable"],description:S(1975,null),enumDescriptions:[S(1981,null),S(1979,null),S(1980,null)]},{type:"array",items:{type:"string"},description:S(1976,null)}]},"([a-z0-9A-Z][a-z0-9-A-Z]*)$":{type:["boolean","string"],enum:[!0,!1,"stable"],description:S(1970,null),enumDescriptions:[S(1986,null),S(1984,null),S(1985,null)]},"\\*":{type:"boolean",enum:[!0,!1],description:S(1972,null),enumDescriptions:[S(1974,null),S(1973,null)]}}}}});function qI(o,r){return o?r?.capabilities.signing?.allPrivateRepositorySigned===!0:r?.capabilities.signing?.allPublicRepositorySigned===!0}function cP(o){return o.tags.find(r=>r.startsWith("lp-"))?.split("lp-")[1]}var ic=L("languagePackService"),bs=class extends T{constructor(e){super();this.extensionGalleryService=e}async getAvailableLanguages(){let e=new mt;setTimeout(()=>e.cancel(),1e3);let t;try{t=await this.extensionGalleryService.query({text:'category:"language packs"',pageSize:20},e.token)}catch{return[]}let i=t.firstPage.filter(s=>s.properties.localizedLanguages?.length&&s.tags.some(a=>a.startsWith("lp-"))).map(s=>{let a=s.properties.localizedLanguages?.[0],l=cP(s);return{...this.createQuickPickItem(l,a,s),extensionId:s.identifier.id,galleryExtension:s}});return i.push(this.createQuickPickItem("en","English")),i}createQuickPickItem(e,t,n){let i=t??e,s;if(i!==e&&(s=`(${e})`),e.toLowerCase()===Cr.toLowerCase()&&(s??="",s+=S(2116,null)),n?.installCount){s??="";let a=n.installCount,l;a>1e6?l=`${Math.floor(a/1e5)/10}M`:a>1e3?l=`${Math.floor(a/1e3)}K`:l=String(a),s+=` $(cloud-download) ${l}`}return{id:e,label:i,description:s}}};bs=b([g(0,At)],bs);var xs=class extends T{constructor(e){super();this.localizationsService=e;this.updateLocalizations()}updateLocalizations(){this.localizationsService.update()}};xs=b([g(0,ic)],xs);var Es=class extends T{constructor(e,t){super();this.environmentService=e;this.logService=t;this._register(new It(()=>{this.cleanUpOldLogs()},10*1e3)).schedule()}async cleanUpOldLogs(){this.logService.trace("[logs cleanup]: Starting to clean up old logs.");try{let e=Nn(this.environmentService.logsHome),t=wd(this.environmentService.logsHome.with({scheme:re.file})).fsPath,s=(await ce.readdir(t)).filter(l=>/^\d{8}T\d{6}$/.test(l)).sort().filter(l=>l!==e),a=s.slice(0,Math.max(0,s.length-9));a.length>0&&(this.logService.trace(`[logs cleanup]: Removing log folders '${a.join(", ")}'`),await Promise.all(a.map(l=>ce.rm(G(t,l)))))}catch(e){Me(e)}}};Es=b([g(0,X),g(1,V)],Es);var yu=class extends T{constructor(e,t,n){super();this.channel=e;this.profile=t;this.workspace=n}async getItems(){let e={profile:this.profile,workspace:this.workspace},t=await this.channel.call("getItems",e);return new Map(t)}updateItems(e){let t={profile:this.profile,workspace:this.workspace};return e.insert&&(t.insert=Array.from(e.insert.entries())),e.delete&&(t.delete=Array.from(e.delete.values())),this.channel.call("updateItems",t)}optimize(){let e={profile:this.profile,workspace:this.workspace};return this.channel.call("optimize",e)}},Su=class extends yu{constructor(e,t){super(e,t,void 0);this._onDidChangeItemsExternal=this._register(new w);this.onDidChangeItemsExternal=this._onDidChangeItemsExternal.event;this.registerListeners()}registerListeners(){this._register(this.channel.listen("onDidChangeStorage",{profile:this.profile})(e=>this.onDidChangeStorage(e)))}onDidChangeStorage(e){(Array.isArray(e.changed)||Array.isArray(e.deleted))&&this._onDidChangeItemsExternal.fire({changed:e.changed?new Map(e.changed):void 0,deleted:e.deleted?new Set(e.deleted):void 0})}},ws=class extends Su{constructor(r){super(r,void 0)}async close(){this.dispose()}},Ps=class extends Su{async close(){this.dispose()}},Iu=class extends yu{constructor(e,t){super(e,void 0,t);this.onDidChangeItemsExternal=k.None}async close(){this.dispose()}},bu=class{constructor(r){this.channel=r}isUsed(r){let e={payload:r,profile:void 0,workspace:void 0};return this.channel.call("isUsed",e)}};var DL=L("contextService");function zI(o){let r=o;return typeof r?.id=="string"&&P.isUri(r.uri)}var KI={id:"ext-dev"};function jI(o){let r=o;return typeof r?.id=="string"&&P.isUri(r.configPath)}var HI="code-workspace",_L=`.${HI}`,kL=[{name:S(2754,null),extensions:[HI]}];import{createHash as ML}from"crypto";var JI=128/4;var mi=L("nativeHostService");var Rn=L("mainProcessService"),xu=class{constructor(r,e){this.server=r;this.router=e}getChannel(r){return this.server.getChannel(r,this.router)}registerChannel(r,e){this.server.registerChannel(r,e)}};var Rs=class extends T{constructor(e,t,n,i){super();this.environmentService=e;this.logService=t;this.nativeHostService=n;this.mainProcessService=i;this._register(new It(()=>{this.cleanUpStorage()},30*1e3)).schedule()}async cleanUpStorage(){this.logService.trace("[storage cleanup]: Starting to clean up workspace storage folders for unused empty workspaces.");try{let e=this.environmentService.workspaceStorageHome.with({scheme:re.file}).fsPath,t=await ce.readdir(e),n=new bu(this.mainProcessService.getChannel("storage"));await Promise.all(t.map(async i=>{let s=G(e,i);i.length===JI||i===KI.id||(await this.nativeHostService.getWindows({includeAuxiliaryWindows:!1})).some(c=>c.workspace?.id===i)||await n.isUsed(s)||(this.logService.trace(`[storage cleanup]: Deleting workspace storage folder ${i} as it seems to be an unused empty workspace.`),await ce.rm(s))}))}catch(e){Me(e)}}};Rs=b([g(0,nt),g(1,V),g(2,mi),g(3,Rn)],Rs);var Rg=L("checksumService");import{createHash as dP}from"crypto";var Ts=class{constructor(r){this.fileService=r}async checksum(r){let e=(await this.fileService.readFileStream(r)).value;return new Promise((t,n)=>{let i=dP("sha256");ns(e,{onData:s=>i.update(s.buffer),onError:s=>n(s),onEnd:()=>t(i.digest("base64").replace(/=+$/,""))})})}};Ts=b([g(0,W)],Ts);var wu;(r=>r.DEFAULT={allowTrailingComma:!0})(wu||={});function Cg(o,r=!1){let e=0,t=o.length,n="",i=0,s=16,a=0;function l(v){let y=0,x=0;for(;y<v;){let E=o.charCodeAt(e);if(E>=48&&E<=57)x=x*16+E-48;else if(E>=65&&E<=70)x=x*16+E-65+10;else if(E>=97&&E<=102)x=x*16+E-97+10;else break;e++,y++}return y<v&&(x=-1),x}function c(v){e=v,n="",i=0,s=16,a=0}function d(){let v=e;if(o.charCodeAt(e)===48)e++;else for(e++;e<o.length&&Cs(o.charCodeAt(e));)e++;if(e<o.length&&o.charCodeAt(e)===46)if(e++,e<o.length&&Cs(o.charCodeAt(e)))for(e++;e<o.length&&Cs(o.charCodeAt(e));)e++;else return a=3,o.substring(v,e);let y=e;if(e<o.length&&(o.charCodeAt(e)===69||o.charCodeAt(e)===101))if(e++,(e<o.length&&o.charCodeAt(e)===43||o.charCodeAt(e)===45)&&e++,e<o.length&&Cs(o.charCodeAt(e))){for(e++;e<o.length&&Cs(o.charCodeAt(e));)e++;y=e}else a=3;return o.substring(v,y)}function u(){let v="",y=e;for(;;){if(e>=t){v+=o.substring(y,e),a=2;break}let x=o.charCodeAt(e);if(x===34){v+=o.substring(y,e),e++;break}if(x===92){if(v+=o.substring(y,e),e++,e>=t){a=2;break}switch(o.charCodeAt(e++)){case 34:v+='"';break;case 92:v+="\\";break;case 47:v+="/";break;case 98:v+="\b";break;case 102:v+="\f";break;case 110:v+=`
`;break;case 114:v+="\r";break;case 116:v+="	";break;case 117:{let R=l(4);R>=0?v+=String.fromCharCode(R):a=4;break}default:a=5}y=e;continue}if(x>=0&&x<=31)if(Eu(x)){v+=o.substring(y,e),a=2;break}else a=6;e++}return v}function p(){if(n="",a=0,i=e,e>=t)return i=t,s=17;let v=o.charCodeAt(e);if(Tg(v)){do e++,n+=String.fromCharCode(v),v=o.charCodeAt(e);while(Tg(v));return s=15}if(Eu(v))return e++,n+=String.fromCharCode(v),v===13&&o.charCodeAt(e)===10&&(e++,n+=`
`),s=14;switch(v){case 123:return e++,s=1;case 125:return e++,s=2;case 91:return e++,s=3;case 93:return e++,s=4;case 58:return e++,s=6;case 44:return e++,s=5;case 34:return e++,n=u(),s=10;case 47:{let y=e-1;if(o.charCodeAt(e+1)===47){for(e+=2;e<t&&!Eu(o.charCodeAt(e));)e++;return n=o.substring(y,e),s=12}if(o.charCodeAt(e+1)===42){e+=2;let x=t-1,E=!1;for(;e<x;){if(o.charCodeAt(e)===42&&o.charCodeAt(e+1)===47){e+=2,E=!0;break}e++}return E||(e++,a=1),n=o.substring(y,e),s=13}return n+=String.fromCharCode(v),e++,s=16}case 45:if(n+=String.fromCharCode(v),e++,e===t||!Cs(o.charCodeAt(e)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return n+=d(),s=11;default:for(;e<t&&m(v);)e++,v=o.charCodeAt(e);if(i!==e){switch(n=o.substring(i,e),n){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return n+=String.fromCharCode(v),e++,s=16}}function m(v){if(Tg(v)||Eu(v))return!1;switch(v){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function h(){let v;do v=p();while(v>=12&&v<=15);return v}return{setPosition:c,getPosition:()=>e,scan:r?h:p,getToken:()=>s,getTokenValue:()=>n,getTokenOffset:()=>i,getTokenLength:()=>e-i,getTokenError:()=>a}}function Tg(o){return o===32||o===9||o===11||o===12||o===160||o===5760||o>=8192&&o<=8203||o===8239||o===8287||o===12288||o===65279}function Eu(o){return o===10||o===13||o===8232||o===8233}function Cs(o){return o>=48&&o<=57}function je(o,r=[],e=wu.DEFAULT){let t=null,n=[],i=[];function s(l){Array.isArray(n)?n.push(l):t!==null&&(n[t]=l)}return gi(o,{onObjectBegin:()=>{let l={};s(l),i.push(n),n=l,t=null},onObjectProperty:l=>{t=l},onObjectEnd:()=>{n=i.pop()},onArrayBegin:()=>{let l=[];s(l),i.push(n),n=l,t=null},onArrayEnd:()=>{n=i.pop()},onLiteralValue:s,onError:(l,c,d)=>{r.push({error:l,offset:c,length:d})}},e),n[0]}function QI(o,r=[],e=wu.DEFAULT){let t={type:"array",offset:-1,length:-1,children:[],parent:void 0};function n(l){t.type==="property"&&(t.length=l-t.offset,t=t.parent)}function i(l){return t.children.push(l),l}gi(o,{onObjectBegin:l=>{t=i({type:"object",offset:l,length:-1,parent:t,children:[]})},onObjectProperty:(l,c,d)=>{t=i({type:"property",offset:c,length:-1,parent:t,children:[]}),t.children.push({type:"string",value:l,offset:c,length:d,parent:t})},onObjectEnd:(l,c)=>{t.length=l+c-t.offset,t=t.parent,n(l+c)},onArrayBegin:(l,c)=>{t=i({type:"array",offset:l,length:-1,parent:t,children:[]})},onArrayEnd:(l,c)=>{t.length=l+c-t.offset,t=t.parent,n(l+c)},onLiteralValue:(l,c,d)=>{i({type:hi(l),offset:c,length:d,parent:t,value:l}),n(c+d)},onSeparator:(l,c,d)=>{t.type==="property"&&(l===":"?t.colonOffset=c:l===","&&n(c))},onError:(l,c,d)=>{r.push({error:l,offset:c,length:d})}},e);let a=t.children[0];return a&&delete a.parent,a}function Dg(o,r){if(!o)return;let e=o;for(let t of r)if(typeof t=="string"){if(e.type!=="object"||!Array.isArray(e.children))return;let n=!1;for(let i of e.children)if(Array.isArray(i.children)&&i.children[0].value===t){e=i.children[1],n=!0;break}if(!n)return}else{let n=t;if(e.type!=="array"||n<0||!Array.isArray(e.children)||n>=e.children.length)return;e=e.children[n]}return e}function gi(o,r,e=wu.DEFAULT){let t=Cg(o,!1);function n(A){return A?()=>A(t.getTokenOffset(),t.getTokenLength()):()=>!0}function i(A){return A?ae=>A(ae,t.getTokenOffset(),t.getTokenLength()):()=>!0}let s=n(r.onObjectBegin),a=i(r.onObjectProperty),l=n(r.onObjectEnd),c=n(r.onArrayBegin),d=n(r.onArrayEnd),u=i(r.onLiteralValue),p=i(r.onSeparator),m=n(r.onComment),h=i(r.onError),v=e&&e.disallowComments,y=e&&e.allowTrailingComma;function x(){for(;;){let A=t.scan();switch(t.getTokenError()){case 4:E(14);break;case 5:E(15);break;case 3:E(13);break;case 1:v||E(11);break;case 2:E(12);break;case 6:E(16);break}switch(A){case 12:case 13:v?E(10):m();break;case 16:E(1);break;case 15:case 14:break;default:return A}}}function E(A,ae=[],J=[]){if(h(A),ae.length+J.length>0){let ge=t.getToken();for(;ge!==17;){if(ae.indexOf(ge)!==-1){x();break}else if(J.indexOf(ge)!==-1)break;ge=x()}}}function R(A){let ae=t.getTokenValue();return A?u(ae):a(ae),x(),!0}function F(){switch(t.getToken()){case 11:{let A=0;try{A=JSON.parse(t.getTokenValue()),typeof A!="number"&&(E(2),A=0)}catch{E(2)}u(A);break}case 7:u(null);break;case 8:u(!0);break;case 9:u(!1);break;default:return!1}return x(),!0}function H(){return t.getToken()!==10?(E(3,[],[2,5]),!1):(R(!1),t.getToken()===6?(p(":"),x(),C()||E(4,[],[2,5])):E(5,[],[2,5]),!0)}function qe(){s(),x();let A=!1;for(;t.getToken()!==2&&t.getToken()!==17;){if(t.getToken()===5){if(A||E(4,[],[]),p(","),x(),t.getToken()===2&&y)break}else A&&E(6,[],[]);H()||E(4,[],[2,5]),A=!0}return l(),t.getToken()!==2?E(7,[2],[]):x(),!0}function B(){c(),x();let A=!1;for(;t.getToken()!==4&&t.getToken()!==17;){if(t.getToken()===5){if(A||E(4,[],[]),p(","),x(),t.getToken()===4&&y)break}else A&&E(6,[],[]);C()||E(4,[],[4,5]),A=!0}return d(),t.getToken()!==4?E(8,[4],[]):x(),!0}function C(){switch(t.getToken()){case 3:return B();case 1:return qe();case 10:return R(!0);default:return F()}}return x(),t.getToken()===17?e.allowEmptyContent?!0:(E(4,[],[]),!1):C()?(t.getToken()!==17&&E(9,[],[]),!0):(E(4,[],[]),!1)}function hi(o){switch(typeof o){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(o){if(Array.isArray(o))return"array"}else return"null";return"object"}default:return"null"}}function YI(o,r,e){let t,n,i,s,a;if(r){for(s=r.offset,a=s+r.length,i=s;i>0&&!oc(o,i-1);)i--;let R=a;for(;R<o.length&&!oc(o,R);)R++;n=o.substring(i,R),t=uP(n,e)}else n=o,t=0,i=0,s=0,a=o.length;let l=kg(e,o),c=!1,d=0,u;e.insertSpaces?u=_g(" ",e.tabSize||4):u="	";let p=Cg(n,!1),m=!1;function h(){return l+_g(u,t+d)}function v(){let R=p.scan();for(c=!1;R===15||R===14;)c=c||R===14,R=p.scan();return m=R===16||p.getTokenError()!==0,R}let y=[];function x(R,F,H){!m&&F<a&&H>s&&o.substring(F,H)!==R&&y.push({offset:F,length:H-F,content:R})}let E=v();if(E!==17){let R=p.getTokenOffset()+i,F=_g(u,t);x(F,i,R)}for(;E!==17;){let R=p.getTokenOffset()+p.getTokenLength()+i,F=v(),H="";for(;!c&&(F===12||F===13);){let B=p.getTokenOffset()+i;x(" ",R,B),R=p.getTokenOffset()+p.getTokenLength()+i,H=F===12?h():"",F=v()}if(F===2)E!==1&&(d--,H=h());else if(F===4)E!==3&&(d--,H=h());else{switch(E){case 3:case 1:d++,H=h();break;case 5:case 12:H=h();break;case 13:c?H=h():H=" ";break;case 6:H=" ";break;case 10:if(F===6){H="";break}case 7:case 8:case 9:case 11:case 2:case 4:F===12||F===13?H=" ":F!==5&&F!==17&&(m=!0);break;case 16:m=!0;break}c&&(F===12||F===13)&&(H=h())}let qe=p.getTokenOffset()+i;x(H,R,qe),E=F}return y}function zn(o,r){let e=JSON.stringify(o,void 0,r.insertSpaces?r.tabSize||4:"	");return r.eol!==void 0?e.replace(/\r\n|\r|\n/g,r.eol):e}function _g(o,r){let e="";for(let t=0;t<r;t++)e+=o;return e}function uP(o,r){let e=0,t=0,n=r.tabSize||4;for(;e<o.length;){let i=o.charAt(e);if(i===" ")t++;else if(i==="	")t+=n;else break;e++}return Math.floor(t/n)}function kg(o,r){for(let e=0;e<r.length;e++){let t=r.charAt(e);if(t==="\r")return e+1<r.length&&r.charAt(e+1)===`
`?`\r
`:"\r";if(t===`
`)return`
`}return o&&o.eol||`
`}function oc(o,r){return`\r
`.indexOf(o.charAt(r))!==-1}function Ds(o,r,e,t,n){let i=r.slice(),a=QI(o,[]),l,c;for(;i.length>0&&(c=i.pop(),l=Dg(a,i),l===void 0&&e!==void 0);)typeof c=="string"?e={[c]:e}:e=[e];if(l)if(l.type==="object"&&typeof c=="string"&&Array.isArray(l.children)){let d=Dg(l,[c]);if(d!==void 0)if(e===void 0){if(!d.parent)throw new Error("Malformed AST");let u=l.children.indexOf(d.parent),p,m=d.parent.offset+d.parent.length;if(u>0){let h=l.children[u-1];p=h.offset+h.length}else p=l.offset+1,l.children.length>1&&(m=l.children[1].offset);return vi(o,{offset:p,length:m-p,content:""},t)}else return vi(o,{offset:d.offset,length:d.length,content:JSON.stringify(e)},t);else{if(e===void 0)return[];let u=`${JSON.stringify(c)}: ${JSON.stringify(e)}`,p=n?n(l.children.map(h=>h.children[0].value)):l.children.length,m;if(p>0){let h=l.children[p-1];m={offset:h.offset+h.length,length:0,content:","+u}}else l.children.length===0?m={offset:l.offset+1,length:0,content:u}:m={offset:l.offset+1,length:0,content:u+","};return vi(o,m,t)}}else if(l.type==="array"&&typeof c=="number"&&Array.isArray(l.children))if(e!==void 0){let d=`${JSON.stringify(e)}`,u;if(l.children.length===0||c===0)u={offset:l.offset+1,length:0,content:l.children.length===0?d:d+","};else{let p=c===-1||c>l.children.length?l.children.length:c,m=l.children[p-1];u={offset:m.offset+m.length,length:0,content:","+d}}return vi(o,u,t)}else{let d=c,u=l.children[d],p;if(l.children.length===1)p={offset:l.offset+1,length:l.length-2,content:""};else if(l.children.length-1===d){let m=l.children[d-1],h=m.offset+m.length,v=l.offset+l.length;p={offset:h,length:v-2-h,content:""}}else p={offset:u.offset,length:l.children[d+1].offset-u.offset,content:""};return vi(o,p,t)}else throw new Error(`Can not add ${typeof c!="number"?"index":"property"} to parent of type ${l.type}`);else return e===void 0?[]:vi(o,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(e)},t)}function vi(o,r,e){let t=Ug(o,r),n=r.offset,i=r.offset+r.content.length;if(r.length===0||r.content.length===0){for(;n>0&&!oc(t,n-1);)n--;for(;i<t.length&&!oc(t,i);)i++}let s=YI(t,{offset:n,length:i-n},e);for(let l=s.length-1;l>=0;l--){let c=s[l];t=Ug(t,c),n=Math.min(n,c.offset),i=Math.max(i,c.offset+c.length),i+=c.content.length-c.length}let a=o.length-(t.length-i)-n;return[{offset:n,length:a,content:t.substring(n,i)}]}function Ug(o,r){return o.substring(0,r.offset)+r.content+o.substring(r.offset+r.length)}function Pu(o,r){let e=r.slice(0).sort((n,i)=>{let s=n.offset-i.offset;return s===0?n.length-i.length:s}),t=o.length;for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.offset+i.length<=t)o=Ug(o,i);else throw new Error("Overlapping edit");t=i.offset}return o}function Ct(o){if(!o||typeof o!="object"||o instanceof RegExp)return o;let r=Array.isArray(o)?[]:{};return Object.entries(o).forEach(([e,t])=>{r[e]=t&&typeof t=="object"?Ct(t):t}),r}function ZI(o){if(!o||typeof o!="object")return o;let r=[o];for(;r.length>0;){let e=r.shift();Object.freeze(e);for(let t in e)if(eb.call(e,t)){let n=e[t];typeof n=="object"&&!Object.isFrozen(n)&&!Ty(n)&&r.push(n)}}return o}var eb=Object.prototype.hasOwnProperty;function _s(o,r){return Lg(o,r,new Set)}function Lg(o,r,e){if(ft(o))return o;let t=r(o);if(typeof t<"u")return t;if(Array.isArray(o)){let n=[];for(let i of o)n.push(Lg(i,r,e));return n}if(Re(o)){if(e.has(o))throw new Error("Cannot clone recursive data-structure");e.add(o);let n={};for(let i in o)eb.call(o,i)&&(n[i]=Lg(o[i],r,e));return e.delete(o),n}return o}function ks(o,r,e=!0){return Re(o)?(Re(r)&&Object.keys(r).forEach(t=>{t in o?e&&(Re(o[t])&&Re(r[t])?ks(o[t],r[t],e):o[t]=r[t]):o[t]=r[t]}),o):r}function it(o,r){if(o===r)return!0;if(o==null||r===null||r===void 0||typeof o!=typeof r||typeof o!="object"||Array.isArray(o)!==Array.isArray(r))return!1;let e,t;if(Array.isArray(o)){if(o.length!==r.length)return!1;for(e=0;e<o.length;e++)if(!it(o[e],r[e]))return!1}else{let n=[];for(t in o)n.push(t);n.sort();let i=[];for(t in r)i.push(t);if(i.sort(),!it(n,i))return!1;for(e=0;e<n.length;e++)if(!it(o[n[e]],r[n[e]]))return!1}return!0}function Mg(o){let r=new Set;return JSON.stringify(o,(e,t)=>{if(Re(t)||Array.isArray(t)){if(r.has(t))return"[Circular]";r.add(t)}return typeof t=="bigint"?`[BigInt ${t.toString()}]`:t})}function ac(o){return Object.isFrozen(o)?o:ZI(o)}var ut=class o{constructor(r,e,t,n,i){this._contents=r;this._keys=e;this._overrides=t;this._raw=n;this.logService=i;this.overrideConfigurations=new Map}static createEmptyModel(r){return new o({},[],[],void 0,r)}get rawConfiguration(){if(!this._rawConfiguration)if(this._raw){let r=(Array.isArray(this._raw)?this._raw:[this._raw]).map(e=>{if(e instanceof o)return e;let t=new Us("",this.logService);return t.parseRaw(e),t.configurationModel});this._rawConfiguration=r.reduce((e,t)=>t===e?t:e.merge(t),r[0])}else this._rawConfiguration=this;return this._rawConfiguration}get contents(){return this._contents}get overrides(){return this._overrides}get keys(){return this._keys}get raw(){if(this._raw&&!(Array.isArray(this._raw)&&this._raw.every(r=>r instanceof o)))return this._raw}isEmpty(){return this._keys.length===0&&Object.keys(this._contents).length===0&&this._overrides.length===0}getValue(r){return r?jl(this.contents,r):this.contents}inspect(r,e){let t=this;return{get value(){return ac(t.rawConfiguration.getValue(r))},get override(){return e?ac(t.rawConfiguration.getOverrideValue(r,e)):void 0},get merged(){return ac(e?t.rawConfiguration.override(e).getValue(r):t.rawConfiguration.getValue(r))},get overrides(){let n=[];for(let{contents:i,identifiers:s,keys:a}of t.rawConfiguration.overrides){let l=new o(i,a,[],void 0,t.logService).getValue(r);l!==void 0&&n.push({identifiers:s,value:l})}return n.length?ac(n):void 0}}}getOverrideValue(r,e){let t=this.getContentsForOverrideIdentifer(e);return t?r?jl(t,r):t:void 0}getKeysForOverrideIdentifier(r){let e=[];for(let t of this.overrides)t.identifiers.includes(r)&&e.push(...t.keys);return dt(e)}getAllOverrideIdentifiers(){let r=[];for(let e of this.overrides)r.push(...e.identifiers);return dt(r)}override(r){let e=this.overrideConfigurations.get(r);return e||(e=this.createOverrideConfigurationModel(r),this.overrideConfigurations.set(r,e)),e}merge(...r){let e=Ct(this.contents),t=Ct(this.overrides),n=[...this.keys],i=this._raw?Array.isArray(this._raw)?[...this._raw]:[this._raw]:[this];for(let s of r)if(i.push(...s._raw?Array.isArray(s._raw)?s._raw:[s._raw]:[s]),!s.isEmpty()){this.mergeContents(e,s.contents);for(let a of s.overrides){let[l]=t.filter(c=>Pt(c.identifiers,a.identifiers));l?(this.mergeContents(l.contents,a.contents),l.keys.push(...a.keys),l.keys=dt(l.keys)):t.push(Ct(a))}for(let a of s.keys)n.indexOf(a)===-1&&n.push(a)}return new o(e,n,t,!i.length||i.every(s=>s instanceof o)?void 0:i,this.logService)}createOverrideConfigurationModel(r){let e=this.getContentsForOverrideIdentifer(r);if(!e||typeof e!="object"||!Object.keys(e).length)return this;let t={};for(let n of dt([...Object.keys(this.contents),...Object.keys(e)])){let i=this.contents[n],s=e[n];s&&(typeof i=="object"&&typeof s=="object"?(i=Ct(i),this.mergeContents(i,s)):i=s),t[n]=i}return new o(t,this.keys,this.overrides,void 0,this.logService)}mergeContents(r,e){for(let t of Object.keys(e)){if(t in r&&Re(r[t])&&Re(e[t])){this.mergeContents(r[t],e[t]);continue}r[t]=Ct(e[t])}}getContentsForOverrideIdentifer(r){let e=null,t=null,n=i=>{i&&(t?this.mergeContents(t,i):t=Ct(i))};for(let i of this.overrides)i.identifiers.length===1&&i.identifiers[0]===r?e=i.contents:i.identifiers.includes(r)&&n(i.contents);return n(e),t}toJSON(){return{contents:this.contents,overrides:this.overrides,keys:this.keys}}addValue(r,e){this.updateValue(r,e,!0)}setValue(r,e){this.updateValue(r,e,!1)}removeValue(r){let e=this.keys.indexOf(r);e!==-1&&(this.keys.splice(e,1),II(this.contents,r),Pn.test(r)&&this.overrides.splice(this.overrides.findIndex(t=>Pt(t.identifiers,gs(r))),1))}updateValue(r,e,t){if(dg(this.contents,r,e,n=>this.logService.error(n)),t=t||this.keys.indexOf(r)===-1,t&&this.keys.push(r),Pn.test(r)){let n=this.contents[r],i=gs(r),s={identifiers:i,keys:Object.keys(n),contents:Qd(n,l=>this.logService.error(l))},a=this.overrides.findIndex(l=>Pt(l.identifiers,i));a!==-1?this.overrides[a]=s:this.overrides.push(s)}}},Us=class{constructor(r,e){this._name=r;this.logService=e;this._raw=null;this._configurationModel=null;this._restrictedConfigurations=[];this._parseErrors=[]}get configurationModel(){return this._configurationModel||ut.createEmptyModel(this.logService)}get restrictedConfigurations(){return this._restrictedConfigurations}get errors(){return this._parseErrors}parse(r,e){if(!ft(r)){let t=this.doParseContent(r);this.parseRaw(t,e)}}reparse(r){this._raw&&this.parseRaw(this._raw,r)}parseRaw(r,e){this._raw=r;let{contents:t,keys:n,overrides:i,restricted:s,hasExcludedProperties:a}=this.doParseRaw(r,e);this._configurationModel=new ut(t,n,i,a?[r]:void 0,this.logService),this._restrictedConfigurations=s||[]}doParseContent(r){let e={},t=null,n=[],i=[],s=[];function a(c){Array.isArray(n)?n.push(c):t!==null&&(n[t]=c)}let l={onObjectBegin:()=>{let c={};a(c),i.push(n),n=c,t=null},onObjectProperty:c=>{t=c},onObjectEnd:()=>{n=i.pop()},onArrayBegin:()=>{let c=[];a(c),i.push(n),n=c,t=null},onArrayEnd:()=>{n=i.pop()},onLiteralValue:a,onError:(c,d,u)=>{s.push({error:c,offset:d,length:u})}};if(r)try{gi(r,l),e=n[0]||{}}catch(c){this.logService.error(`Error while parsing settings file ${this._name}: ${c}`),this._parseErrors=[c]}return e}doParseRaw(r,e){let t=gt.as(zt.Configuration),n=t.getConfigurationProperties(),i=t.getExcludedConfigurationProperties(),s=this.filter(r,n,i,!0,e);r=s.raw;let a=Qd(r,d=>this.logService.error(`Conflict in settings file ${this._name}: ${d}`)),l=Object.keys(r),c=this.toOverrides(r,d=>this.logService.error(`Conflict in settings file ${this._name}: ${d}`));return{contents:a,keys:l,overrides:c,restricted:s.restricted,hasExcludedProperties:s.hasExcludedProperties}}filter(r,e,t,n,i){let s=!1;if(!i?.scopes&&!i?.skipRestricted&&!i?.skipUnregistered&&!i?.exclude?.length)return{raw:r,restricted:[],hasExcludedProperties:s};let a={},l=[];for(let c in r)if(Pn.test(c)&&n){let d=this.filter(r[c],e,t,!1,i);a[c]=d.raw,s=s||d.hasExcludedProperties,l.push(...d.restricted)}else{let d=e[c];d?.restricted&&l.push(c),this.shouldInclude(c,d,t,i)?a[c]=r[c]:s=!0}return{raw:a,restricted:l,hasExcludedProperties:s}}shouldInclude(r,e,t,n){if(n.exclude?.includes(r))return!1;if(n.include?.includes(r))return!0;if(n.skipRestricted&&e?.restricted||n.skipUnregistered&&!e)return!1;let i=e??t[r],s=i?typeof i.scope<"u"?i.scope:4:void 0;return s===void 0||n.scopes===void 0?!0:n.scopes.includes(s)}toOverrides(r,e){let t=[];for(let n of Object.keys(r))if(Pn.test(n)){let i={},s=r[n];for(let a in s)i[a]=s[a];t.push({identifiers:gs(n),keys:Object.keys(i),contents:Qd(i,e)})}return t}},Ru=class extends T{constructor(e,t,n,i,s){super();this.userSettingsResource=e;this.parseOptions=t;this.fileService=i;this.logService=s;this._onDidChange=this._register(new w);this.onDidChange=this._onDidChange.event;this.parser=new Us(this.userSettingsResource.toString(),s),this._register(this.fileService.watch(n.dirname(this.userSettingsResource))),this._register(this.fileService.watch(this.userSettingsResource)),this._register(k.any(k.filter(this.fileService.onDidFilesChange,a=>a.contains(this.userSettingsResource)),k.filter(this.fileService.onDidRunOperation,a=>(a.isOperation(0)||a.isOperation(3)||a.isOperation(1)||a.isOperation(4))&&n.isEqual(a.resource,e)))(()=>this._onDidChange.fire()))}async loadConfiguration(){try{let e=await this.fileService.readFile(this.userSettingsResource);return this.parser.parse(e.value.toString()||"{}",this.parseOptions),this.parser.configurationModel}catch{return ut.createEmptyModel(this.logService)}}reparse(e){return e&&(this.parseOptions=e),this.parser.reparse(this.parseOptions),this.parser.configurationModel}getRestrictedSettings(){return this.parser.restrictedConfigurations}},Ag=class{constructor(r,e,t,n,i,s,a,l,c,d,u,p,m){this.key=r;this.overrides=e;this._value=t;this.overrideIdentifiers=n;this.defaultConfiguration=i;this.policyConfiguration=s;this.applicationConfiguration=a;this.userConfiguration=l;this.localUserConfiguration=c;this.remoteUserConfiguration=d;this.workspaceConfiguration=u;this.folderConfigurationModel=p;this.memoryConfigurationModel=m}get value(){return ac(this._value)}toInspectValue(r){return r?.value!==void 0||r?.override!==void 0||r?.overrides!==void 0?r:void 0}get defaultInspectValue(){return this._defaultInspectValue||(this._defaultInspectValue=this.defaultConfiguration.inspect(this.key,this.overrides.overrideIdentifier)),this._defaultInspectValue}get defaultValue(){return this.defaultInspectValue.merged}get default(){return this.toInspectValue(this.defaultInspectValue)}get policyInspectValue(){return this._policyInspectValue===void 0&&(this._policyInspectValue=this.policyConfiguration?this.policyConfiguration.inspect(this.key):null),this._policyInspectValue}get policyValue(){return this.policyInspectValue?.merged}get policy(){return this.policyInspectValue?.value!==void 0?{value:this.policyInspectValue.value}:void 0}get applicationInspectValue(){return this._applicationInspectValue===void 0&&(this._applicationInspectValue=this.applicationConfiguration?this.applicationConfiguration.inspect(this.key):null),this._applicationInspectValue}get applicationValue(){return this.applicationInspectValue?.merged}get application(){return this.toInspectValue(this.applicationInspectValue)}get userInspectValue(){return this._userInspectValue||(this._userInspectValue=this.userConfiguration.inspect(this.key,this.overrides.overrideIdentifier)),this._userInspectValue}get userValue(){return this.userInspectValue.merged}get user(){return this.toInspectValue(this.userInspectValue)}get userLocalInspectValue(){return this._userLocalInspectValue||(this._userLocalInspectValue=this.localUserConfiguration.inspect(this.key,this.overrides.overrideIdentifier)),this._userLocalInspectValue}get userLocalValue(){return this.userLocalInspectValue.merged}get userLocal(){return this.toInspectValue(this.userLocalInspectValue)}get userRemoteInspectValue(){return this._userRemoteInspectValue||(this._userRemoteInspectValue=this.remoteUserConfiguration.inspect(this.key,this.overrides.overrideIdentifier)),this._userRemoteInspectValue}get userRemoteValue(){return this.userRemoteInspectValue.merged}get userRemote(){return this.toInspectValue(this.userRemoteInspectValue)}get workspaceInspectValue(){return this._workspaceInspectValue===void 0&&(this._workspaceInspectValue=this.workspaceConfiguration?this.workspaceConfiguration.inspect(this.key,this.overrides.overrideIdentifier):null),this._workspaceInspectValue}get workspaceValue(){return this.workspaceInspectValue?.merged}get workspace(){return this.toInspectValue(this.workspaceInspectValue)}get workspaceFolderInspectValue(){return this._workspaceFolderInspectValue===void 0&&(this._workspaceFolderInspectValue=this.folderConfigurationModel?this.folderConfigurationModel.inspect(this.key,this.overrides.overrideIdentifier):null),this._workspaceFolderInspectValue}get workspaceFolderValue(){return this.workspaceFolderInspectValue?.merged}get workspaceFolder(){return this.toInspectValue(this.workspaceFolderInspectValue)}get memoryInspectValue(){return this._memoryInspectValue===void 0&&(this._memoryInspectValue=this.memoryConfigurationModel.inspect(this.key,this.overrides.overrideIdentifier)),this._memoryInspectValue}get memoryValue(){return this.memoryInspectValue.merged}get memory(){return this.toInspectValue(this.memoryInspectValue)}},Ls=class o{constructor(r,e,t,n,i,s,a,l,c,d){this._defaultConfiguration=r;this._policyConfiguration=e;this._applicationConfiguration=t;this._localUserConfiguration=n;this._remoteUserConfiguration=i;this._workspaceConfiguration=s;this._folderConfigurations=a;this._memoryConfiguration=l;this._memoryConfigurationByResource=c;this.logService=d;this._workspaceConsolidatedConfiguration=null;this._foldersConsolidatedConfigurations=new He;this._userConfiguration=null}getValue(r,e,t){return this.getConsolidatedConfigurationModel(r,e,t).getValue(r)}updateValue(r,e,t={}){let n;t.resource?(n=this._memoryConfigurationByResource.get(t.resource),n||(n=ut.createEmptyModel(this.logService),this._memoryConfigurationByResource.set(t.resource,n))):n=this._memoryConfiguration,e===void 0?n.removeValue(r):n.setValue(r,e),t.resource||(this._workspaceConsolidatedConfiguration=null)}inspect(r,e,t){let n=this.getConsolidatedConfigurationModel(r,e,t),i=this.getFolderConfigurationModelForResource(e.resource,t),s=e.resource?this._memoryConfigurationByResource.get(e.resource)||this._memoryConfiguration:this._memoryConfiguration,a=new Set;for(let l of n.overrides)for(let c of l.identifiers)n.getOverrideValue(r,c)!==void 0&&a.add(c);return new Ag(r,e,n.getValue(r),a.size?[...a]:void 0,this._defaultConfiguration,this._policyConfiguration.isEmpty()?void 0:this._policyConfiguration,this.applicationConfiguration.isEmpty()?void 0:this.applicationConfiguration,this.userConfiguration,this.localUserConfiguration,this.remoteUserConfiguration,t?this._workspaceConfiguration:void 0,i||void 0,s)}keys(r){let e=this.getFolderConfigurationModelForResource(void 0,r);return{default:this._defaultConfiguration.keys.slice(0),policy:this._policyConfiguration.keys.slice(0),user:this.userConfiguration.keys.slice(0),workspace:this._workspaceConfiguration.keys.slice(0),workspaceFolder:e?e.keys.slice(0):[]}}updateDefaultConfiguration(r){this._defaultConfiguration=r,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updatePolicyConfiguration(r){this._policyConfiguration=r}updateApplicationConfiguration(r){this._applicationConfiguration=r,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateLocalUserConfiguration(r){this._localUserConfiguration=r,this._userConfiguration=null,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateRemoteUserConfiguration(r){this._remoteUserConfiguration=r,this._userConfiguration=null,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateWorkspaceConfiguration(r){this._workspaceConfiguration=r,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateFolderConfiguration(r,e){this._folderConfigurations.set(r,e),this._foldersConsolidatedConfigurations.delete(r)}deleteFolderConfiguration(r){this.folderConfigurations.delete(r),this._foldersConsolidatedConfigurations.delete(r)}compareAndUpdateDefaultConfiguration(r,e){let t=[];if(!e){let{added:n,updated:i,removed:s}=yi(this._defaultConfiguration,r);e=[...n,...i,...s]}for(let n of e)for(let i of gs(n)){let s=this._defaultConfiguration.getKeysForOverrideIdentifier(i),a=r.getKeysForOverrideIdentifier(i),l=[...a.filter(c=>s.indexOf(c)===-1),...s.filter(c=>a.indexOf(c)===-1),...s.filter(c=>!it(this._defaultConfiguration.override(i).getValue(c),r.override(i).getValue(c)))];t.push([i,l])}return this.updateDefaultConfiguration(r),{keys:e,overrides:t}}compareAndUpdatePolicyConfiguration(r){let{added:e,updated:t,removed:n}=yi(this._policyConfiguration,r),i=[...e,...t,...n];return i.length&&this.updatePolicyConfiguration(r),{keys:i,overrides:[]}}compareAndUpdateApplicationConfiguration(r){let{added:e,updated:t,removed:n,overrides:i}=yi(this.applicationConfiguration,r),s=[...e,...t,...n];return s.length&&this.updateApplicationConfiguration(r),{keys:s,overrides:i}}compareAndUpdateLocalUserConfiguration(r){let{added:e,updated:t,removed:n,overrides:i}=yi(this.localUserConfiguration,r),s=[...e,...t,...n];return s.length&&this.updateLocalUserConfiguration(r),{keys:s,overrides:i}}compareAndUpdateRemoteUserConfiguration(r){let{added:e,updated:t,removed:n,overrides:i}=yi(this.remoteUserConfiguration,r),s=[...e,...t,...n];return s.length&&this.updateRemoteUserConfiguration(r),{keys:s,overrides:i}}compareAndUpdateWorkspaceConfiguration(r){let{added:e,updated:t,removed:n,overrides:i}=yi(this.workspaceConfiguration,r),s=[...e,...t,...n];return s.length&&this.updateWorkspaceConfiguration(r),{keys:s,overrides:i}}compareAndUpdateFolderConfiguration(r,e){let t=this.folderConfigurations.get(r),{added:n,updated:i,removed:s,overrides:a}=yi(t,e),l=[...n,...i,...s];return(l.length||!t)&&this.updateFolderConfiguration(r,e),{keys:l,overrides:a}}compareAndDeleteFolderConfiguration(r){let e=this.folderConfigurations.get(r);if(!e)throw new Error("Unknown folder");this.deleteFolderConfiguration(r);let{added:t,updated:n,removed:i,overrides:s}=yi(e,void 0);return{keys:[...t,...n,...i],overrides:s}}get defaults(){return this._defaultConfiguration}get applicationConfiguration(){return this._applicationConfiguration}get userConfiguration(){if(!this._userConfiguration)if(this._remoteUserConfiguration.isEmpty())this._userConfiguration=this._localUserConfiguration;else{let r=this._localUserConfiguration.merge(this._remoteUserConfiguration);this._userConfiguration=new ut(r.contents,r.keys,r.overrides,void 0,this.logService)}return this._userConfiguration}get localUserConfiguration(){return this._localUserConfiguration}get remoteUserConfiguration(){return this._remoteUserConfiguration}get workspaceConfiguration(){return this._workspaceConfiguration}get folderConfigurations(){return this._folderConfigurations}getConsolidatedConfigurationModel(r,e,t){let n=this.getConsolidatedConfigurationModelForResource(e,t);if(e.overrideIdentifier&&(n=n.override(e.overrideIdentifier)),!this._policyConfiguration.isEmpty()&&this._policyConfiguration.getValue(r)!==void 0){n=n.merge();for(let i of this._policyConfiguration.keys)n.setValue(i,this._policyConfiguration.getValue(i))}return n}getConsolidatedConfigurationModelForResource({resource:r},e){let t=this.getWorkspaceConsolidatedConfiguration();if(e&&r){let n=e.getFolder(r);n&&(t=this.getFolderConsolidatedConfiguration(n.uri)||t);let i=this._memoryConfigurationByResource.get(r);i&&(t=t.merge(i))}return t}getWorkspaceConsolidatedConfiguration(){return this._workspaceConsolidatedConfiguration||(this._workspaceConsolidatedConfiguration=this._defaultConfiguration.merge(this.applicationConfiguration,this.userConfiguration,this._workspaceConfiguration,this._memoryConfiguration)),this._workspaceConsolidatedConfiguration}getFolderConsolidatedConfiguration(r){let e=this._foldersConsolidatedConfigurations.get(r);if(!e){let t=this.getWorkspaceConsolidatedConfiguration(),n=this._folderConfigurations.get(r);n?(e=t.merge(n),this._foldersConsolidatedConfigurations.set(r,e)):e=t}return e}getFolderConfigurationModelForResource(r,e){if(e&&r){let t=e.getFolder(r);if(t)return this._folderConfigurations.get(t.uri)}}toData(){return{defaults:{contents:this._defaultConfiguration.contents,overrides:this._defaultConfiguration.overrides,keys:this._defaultConfiguration.keys},policy:{contents:this._policyConfiguration.contents,overrides:this._policyConfiguration.overrides,keys:this._policyConfiguration.keys},application:{contents:this.applicationConfiguration.contents,overrides:this.applicationConfiguration.overrides,keys:this.applicationConfiguration.keys,raw:Array.isArray(this.applicationConfiguration.raw)?void 0:this.applicationConfiguration.raw},userLocal:{contents:this.localUserConfiguration.contents,overrides:this.localUserConfiguration.overrides,keys:this.localUserConfiguration.keys,raw:Array.isArray(this.localUserConfiguration.raw)?void 0:this.localUserConfiguration.raw},userRemote:{contents:this.remoteUserConfiguration.contents,overrides:this.remoteUserConfiguration.overrides,keys:this.remoteUserConfiguration.keys,raw:Array.isArray(this.remoteUserConfiguration.raw)?void 0:this.remoteUserConfiguration.raw},workspace:{contents:this._workspaceConfiguration.contents,overrides:this._workspaceConfiguration.overrides,keys:this._workspaceConfiguration.keys},folders:[...this._folderConfigurations.keys()].reduce((r,e)=>{let{contents:t,overrides:n,keys:i}=this._folderConfigurations.get(e);return r.push([e,{contents:t,overrides:n,keys:i}]),r},[])}}allKeys(){let r=new Set;return this._defaultConfiguration.keys.forEach(e=>r.add(e)),this.userConfiguration.keys.forEach(e=>r.add(e)),this._workspaceConfiguration.keys.forEach(e=>r.add(e)),this._folderConfigurations.forEach(e=>e.keys.forEach(t=>r.add(t))),[...r.values()]}allOverrideIdentifiers(){let r=new Set;return this._defaultConfiguration.getAllOverrideIdentifiers().forEach(e=>r.add(e)),this.userConfiguration.getAllOverrideIdentifiers().forEach(e=>r.add(e)),this._workspaceConfiguration.getAllOverrideIdentifiers().forEach(e=>r.add(e)),this._folderConfigurations.forEach(e=>e.getAllOverrideIdentifiers().forEach(t=>r.add(t))),[...r.values()]}getAllKeysForOverrideIdentifier(r){let e=new Set;return this._defaultConfiguration.getKeysForOverrideIdentifier(r).forEach(t=>e.add(t)),this.userConfiguration.getKeysForOverrideIdentifier(r).forEach(t=>e.add(t)),this._workspaceConfiguration.getKeysForOverrideIdentifier(r).forEach(t=>e.add(t)),this._folderConfigurations.forEach(t=>t.getKeysForOverrideIdentifier(r).forEach(n=>e.add(n))),[...e.values()]}static parse(r,e){let t=this.parseConfigurationModel(r.defaults,e),n=this.parseConfigurationModel(r.policy,e),i=this.parseConfigurationModel(r.application,e),s=this.parseConfigurationModel(r.userLocal,e),a=this.parseConfigurationModel(r.userRemote,e),l=this.parseConfigurationModel(r.workspace,e),c=r.folders.reduce((d,u)=>(d.set(P.revive(u[0]),this.parseConfigurationModel(u[1],e)),d),new He);return new o(t,n,i,s,a,l,c,ut.createEmptyModel(e),new He,e)}static parseConfigurationModel(r,e){return new ut(r.contents,r.keys,r.overrides,r.raw,e)}};var Tu=class{constructor(r,e,t,n,i){this.change=r;this.previous=e;this.currentConfiguraiton=t;this.currentWorkspace=n;this.logService=i;this._marker=`
`;this._markerCode1=this._marker.charCodeAt(0);this._markerCode2=46;this.affectedKeys=new Set;this._previousConfiguration=void 0;for(let s of r.keys)this.affectedKeys.add(s);for(let[,s]of r.overrides)for(let a of s)this.affectedKeys.add(a);this._affectsConfigStr=this._marker;for(let s of this.affectedKeys)this._affectsConfigStr+=s+this._marker}get previousConfiguration(){return!this._previousConfiguration&&this.previous&&(this._previousConfiguration=Ls.parse(this.previous.data,this.logService)),this._previousConfiguration}affectsConfiguration(r,e){let t=this._marker+r,n=this._affectsConfigStr.indexOf(t);if(n<0)return!1;let i=n+t.length;if(i>=this._affectsConfigStr.length)return!1;let s=this._affectsConfigStr.charCodeAt(i);if(s!==this._markerCode1&&s!==this._markerCode2)return!1;if(e){let a=this.previousConfiguration?this.previousConfiguration.getValue(r,e,this.previous?.workspace):void 0,l=this.currentConfiguraiton.getValue(r,e,this.currentWorkspace);return!it(a,l)}return!0}};function yi(o,r){let{added:e,removed:t,updated:n}=tb(r?.rawConfiguration,o?.rawConfiguration),i=[],s=o?.getAllOverrideIdentifiers()||[],a=r?.getAllOverrideIdentifiers()||[];if(r){let l=a.filter(c=>!s.includes(c));for(let c of l)i.push([c,r.getKeysForOverrideIdentifier(c)])}if(o){let l=s.filter(c=>!a.includes(c));for(let c of l)i.push([c,o.getKeysForOverrideIdentifier(c)])}if(r&&o){for(let l of s)if(a.includes(l)){let c=tb({contents:o.getOverrideValue(void 0,l)||{},keys:o.getKeysForOverrideIdentifier(l)},{contents:r.getOverrideValue(void 0,l)||{},keys:r.getKeysForOverrideIdentifier(l)});i.push([l,[...c.added,...c.removed,...c.updated]])}}return{added:e,removed:t,updated:n,overrides:i}}function tb(o,r){let e=o?r?o.keys.filter(i=>r.keys.indexOf(i)===-1):[...o.keys]:[],t=r?o?r.keys.filter(i=>o.keys.indexOf(i)===-1):[...r.keys]:[],n=[];if(o&&r){for(let i of r.keys)if(o.keys.indexOf(i)!==-1){let s=jl(r.contents,i),a=jl(o.contents,i);it(s,a)||n.push(i)}}return{added:e,removed:t,updated:n}}var Du=L("policy"),Cu=class extends T{constructor(){super(...arguments);this.policyDefinitions={};this.policies=new Map;this._onDidChange=this._register(new w);this.onDidChange=this._onDidChange.event}async updatePolicyDefinitions(e){let t=Object.keys(this.policyDefinitions).length;return this.policyDefinitions={...e,...this.policyDefinitions},t!==Object.keys(this.policyDefinitions).length&&await this._updatePolicyDefinitions(this.policyDefinitions),ti.reduce(this.policies.entries(),(n,[i,s])=>({...n,[i]:s}),{})}getPolicyValue(e){return this.policies.get(e)}serialize(){return ti.reduce(Object.entries(this.policyDefinitions),(e,[t,n])=>({...e,[t]:{definition:n,value:this.policies.get(t)}}),{})}},Ms=class{constructor(){this.onDidChange=k.None;this.policyDefinitions={}}async updatePolicyDefinitions(){return{}}getPolicyValue(){}serialize(){}};var _u=class extends T{constructor(e){super();this.logService=e;this._onDidChangeConfiguration=this._register(new w);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=ut.createEmptyModel(e)}get configurationModel(){return this._configurationModel}async initialize(){return this.resetConfigurationModel(),this._register(gt.as(zt.Configuration).onDidUpdateConfiguration(({properties:e,defaultsOverrides:t})=>this.onDidUpdateConfiguration(Array.from(e),t))),this.configurationModel}reload(){return this.resetConfigurationModel(),this.configurationModel}onDidUpdateConfiguration(e,t){this.updateConfigurationModel(e,gt.as(zt.Configuration).getConfigurationProperties()),this._onDidChangeConfiguration.fire({defaults:this.configurationModel,properties:e})}getConfigurationDefaultOverrides(){return{}}resetConfigurationModel(){this._configurationModel=ut.createEmptyModel(this.logService);let e=gt.as(zt.Configuration).getConfigurationProperties();this.updateConfigurationModel(Object.keys(e),e)}updateConfigurationModel(e,t){let n=this.getConfigurationDefaultOverrides();for(let i of e){let s=n[i],a=t[i];s!==void 0?this._configurationModel.setValue(i,s):a?this._configurationModel.setValue(i,Ct(a.default)):this._configurationModel.removeValue(i)}}},ku=class{constructor(){this.onDidChangeConfiguration=k.None;this.configurationModel=ut.createEmptyModel(new Hd)}async initialize(){return this.configurationModel}},As=class extends T{constructor(e,t,n){super();this.defaultConfiguration=e;this.policyService=t;this.logService=n;this._onDidChangeConfiguration=this._register(new w);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=ut.createEmptyModel(this.logService),this.configurationRegistry=gt.as(zt.Configuration)}get configurationModel(){return this._configurationModel}async initialize(){return this.logService.trace("PolicyConfiguration#initialize"),this.update(await this.updatePolicyDefinitions(this.defaultConfiguration.configurationModel.keys),!1),this.update(await this.updatePolicyDefinitions(Object.keys(this.configurationRegistry.getExcludedConfigurationProperties())),!1),this._register(this.policyService.onDidChange(e=>this.onDidChangePolicies(e))),this._register(this.defaultConfiguration.onDidChangeConfiguration(async({properties:e})=>this.update(await this.updatePolicyDefinitions(e),!0))),this._configurationModel}async updatePolicyDefinitions(e){this.logService.trace("PolicyConfiguration#updatePolicyDefinitions",e);let t={},n=[],i=this.configurationRegistry.getConfigurationProperties(),s=this.configurationRegistry.getExcludedConfigurationProperties();for(let a of e){let l=i[a]??s[a];if(!l){n.push(a);continue}if(l.policy){if(l.type!=="string"&&l.type!=="number"&&l.type!=="array"&&l.type!=="object"&&l.type!=="boolean"){this.logService.warn(`Policy ${l.policy.name} has unsupported type ${l.type}`);continue}let{value:c}=l.policy;n.push(a),t[l.policy.name]={type:l.type==="number"?"number":l.type==="boolean"?"boolean":"string",value:c}}}return nd(t)||await this.policyService.updatePolicyDefinitions(t),n}onDidChangePolicies(e){this.logService.trace("PolicyConfiguration#onDidChangePolicies",e);let t=this.configurationRegistry.getPolicyConfigurations(),n=hn(e.map(i=>t.get(i)));this.update(n,!0)}update(e,t){this.logService.trace("PolicyConfiguration#update",e);let n=this.configurationRegistry.getConfigurationProperties(),i=this.configurationRegistry.getExcludedConfigurationProperties(),s=[],a=this._configurationModel.isEmpty();for(let l of e){let c=n[l]??i[l],d=c?.policy?.name;if(d){let u=this.policyService.getPolicyValue(d);if(ue(u)&&c.type!=="string")try{u=this.parse(u)}catch(p){this.logService.error(`Error parsing policy value ${d}:`,ee(p));continue}(a?u!==void 0:!it(this._configurationModel.getValue(l),u))&&s.push([l,u])}else this._configurationModel.getValue(l)!==void 0&&s.push([l,void 0])}if(s.length){this.logService.trace("PolicyConfiguration#changed",s);let l=this._configurationModel;this._configurationModel=ut.createEmptyModel(this.logService);for(let c of l.keys)this._configurationModel.setValue(c,l.getValue(c));for(let[c,d]of s)d===void 0?this._configurationModel.removeValue(c):this._configurationModel.setValue(c,d);t&&this._onDidChangeConfiguration.fire(this._configurationModel)}}parse(e){let t={},n=null,i=[],s=[],a=[];function l(d){if(Array.isArray(i))i.push(d);else if(n!==null){if(i[n]!==void 0)throw new Error(`Duplicate property found: ${n}`);i[n]=d}}if(e&&(gi(e,{onObjectBegin:()=>{let d={};l(d),s.push(i),i=d,n=null},onObjectProperty:d=>{n=d},onObjectEnd:()=>{i=s.pop()},onArrayBegin:()=>{let d=[];l(d),s.push(i),i=d,n=null},onArrayEnd:()=>{i=s.pop()},onLiteralValue:l,onError:(d,u,p)=>{a.push({error:d,offset:u,length:p})}}),t=i[0]||t),a.length>0)throw new Error(a.map(d=>ee(d.error)).join(`
`));return t}};As=b([g(1,Du),g(2,V)],As);var Uu=class extends T{constructor(e,t,n,i){super();this.settingsResource=e;this.logService=i;this._onDidChangeConfiguration=this._register(new w);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this.defaultConfiguration=this._register(new _u(i)),this.policyConfiguration=n instanceof Ms?new ku:this._register(new As(this.defaultConfiguration,n,i)),this.userConfiguration=this._register(new Ru(this.settingsResource,{},Xi,t,i)),this.configuration=new Ls(this.defaultConfiguration.configurationModel,this.policyConfiguration.configurationModel,ut.createEmptyModel(i),ut.createEmptyModel(i),ut.createEmptyModel(i),ut.createEmptyModel(i),new He,ut.createEmptyModel(i),new He,i),this.configurationEditing=new Fg(e,t,this),this.reloadConfigurationScheduler=this._register(new It(()=>this.reloadConfiguration(),50)),this._register(this.defaultConfiguration.onDidChangeConfiguration(({defaults:s,properties:a})=>this.onDidDefaultConfigurationChange(s,a))),this._register(this.policyConfiguration.onDidChangeConfiguration(s=>this.onDidPolicyConfigurationChange(s))),this._register(this.userConfiguration.onDidChange(()=>this.reloadConfigurationScheduler.schedule()))}async initialize(){let[e,t,n]=await Promise.all([this.defaultConfiguration.initialize(),this.policyConfiguration.initialize(),this.userConfiguration.loadConfiguration()]);this.configuration=new Ls(e,t,ut.createEmptyModel(this.logService),n,ut.createEmptyModel(this.logService),ut.createEmptyModel(this.logService),new He,ut.createEmptyModel(this.logService),new He,this.logService)}getConfigurationData(){return this.configuration.toData()}getValue(e,t){let n=typeof e=="string"?e:void 0,i=Jd(e)?e:Jd(t)?t:{};return this.configuration.getValue(n,i,void 0)}async updateValue(e,t,n,i,s){let a=yI(n)?n:Jd(n)?{resource:n.resource,overrideIdentifiers:n.overrideIdentifier?[n.overrideIdentifier]:void 0}:void 0,l=a?i:n;if(l!==void 0&&l!==3&&l!==2)throw new Error(`Unable to write ${e} to target ${l}.`);a?.overrideIdentifiers&&(a.overrideIdentifiers=dt(a.overrideIdentifiers),a.overrideIdentifiers=a.overrideIdentifiers.length?a.overrideIdentifiers:void 0);let c=this.inspect(e,{resource:a?.resource,overrideIdentifier:a?.overrideIdentifiers?a.overrideIdentifiers[0]:void 0});if(c.policyValue!==void 0)throw new Error(`Unable to write ${e} because it is configured in system policy.`);if(it(t,c.defaultValue)&&(t=void 0),a?.overrideIdentifiers?.length&&a.overrideIdentifiers.length>1){let u=a.overrideIdentifiers.sort(),p=this.configuration.localUserConfiguration.overrides.find(m=>Pt([...m.identifiers].sort(),u));p&&(a.overrideIdentifiers=p.identifiers)}let d=a?.overrideIdentifiers?.length?[TI(a.overrideIdentifiers),e]:[e];await this.configurationEditing.write(d,t),await this.reloadConfiguration()}inspect(e,t={}){return this.configuration.inspect(e,t,void 0)}keys(){return this.configuration.keys(void 0)}async reloadConfiguration(){let e=await this.userConfiguration.loadConfiguration();this.onDidChangeUserConfiguration(e)}onDidChangeUserConfiguration(e){let t=this.configuration.toData(),n=this.configuration.compareAndUpdateLocalUserConfiguration(e);this.trigger(n,t,2)}onDidDefaultConfigurationChange(e,t){let n=this.configuration.toData(),i=this.configuration.compareAndUpdateDefaultConfiguration(e,t);this.trigger(i,n,7)}onDidPolicyConfigurationChange(e){let t=this.configuration.toData(),n=this.configuration.compareAndUpdatePolicyConfiguration(e);this.trigger(n,t,7)}trigger(e,t,n){let i=new Tu(e,{data:t},this.configuration,void 0,this.logService);i.source=n,this._onDidChangeConfiguration.fire(i)}},Fg=class{constructor(r,e,t){this.settingsResource=r;this.fileService=e;this.configurationService=t;this.queue=new kr}write(r,e){return this.queue.queue(()=>this.doWriteConfiguration(r,e))}async doWriteConfiguration(r,e){let t;try{t=(await this.fileService.readFile(this.settingsResource)).value.toString()}catch(s){if(s.fileOperationResult===1)t="{}";else throw s}let n=[];if(je(t,n,{allowTrailingComma:!0,allowEmptyContent:!0}),n.length>0)throw new Error("Unable to write into the settings file. Please open the file to correct errors/warnings in the file and try again.");let i=this.getEdits(t,r,e);t=Pu(t,i),await this.fileService.writeFile(this.settingsResource,U.fromString(t))}getEdits(r,e,t){let{tabSize:n,insertSpaces:i,eol:s}=this.formattingOptions;if(!e.length){let a=JSON.stringify(t,null,i?" ".repeat(n):"	");return[{content:a,length:a.length,offset:0}]}return Ds(r,e,t,{tabSize:n,insertSpaces:i,eol:s})}get formattingOptions(){if(!this._formattingOptions){let r=bn===3||bn===2?`
`:`\r
`,e=this.configurationService.getValue("files.eol",{overrideIdentifier:"jsonc"});e&&typeof e=="string"&&e!=="auto"&&(r=e),this._formattingOptions={eol:r,insertSpaces:!!this.configurationService.getValue("editor.insertSpaces",{overrideIdentifier:"jsonc"}),tabSize:this.configurationService.getValue("editor.tabSize",{overrideIdentifier:"jsonc"})}}return this._formattingOptions}};var fP="diagnosticsService",Ng=L(fP);function Vg(o){let r=o;return!!r?.hostName&&!!r?.errorMessage}import*as sb from"fs";import*as xt from"os";import{networkInterfaces as hP}from"os";var mP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rb(o){return mP.test(o)}var Le=(function(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID.bind(crypto);let o=new Uint8Array(16),r=[];for(let e=0;e<256;e++)r.push(e.toString(16).padStart(2,"0"));return function(){crypto.getRandomValues(o),o[6]=o[6]&15|64,o[8]=o[8]&63|128;let t=0,n="";return n+=r[o[t++]],n+=r[o[t++]],n+=r[o[t++]],n+=r[o[t++]],n+="-",n+=r[o[t++]],n+=r[o[t++]],n+="-",n+=r[o[t++]],n+=r[o[t++]],n+="-",n+=r[o[t++]],n+=r[o[t++]],n+="-",n+=r[o[t++]],n+=r[o[t++]],n+=r[o[t++]],n+=r[o[t++]],n+=r[o[t++]],n+=r[o[t++]],n}})();import{networkInterfaces as rA}from"os";var Wg=new class{_isVirtualMachineMacAddress(o){return this._virtualMachineOUIs||(this._virtualMachineOUIs=Mr.forStrings(),this._virtualMachineOUIs.set("00-50-56",!0),this._virtualMachineOUIs.set("00-0C-29",!0),this._virtualMachineOUIs.set("00-05-69",!0),this._virtualMachineOUIs.set("00-03-FF",!0),this._virtualMachineOUIs.set("00-1C-42",!0),this._virtualMachineOUIs.set("00-16-3E",!0),this._virtualMachineOUIs.set("08-00-27",!0),this._virtualMachineOUIs.set("00:50:56",!0),this._virtualMachineOUIs.set("00:0C:29",!0),this._virtualMachineOUIs.set("00:05:69",!0),this._virtualMachineOUIs.set("00:03:FF",!0),this._virtualMachineOUIs.set("00:1C:42",!0),this._virtualMachineOUIs.set("00:16:3E",!0),this._virtualMachineOUIs.set("08:00:27",!0)),!!this._virtualMachineOUIs.findSubstr(o)}value(){if(this._value===void 0){let o=0,r=0,e=hP();for(let t in e){let n=e[t];if(n)for(let{mac:i,internal:s}of n)s||(r+=1,this._isVirtualMachineMacAddress(i.toUpperCase())&&(o+=1))}this._value=r>0?o/r:0}return this._value}};import{exec as Mu}from"child_process";import{totalmem as vP}from"os";var yP=/[a-zA-Z-]+\.js\b/g;function Bg(o){return new Promise((r,e)=>{let t,n=new Map,i=vP();function s(l,c,d,u,p){let m=n.get(c);if(l===o||m){let h={name:a(d),cmd:d,pid:l,ppid:c,load:u,mem:he?p:i*(p/100)};n.set(l,h),l===o&&(t=h),m&&(m.children||(m.children=[]),m.children.push(h),m.children.length>1&&(m.children=m.children.sort((v,y)=>v.pid-y.pid)))}}function a(l){let c=/--utility-sub-type=network/i,d=/--crashes-directory/i,u=/conhost\.exe.+--headless/i,p=/--type=([a-zA-Z-]+)/;if(d.exec(l))return"electron-crash-reporter";if(u.exec(l))return"conpty-agent";let m=p.exec(l);if(m&&m.length===2)return m[1]==="renderer"?"window":m[1]==="utility"?c.exec(l)?"utility-network-service":"utility-process":m[1]==="extensionHost"?"extension-host":m[1];if(l.indexOf("node ")<0&&l.indexOf("node.exe")<0){let h="";do m=yP.exec(l),m&&(h+=m+" ");while(m);if(h)return`electron-nodejs (${h.trim()})`}return l}if(process.platform==="win32"){let l=c=>c.indexOf("\\\\?\\")===0||c.indexOf("\\??\\")===0?c.substring(4):c.indexOf('"\\\\?\\')===0||c.indexOf('"\\??\\')===0?'"'+c.substring(5):c;import("@vscode/windows-process-tree").then(c=>{c.getProcessList(o,d=>{if(!d){e(new Error(`Root process ${o} not found`));return}c.getProcessCpuUsage(d,u=>{let p=new Map;u.forEach(m=>{let h=l(m.commandLine||"");p.set(m.pid,{name:a(h),cmd:h,pid:m.pid,ppid:m.ppid,load:m.cpu||0,mem:m.memory||0})}),t=p.get(o),t?(p.forEach(m=>{let h=p.get(m.ppid);h&&(h.children||(h.children=[]),h.children.push(m))}),p.forEach(m=>{m.children&&(m.children=m.children.sort((h,v)=>h.pid-v.pid))}),r(t)):e(new Error(`Root process ${o} not found`))})},c.ProcessDataFlag.CommandLine|c.ProcessDataFlag.Memory)})}else{let l=function(){let c=[t],d=[];for(;c.length;){let p=c.shift();p&&(d.push(p.pid),p.children&&(c=c.concat(p.children)))}let u=JSON.stringify(dr.asFileUri("vs/base/node/cpuUsage.sh").fsPath);u+=" "+d.join(" "),Mu(u,{},(p,m,h)=>{if(p||h)e(p||new Error(h.toString()));else{let v=m.toString().split(`
`);for(let y=0;y<d.length;y++){let x=n.get(d[y]);x.load=parseFloat(v[y])}if(!t){e(new Error(`Root process ${o} not found`));return}r(t)}})};Mu("which ps",{},(c,d,u)=>{if(c||u)if(process.platform!=="linux")e(c||new Error(u.toString()));else{let p=JSON.stringify(dr.asFileUri("vs/base/node/ps.sh").fsPath);Mu(p,{},(m,h,v)=>{m||v?e(m||new Error(v.toString())):(nb(h,s),l())})}else{let p=d.toString().trim();Mu(`${p} -ax -o pid=,ppid=,pcpu=,pmem=,command=`,{maxBuffer:1e3*1024,env:{LC_NUMERIC:"en_US.UTF-8"}},(h,v,y)=>{h||y&&!y.includes("screen size is bogus")?e(h||new Error(y.toString())):(nb(v,s),process.platform==="linux"?l():t?r(t):e(new Error(`Root process ${o} not found`)))})}})}})}function nb(o,r){let e=/^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+\.[0-9]+)\s+([0-9]+\.[0-9]+)\s+(.+)$/,t=o.toString().split(`
`);for(let n of t){let i=e.exec(n.trim());i&&i.length===6&&r(parseInt(i[1]),parseInt(i[2]),i[5],parseFloat(i[3]),parseFloat(i[4]))}}var de=L("telemetryService");var $g=L("customEndpointTelemetryService");var ib="telemetry",Fs="telemetry.telemetryLevel",Au="telemetry.enableCrashReporter",lc="telemetry.enableTelemetry";var ob=new Map;async function Gg(o,r){let e=`${o}::${r.join(":")}`,t=ob.get(e);if(t)return t;let n=[{tag:"grunt.js",filePattern:/^gruntfile\.js$/i},{tag:"gulp.js",filePattern:/^gulpfile\.js$/i},{tag:"tsconfig.json",filePattern:/^tsconfig\.json$/i},{tag:"package.json",filePattern:/^package\.json$/i},{tag:"jsconfig.json",filePattern:/^jsconfig\.json$/i},{tag:"tslint.json",filePattern:/^tslint\.json$/i},{tag:"eslint.json",filePattern:/^eslint\.json$/i},{tag:"tasks.json",filePattern:/^tasks\.json$/i},{tag:"launch.json",filePattern:/^launch\.json$/i},{tag:"mcp.json",filePattern:/^mcp\.json$/i},{tag:"settings.json",filePattern:/^settings\.json$/i},{tag:"webpack.config.js",filePattern:/^webpack\.config\.js$/i},{tag:"project.json",filePattern:/^project\.json$/i},{tag:"makefile",filePattern:/^makefile$/i},{tag:"sln",filePattern:/^.+\.sln$/i},{tag:"csproj",filePattern:/^.+\.csproj$/i},{tag:"cmake",filePattern:/^.+\.cmake$/i},{tag:"github-actions",filePattern:/^.+\.ya?ml$/i,relativePathPattern:/^\.github(?:\/|\\)workflows$/i},{tag:"devcontainer.json",filePattern:/^devcontainer\.json$/i},{tag:"dockerfile",filePattern:/^(dockerfile|docker\-compose\.ya?ml)$/i},{tag:"cursorrules",filePattern:/^\.cursorrules$/i},{tag:"cursorrules-dir",filePattern:/\.mdc$/i,relativePathPattern:/^\.cursor[\/\\]rules$/i},{tag:"github-instructions-dir",filePattern:/\.instructions\.md$/i,relativePathPattern:/^\.github[\/\\]instructions$/i},{tag:"github-prompts-dir",filePattern:/\.prompt\.md$/i,relativePathPattern:/^\.github[\/\\]prompts$/i},{tag:"clinerules",filePattern:/^\.clinerules$/i},{tag:"clinerules-dir",filePattern:/\.md$/i,relativePathPattern:/^\.clinerules$/i},{tag:"agent.md",filePattern:/^agent\.md$/i},{tag:"agents.md",filePattern:/^agents\.md$/i},{tag:"claude.md",filePattern:/^claude\.md$/i},{tag:"claude-settings",filePattern:/^settings\.json$/i,relativePathPattern:/^\.claude$/i},{tag:"claude-settings-local",filePattern:/^settings\.local\.json$/i,relativePathPattern:/^\.claude$/i},{tag:"claude-mcp",filePattern:/^mcp\.json$/i,relativePathPattern:/^\.claude$/i},{tag:"claude-commands-dir",filePattern:/\.md$/i,relativePathPattern:/^\.claude[\/\\]commands$/i},{tag:"claude-skills-dir",filePattern:/^SKILL\.md$/i,relativePathPattern:/^\.claude[\/\\]skills[\/\\]/i},{tag:"claude-rules-dir",filePattern:/\.md$/i,relativePathPattern:/^\.claude[\/\\]rules$/i},{tag:"gemini.md",filePattern:/^gemini\.md$/i},{tag:"copilot-instructions.md",filePattern:/^copilot\-instructions\.md$/i,relativePathPattern:/^\.github$/i}],i=new Map,s=new Map,a=2e4;function l(d,u,p,m){let h=u.substring(d.length+1);return Ke.withAsyncBody(async v=>{let y;m.readdirCount++;try{y=await ce.readdir(u,{withFileTypes:!0})}catch{v();return}if(m.count>=a){m.count+=y.length,m.maxReached=!0,v();return}let x=y.length;if(x===0){v();return}let E=y;m.count+y.length>a&&(m.maxReached=!0,x=a-m.count,E=y.slice(0,x)),m.count+=y.length;for(let R of E)if(R.isDirectory()){if(p.includes(R.name)||await l(d,G(u,R.name),p,m),--x===0){v();return}}else{let F=R.name.lastIndexOf(".");if(F>=0){let H=R.name.substring(F+1);H&&i.set(H,(i.get(H)??0)+1)}for(let H of n)H.relativePathPattern?.test(h)!==!1&&H.filePattern.test(R.name)&&s.set(H.tag,(s.get(H.tag)??0)+1);if(--x===0){v();return}}})}let c=Ke.withAsyncBody(async d=>{let u={count:0,maxReached:!1,readdirCount:0},p=new qr(!0);await l(o,o,r,u);let m=await IP(o);d({configFiles:qg(s),fileTypes:qg(i),fileCount:u.count,maxFilesReached:u.maxReached,launchConfigFiles:m,totalScanTime:p.elapsed(),totalReaddirCount:u.readdirCount})});return ob.set(e,c),c}function qg(o){return Array.from(o.entries(),([r,e])=>({name:r,count:e})).sort((r,e)=>e.count-r.count)}function SP(){let o={os:`${xt.type()} ${xt.arch()} ${xt.release()}`,memory:`${(xt.totalmem()/fi.GB).toFixed(2)}GB (${(xt.freemem()/fi.GB).toFixed(2)}GB free)`,vmHint:`${Math.round(Wg.value()*100)}%`},r=xt.cpus();return r&&r.length>0&&(o.cpus=`${r[0].model} (${r.length} x ${r[0].speed})`),o}async function IP(o){try{let r=new Map,e=G(o,".vscode","launch.json"),t=await sb.promises.readFile(e),n=[],i=je(t.toString(),n);if(n.length)return console.log(`Unable to parse ${e}`),[];if(hi(i)==="object"&&i.configurations)for(let s of i.configurations){let a=s.type;a&&(r.has(a)?r.set(a,r.get(a)+1):r.set(a,1))}return qg(r)}catch{return[]}}var Os=class{constructor(r,e){this.telemetryService=r;this.productService=e}formatMachineInfo(r){let e=[];return e.push(`OS Version:       ${r.os}`),e.push(`CPUs:             ${r.cpus}`),e.push(`Memory (System):  ${r.memory}`),e.push(`VM:               ${r.vmHint}`),e.join(`
`)}formatEnvironment(r){let e=[];e.push(`Version:          ${this.productService.nameShort} ${this.productService.version} (${this.productService.commit||"Commit unknown"}, ${this.productService.date||"Date unknown"})`),e.push(`OS Version:       ${xt.type()} ${xt.arch()} ${xt.release()}`);let t=xt.cpus();return t&&t.length>0&&e.push(`CPUs:             ${t[0].model} (${t.length} x ${t[0].speed})`),e.push(`Memory (System):  ${(xt.totalmem()/fi.GB).toFixed(2)}GB (${(xt.freemem()/fi.GB).toFixed(2)}GB free)`),he||e.push(`Load (avg):       ${xt.loadavg().map(n=>Math.round(n)).join(", ")}`),e.push(`VM:               ${Math.round(Wg.value()*100)}%`),e.push(`Screen Reader:    ${r.screenReader?"yes":"no"}`),e.push(`Process Argv:     ${r.mainArguments.join(" ")}`),e.push(`GPU Status:       ${this.expandGPUFeatures(r.gpuFeatureStatus)}`),r.gpuLogMessages&&r.gpuLogMessages.length>0&&(e.push("GPU Log Messages:"),r.gpuLogMessages.forEach(n=>{e.push(`${n.header}: ${n.message}`)})),e.join(`
`)}async getPerformanceInfo(r,e){return Promise.all([Bg(r.mainPID),this.formatWorkspaceMetadata(r)]).then(async t=>{let[n,i]=t,s=this.formatProcessList(r,n);return e.forEach(a=>{if(Vg(a))s+=`
${a.errorMessage}`,i+=`
${a.errorMessage}`;else if(s+=`

Remote: ${a.hostName}`,a.processes&&(s+=`
${this.formatProcessList(r,a.processes)}`),a.workspaceMetadata){i+=`
|  Remote: ${a.hostName}`;for(let l of Object.keys(a.workspaceMetadata)){let c=a.workspaceMetadata[l],d=`${c.fileCount} files`;c.maxFilesReached&&(d=`more than ${d}`),i+=`|    Folder (${l}): ${d}`,i+=this.formatWorkspaceStats(c)}}}),{processInfo:s,workspaceInfo:i}})}async getSystemInfo(r,e){let{memory:t,vmHint:n,os:i,cpus:s}=SP(),a={os:i,memory:t,cpus:s,vmHint:n,processArgs:`${r.mainArguments.join(" ")}`,gpuStatus:r.gpuFeatureStatus,screenReader:`${r.screenReader?"yes":"no"}`,remoteData:e};return he||(a.load=`${xt.loadavg().map(l=>Math.round(l)).join(", ")}`),Be&&(a.linuxEnv={desktopSession:process.env.DESKTOP_SESSION,xdgSessionDesktop:process.env.XDG_SESSION_DESKTOP,xdgCurrentDesktop:process.env.XDG_CURRENT_DESKTOP,xdgSessionType:process.env.XDG_SESSION_TYPE}),Promise.resolve(a)}async getDiagnostics(r,e){let t=[];return Bg(r.mainPID).then(async n=>(t.push(""),t.push(this.formatEnvironment(r)),t.push(""),t.push(this.formatProcessList(r,n)),r.windows.some(i=>i.folderURIs&&i.folderURIs.length>0&&!i.remoteAuthority)&&(t.push(""),t.push("Workspace Stats: "),t.push(await this.formatWorkspaceMetadata(r))),e.forEach(i=>{if(Vg(i))t.push(`
${i.errorMessage}`);else if(t.push(`

`),t.push(`Remote:           ${i.hostName}`),t.push(this.formatMachineInfo(i.machineInfo)),i.processes&&t.push(this.formatProcessList(r,i.processes)),i.workspaceMetadata)for(let s of Object.keys(i.workspaceMetadata)){let a=i.workspaceMetadata[s],l=`${a.fileCount} files`;a.maxFilesReached&&(l=`more than ${l}`),t.push(`Folder (${s}): ${l}`),t.push(this.formatWorkspaceStats(a))}}),t.push(""),t.push(""),t.join(`
`)))}formatWorkspaceStats(r){let e=[],n=0,i=(c,d)=>{let u=` ${c}(${d})`;n+u.length>60?(e.push(s),s="|                 ",n=s.length):n+=u.length,s+=u},s="|      File types:",a=10,l=r.fileTypes.length>a?a:r.fileTypes.length;for(let c=0;c<l;c++){let d=r.fileTypes[c];i(d.name,d.count)}if(e.push(s),r.configFiles.length>=0&&(s="|      Conf files:",n=0,r.configFiles.forEach(c=>{i(c.name,c.count)}),e.push(s)),r.launchConfigFiles.length>0){let c="|      Launch Configs:";r.launchConfigFiles.forEach(d=>{let u=d.count>1?` ${d.name}(${d.count})`:` ${d.name}`;c+=u}),e.push(c)}return e.join(`
`)}expandGPUFeatures(r){let e=Math.max(...Object.keys(r).map(t=>t.length));return Object.keys(r).map(t=>`${t}:  ${" ".repeat(e-t.length)}  ${r[t]}`).join(`
                  `)}formatWorkspaceMetadata(r){let e=[],t=[];return r.windows.forEach(n=>{n.folderURIs.length===0||n.remoteAuthority||(e.push(`|  Window (${n.title})`),n.folderURIs.forEach(i=>{let s=P.revive(i);if(s.scheme===re.file){let a=s.fsPath;t.push(Gg(a,["node_modules",".git"]).then(l=>{let c=`${l.fileCount} files`;l.maxFilesReached&&(c=`more than ${c}`),e.push(`|    Folder (${lt(a)}): ${c}`),e.push(this.formatWorkspaceStats(l))}).catch(l=>{e.push(`|      Error: Unable to collect workspace stats for folder ${a} (${l.toString()})`)}))}else e.push(`|    Folder (${s.toString()}): Workspace stats not available.`)}))}),Promise.all(t).then(n=>e.join(`
`)).catch(n=>`Unable to collect workspace stats: ${n}`)}formatProcessList(r,e){let t=new Map;r.windows.forEach(i=>t.set(i.pid,`window [${i.id}] (${i.title})`)),r.pidToNames.forEach(({pid:i,name:s})=>t.set(i,s));let n=[];return n.push("CPU %	Mem MB	   PID	Process"),e&&this.formatProcessItem(r.mainPID,t,n,e,0),n.join(`
`)}formatProcessItem(r,e,t,n,i){let s=i===0,a;s?a=n.pid===r?this.productService.applicationName:"remote-server":e.has(n.pid)?a=e.get(n.pid):a=`${"  ".repeat(i)} ${n.name}`;let l=process.platform==="win32"?n.mem:xt.totalmem()*(n.mem/100);t.push(`${n.load.toFixed(0).padStart(5," ")}	${(l/fi.MB).toFixed(0).padStart(6," ")}	${n.pid.toFixed(0).padStart(6," ")}	${a}`),Array.isArray(n.children)&&n.children.forEach(c=>this.formatProcessItem(r,e,t,c,i+1))}async getWorkspaceFileExtensions(r){let e=new Set;for(let{uri:t}of r.folders){let n=P.revive(t);if(n.scheme!==re.file)continue;let i=n.fsPath;try{(await Gg(i,["node_modules",".git"])).fileTypes.forEach(a=>e.add(a.name))}catch{}}return{extensions:[...e]}}async reportWorkspaceStats(r){for(let{uri:e}of r.folders){let t=P.revive(e);if(t.scheme!==re.file)continue;let n=t.fsPath;try{let i=await Gg(n,["node_modules",".git"]);this.telemetryService.publicLog2("workspace.stats",{"workspace.id":r.telemetryId,rendererSessionId:r.rendererSessionId}),i.fileTypes.forEach(s=>{this.telemetryService.publicLog2("workspace.stats.file",{rendererSessionId:r.rendererSessionId,type:s.name,count:s.count})}),i.launchConfigFiles.forEach(s=>{this.telemetryService.publicLog2("workspace.stats.launchConfigFile",{rendererSessionId:r.rendererSessionId,type:s.name,count:s.count})}),i.configFiles.forEach(s=>{this.telemetryService.publicLog2("workspace.stats.configFiles",{rendererSessionId:r.rendererSessionId,type:s.name,count:s.count})}),this.telemetryService.publicLog2("workspace.stats.metadata",{duration:i.totalScanTime,reachedLimit:i.maxFilesReached,fileCount:i.fileCount,readdirCount:i.totalReaddirCount})}catch{}}}};Os=b([g(0,de),g(1,ne)],Os);var Fu=L("downloadService");var Nr=L("requestService"),Kg=class{constructor(r){this.original=r}toJSON(){if(!this.headers){let r=Object.create(null);for(let e in this.original)e.toLowerCase()==="authorization"||e.toLowerCase()==="proxy-authorization"?r[e]="*****":r[e]=this.original[e];this.headers=r}return this.headers}},Ou=class extends T{constructor(e){super();this.logService=e;this.counter=0}async logAndRequest(e,t){let n=`#${++this.counter}: ${e.url}`;this.logService.trace(`${n} - begin`,e.type,new Kg(e.headers??{}));try{let i=await t();return this.logService.trace(`${n} - end`,e.type,i.res.statusCode,i.res.headers),i}catch(i){throw this.logService.error(`${n} - error`,e.type,ee(i)),i}}};function Kn(o){return o.res.statusCode&&o.res.statusCode>=200&&o.res.statusCode<300||o.res.statusCode===1223}function cb(o){return!!o.res.statusCode&&o.res.statusCode>=400&&o.res.statusCode<500}function db(o){return!!o.res.statusCode&&o.res.statusCode>=500&&o.res.statusCode<600}function Nu(o){return o.res.statusCode===204}async function cc(o){return Nu(o)?null:(await En(o.stream)).toString()}async function Vr(o){if(!Kn(o))throw new Error("Server returned "+o.res.statusCode);return cc(o)}async function jr(o){if(!Kn(o))throw new Error("Server returned "+o.res.statusCode);if(Nu(o))return null;let e=(await En(o.stream)).toString();try{return JSON.parse(e)}catch(t){throw t.message+=`:
`+e,t}}var jg=!1,zg=[],ab,lb;function bP(o=!0,r=!0){if(ab===o&&lb===r)return;ab=o,lb=r;let e=gt.as(zt.Configuration),t=zg;zg=[{id:"http",order:15,title:S(2276,null),type:"object",scope:2,properties:{"http.useLocalProxyConfiguration":{type:"boolean",default:r,markdownDescription:S(2291,null),restricted:!0}}},{id:"http",order:15,title:S(2276,null),type:"object",scope:1,properties:{"http.electronFetch":{type:"boolean",default:!1,description:S(2274,null),restricted:!0}}},{id:"http",order:15,title:S(2276,null),type:"object",scope:o?1:2,properties:{"http.proxy":{type:"string",pattern:"^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",markdownDescription:S(2279,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyStrictSSL":{type:"boolean",default:!0,markdownDescription:S(2287,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyKerberosServicePrincipal":{type:"string",markdownDescription:S(2281,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.noProxy":{type:"array",items:{type:"string"},markdownDescription:S(2278,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyAuthorization":{type:["null","string"],default:null,markdownDescription:S(2280,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxySupport":{type:"string",enum:["off","on","fallback","override"],enumDescriptions:[S(2284,null),S(2285,null),S(2283,null),S(2286,null)],default:"override",markdownDescription:S(2282,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificates":{type:"boolean",default:!0,markdownDescription:S(2288,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificatesNode":{type:"boolean",tags:["experimental"],default:jg,markdownDescription:S(2289,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}},"http.experimental.systemCertificatesV2":{type:"boolean",tags:["experimental"],default:!1,markdownDescription:S(2290,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.fetchAdditionalSupport":{type:"boolean",default:!0,markdownDescription:S(2275,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.experimental.networkInterfaceCheckInterval":{type:"number",default:300,minimum:-1,tags:["experimental"],markdownDescription:S(2277,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}}}}],e.updateConfigurations({add:zg,remove:t})}bP();var Ns=class{constructor(r,e){this.requestService=r;this.fileService=e}async download(r,e,t=Y.None){if(r.scheme===re.file||r.scheme===re.vscodeRemote){await this.fileService.copy(r,e);return}let n={type:"GET",url:r.toString(!0)},i=await this.requestService.request(n,t);if(i.res.statusCode===200)await this.fileService.writeFile(e,i.stream);else{let s=await Vr(i);throw new Error(`Expected 200, got back ${i.res.statusCode} instead.

${s}`)}}};Ns=b([g(0,Nr),g(1,W)],Ns);function xP(o){if(In===2&&/^penguin(\.|$)/i.test(o))return"chromebook"}function ub(o,r,e,t,n,i,s,a,l,c,d){let u=Object.create(null);u["common.machineId"]=i,u["common.sqmId"]=s,u["common.devDeviceId"]=a,u.sessionID=Le()+Date.now(),u.commitHash=t,u.version=n,u["common.releaseDate"]=c,u["common.platformVersion"]=(o||"").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/,"$1$2$3"),u["common.platform"]=cd(In),u["common.nodePlatform"]=vd,u["common.nodeArch"]=e,u["common.product"]=d||"desktop",l&&(u["common.msftInternal"]=l);let p=0,m=Date.now();Object.defineProperties(u,{timestamp:{get:()=>new Date,enumerable:!0},"common.timesincesessionstart":{get:()=>Date.now()-m,enumerable:!0},"common.sequence":{get:()=>p++,enumerable:!0}}),Hy&&(u["common.snap"]="true");let h=xP(r);return h&&(u["common.platformDetail"]=h),u}function pb(o){let r=Fe.USERDNSDOMAIN;if(!r)return!1;let e=r.toLowerCase();return o.some(t=>e===t)}var Si=class{constructor(r){this.value=r;this.isTrustedTelemetryValue=!0}},Hg=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=!1}publicLog(){}publicLog2(){}publicLogError(){}publicLogError2(){}setExperimentProperty(){}},mb=new Hg;var Jg="telemetry",gb={id:Jg,name:S(2316,null)},hb={log:()=>null,flush:()=>Promise.resolve(void 0)};function Vu(o,r){return!r.isBuilt&&!r.disableTelemetry?!0:!(r.disableTelemetry||!o.enableTelemetry)}function Wu(o,r){return r.extensionTestsLocationURI?!0:!(r.isBuilt||r.disableTelemetry||o.enableTelemetry&&o.aiConfig?.ariaKey)}function Bu(o){let r=o.getValue(Fs),e=o.getValue(Au);if(o.getValue(lc)===!1||e===!1)return 0;switch(r??"all"){case"all":return 3;case"error":return 2;case"crash":return 1;case"off":return 0}}function $u(o){let r={},e={},t={};vb(o,t);for(let n in t){n=n.length>150?n.substr(n.length-149):n;let i=t[n];typeof i=="number"?e[n]=i:typeof i=="boolean"?e[n]=i?1:0:typeof i=="string"?(i.length>8192&&console.warn(`Telemetry property: ${n} has been trimmed to 8192, the original length is ${i.length}`),r[n]=i.substring(0,8191)):typeof i<"u"&&i!==null&&(r[n]=String(i))}return{properties:r,measurements:e}}function vb(o,r,e=0,t){if(!o||typeof o!="object"&&typeof o!="function")return;let n=o;for(let i of Object.getOwnPropertyNames(n)){let s=n[i],a=t?t+i:i;Array.isArray(s)?r[a]=Mg(s):s instanceof Date?r[a]=s.toISOString():Re(s)?e<2?vb(s,r,e+1,a+"."):r[a]=Mg(s):r[a]=s}}function yb(o,r){let e=o.msftInternalDomains||[],t=r.getValue("telemetry.internalTesting");return pb(e)||t}function Sb(o){return[o.appRoot,o.extensionsPath,o.userHome.fsPath,o.tmpDir.fsPath,o.userDataPath]}function wP(o,r){if(!o||!o.includes("/")&&!o.includes("\\"))return o;let e=o,t=[];for(let l of r)for(;;){let c=l.exec(o);if(!c)break;t.push([c.index,l.lastIndex])}let n=/^[\\\/]?(node_modules|node_modules\.asar)[\\\/]/,i=/^(.*?)((?:\.vscode(?:-[a-z]+)*|resources[\\\/]app)[\\\/]extensions[\\\/].*)$/i,s=/(file:\/\/)?([a-zA-Z]:(\\\\|\\|\/)|(\\\\|\\|\/))?([\w-\._]+(\\\\|\\|\/))+[\w-\._]*/g,a=0;for(e="";;){let l=s.exec(o);if(!l)break;let c=t.some(([d,u])=>l.index<u&&d<s.lastIndex);if(!n.test(l[0])&&!c){let d=i.exec(l[0]);d?e+=o.substring(a,l.index)+"<REDACTED: user-file-path>/"+d[2]:e+=o.substring(a,l.index)+"<REDACTED: user-file-path>",a=s.lastIndex}}return a<o.length&&(e+=o.substr(a)),e}function PP(o){if(!o)return o;let r=[{label:"URL",regex:/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s]*/},{label:"Google API Key",regex:/AIza[A-Za-z0-9_\\\-]{35}/},{label:"JWT",regex:/eyJ[0eXAiOiJKV1Qi|hbGci|a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+/},{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.-]+\.[a-zA-Z]{2,}/}];for(let e of r)if(e.regex.test(o))return`<REDACTED: ${e.label}>`;return o}function Ib(o,r){return o?_s(o,e=>{if(e instanceof Si||Object.hasOwnProperty.call(e,"isTrustedTelemetryValue"))return e.value;if(typeof e=="string"){let t=e.replaceAll("%20"," ");t=wP(t,r);for(let n of r)t=t.replace(n,"");return t=PP(t),t}}):{}}function j(o,r){return o.uuid&&r.uuid?o.uuid===r.uuid:o.id===r.id?!0:Xo(o.id,r.id)===0}var RP=/^([^.]+\..+)-(\d+\.\d+\.\d+)(-(.+))?$/,Lt=class o{constructor(r,e,t="undefined"){this.identifier=r;this.version=e;this.targetPlatform=t;this.id=r.id}static create(r){let e=r.manifest?r.manifest.version:r.version,t=r.manifest?r.targetPlatform:r.properties.targetPlatform;return new o(r.identifier,e,t)}static parse(r){let e=RP.exec(r);return e&&e[1]&&e[2]?new o({id:e[1]},e[2],e[4]||void 0):null}toString(){return`${this.id}-${this.version}${this.targetPlatform!=="undefined"?`-${this.targetPlatform}`:""}`}equals(r){return r instanceof o?j(this,r)&&this.version===r.version&&this.targetPlatform===r.targetPlatform:!1}},TP=/^([^.]+\..+)@((prerelease)|(\d+\.\d+\.\d+(-.*)?))$/;function bb(o){let r=TP.exec(o);return r&&r[1]?[oo(r[1]),r[2]]:[oo(o),void 0]}function so(o,r){return`${o}.${r}`}function oo(o){return o.toLowerCase()}function Er(o,r){return oo(so(o??su,r))}function Gu(o,r){let e=[],t=n=>{for(let i of e)if(i.some(s=>j(r(s),r(n))))return i;return null};for(let n of o){let i=t(n);i?i.push(n):e.push([n])}return e}function xb(o){return{id:o.identifier.id,name:o.manifest.name,galleryId:null,publisherId:o.publisherId,publisherName:o.manifest.publisher,publisherDisplayName:o.publisherDisplayName,dependencies:o.manifest.extensionDependencies&&o.manifest.extensionDependencies.length>0}}function dc(o){return{id:new Si(o.identifier.id),name:new Si(o.name),extensionVersion:o.version,galleryId:o.identifier.uuid,publisherId:o.publisherId,publisherName:o.publisher,publisherDisplayName:o.publisherDisplayName,isPreReleaseVersion:o.properties.isPreReleaseVersion,dependencies:!!(o.properties.dependencies&&o.properties.dependencies.length>0),isSigned:o.isSigned,...o.telemetryData}}var V5=new on("pprice.better-merge");async function CP(o,r){if(!Be)return!1;let e;try{e=(await o.readFile(P.file("/etc/os-release"))).value.toString()}catch{try{e=(await o.readFile(P.file("/usr/lib/os-release"))).value.toString()}catch(n){r.debug("Error while getting the os-release file.",ee(n))}}return!!e&&(e.match(/^ID=([^\u001b\r\n]*)/m)||[])[1]==="alpine"}async function qu(o,r){let e=await CP(o,r),t=mu(e?"alpine":In,yd);return r.debug("ComputeTargetPlatform:",t),t}function Eb(o,r){return DP(o,r)!==void 0}function DP(o,r){return r.find(({extensionOrPublisher:e})=>ue(e)?Xo(o.id.split(".")[0],e)===0:j(o,e))}function Qg(o){let r=[];typeof o=="number"&&r.push("code/timeOrigin",o);function e(n,i){r.push(n,i?.startTime??Date.now())}function t(){let n=[];for(let i=0;i<r.length;i+=2)n.push({name:r[i],startTime:r[i+1]});return n}return{mark:e,getMarks:t}}function _P(){if(typeof performance=="object"&&typeof performance.mark=="function"&&!performance.nodeTiming)return typeof performance.timeOrigin!="number"&&!performance.timing?Qg():{mark(o,r){performance.mark(o,r)},getMarks(){let o=performance.timeOrigin;typeof o!="number"&&(o=(performance.timing.navigationStart||performance.timing.redirectStart||performance.timing.fetchStart)??0);let r=[{name:"code/timeOrigin",startTime:Math.round(o)}];for(let e of performance.getEntriesByType("mark"))r.push({name:e.name,startTime:Math.round(o+e.startTime)});return r}};if(typeof process=="object"){let o=performance?.timeOrigin;return Qg(o)}else return console.trace("perf-util loaded in UNKNOWN environment"),Qg()}function kP(o){return o.MonacoPerformanceMarks||(o.MonacoPerformanceMarks=_P()),o.MonacoPerformanceMarks}var wb=kP(globalThis),Tn=wb.mark,B5=wb.getMarks;var jn=class o extends T{constructor(e,t=Object.create(null)){super();this.database=e;this.options=t;this._onDidChangeStorage=this._register(new ri);this.onDidChangeStorage=this._onDidChangeStorage.event;this.state=0;this.cache=new Map;this.flushDelayer=this._register(new ur(o.DEFAULT_FLUSH_DELAY));this.pendingDeletes=new Set;this.pendingInserts=new Map;this.pendingClose=void 0;this.whenFlushedCallbacks=[];this.registerListeners()}static{this.DEFAULT_FLUSH_DELAY=100}registerListeners(){this._register(this.database.onDidChangeItemsExternal(e=>this.onDidChangeItemsExternal(e)))}onDidChangeItemsExternal(e){this._onDidChangeStorage.pause();try{e.changed?.forEach((t,n)=>this.acceptExternal(n,t)),e.deleted?.forEach(t=>this.acceptExternal(t,void 0))}finally{this._onDidChangeStorage.resume()}}acceptExternal(e,t){if(this.state===2)return;let n=!1;ft(t)?n=this.cache.delete(e):this.cache.get(e)!==t&&(this.cache.set(e,t),n=!0),n&&this._onDidChangeStorage.fire({key:e,external:!0})}get items(){return this.cache}get size(){return this.cache.size}async init(){this.state===0&&(this.state=1,this.options.hint!==0&&(this.cache=await this.database.getItems()))}get(e,t){let n=this.cache.get(e);return ft(n)?t:n}getBoolean(e,t){let n=this.get(e);return ft(n)?t:n==="true"}getNumber(e,t){let n=this.get(e);return ft(n)?t:parseInt(n,10)}getObject(e,t){let n=this.get(e);return ft(n)?t:XS(n)}async set(e,t,n=!1){if(this.state===2)return;if(ft(t))return this.delete(e,n);let i=Re(t)||Array.isArray(t)?QS(t):String(t);if(this.cache.get(e)!==i)return this.cache.set(e,i),this.pendingInserts.set(e,i),this.pendingDeletes.delete(e),this._onDidChangeStorage.fire({key:e,external:n}),this.doFlush()}async delete(e,t=!1){if(!(this.state===2||!this.cache.delete(e)))return this.pendingDeletes.has(e)||this.pendingDeletes.add(e),this.pendingInserts.delete(e),this._onDidChangeStorage.fire({key:e,external:t}),this.doFlush()}async optimize(){if(this.state!==2)return await this.flush(0),this.database.optimize()}async close(){return this.pendingClose||(this.pendingClose=this.doClose()),this.pendingClose}async doClose(){this.state=2;try{await this.doFlush(0)}catch{}await this.database.close(()=>this.cache)}get hasPending(){return this.pendingInserts.size>0||this.pendingDeletes.size>0}async flushPending(){if(!this.hasPending)return;let e={insert:this.pendingInserts,delete:this.pendingDeletes};return this.pendingDeletes=new Set,this.pendingInserts=new Map,this.database.updateItems(e).finally(()=>{if(!this.hasPending)for(;this.whenFlushedCallbacks.length;)this.whenFlushedCallbacks.pop()?.()})}async flush(e){if(!(this.state===2||this.pendingClose))return this.doFlush(e)}async doFlush(e){return this.options.hint===1?this.flushPending():this.flushDelayer.trigger(()=>this.flushPending(),e)}async whenFlushed(){if(this.hasPending)return new Promise(e=>this.whenFlushedCallbacks.push(e))}isInMemory(){return this.options.hint===1}};var te=L("IUriIdentityService");function ju(o){let r=o;return!!(r&&typeof r=="object"&&typeof r.id=="string"&&typeof r.isDefault=="boolean"&&typeof r.name=="string"&&P.isUri(r.location)&&P.isUri(r.globalStorageHome)&&P.isUri(r.settingsResource)&&P.isUri(r.keybindingsResource)&&P.isUri(r.tasksResource)&&P.isUri(r.snippetsHome)&&P.isUri(r.promptsHome)&&P.isUri(r.extensionsResource)&&P.isUri(r.mcpResource))}var fe=L("IUserDataProfilesService");function nr(o,r){return{id:o.id,isDefault:o.isDefault,name:o.name,icon:o.icon,location:P.revive(o.location).with({scheme:r}),globalStorageHome:P.revive(o.globalStorageHome).with({scheme:r}),settingsResource:P.revive(o.settingsResource).with({scheme:r}),keybindingsResource:P.revive(o.keybindingsResource).with({scheme:r}),tasksResource:P.revive(o.tasksResource).with({scheme:r}),snippetsHome:P.revive(o.snippetsHome).with({scheme:r}),promptsHome:P.revive(o.promptsHome).with({scheme:r}),extensionsResource:P.revive(o.extensionsResource).with({scheme:r}),mcpResource:P.revive(o.mcpResource).with({scheme:r}),cacheHome:P.revive(o.cacheHome).with({scheme:r}),useDefaultFlags:o.useDefaultFlags,isTransient:o.isTransient,workspaces:o.workspaces?.map(e=>P.revive(e))}}function zu(o,r,e,t,n,i){return{id:o,name:r,location:e,isDefault:!1,icon:n?.icon,globalStorageHome:i&&n?.useDefaultFlags?.globalState?i.globalStorageHome:$(e,"globalStorage"),settingsResource:i&&n?.useDefaultFlags?.settings?i.settingsResource:$(e,"settings.json"),keybindingsResource:i&&n?.useDefaultFlags?.keybindings?i.keybindingsResource:$(e,"keybindings.json"),tasksResource:i&&n?.useDefaultFlags?.tasks?i.tasksResource:$(e,"tasks.json"),snippetsHome:i&&n?.useDefaultFlags?.snippets?i.snippetsHome:$(e,"snippets"),promptsHome:i&&n?.useDefaultFlags?.prompts?i.promptsHome:$(e,"prompts"),extensionsResource:i&&n?.useDefaultFlags?.extensions?i.extensionsResource:$(e,"extensions.json"),mcpResource:i&&n?.useDefaultFlags?.mcp?i.mcpResource:$(e,"mcp.json"),cacheHome:$(t,o),useDefaultFlags:n?.useDefaultFlags,isTransient:n?.transient,workspaces:n?.workspaces}}var Ku=class extends T{constructor(e,t,n,i){super();this.environmentService=e;this.fileService=t;this.uriIdentityService=n;this.logService=i;this._onDidChangeProfiles=this._register(new w);this.onDidChangeProfiles=this._onDidChangeProfiles.event;this._onWillCreateProfile=this._register(new w);this.onWillCreateProfile=this._onWillCreateProfile.event;this._onWillRemoveProfile=this._register(new w);this.onWillRemoveProfile=this._onWillRemoveProfile.event;this._onDidResetWorkspaces=this._register(new w);this.onDidResetWorkspaces=this._onDidResetWorkspaces.event;this.profileCreationPromises=new Map;this.transientProfilesObject={profiles:[],emptyWindows:new Map};this.profilesHome=$(this.environmentService.userRoamingDataHome,"profiles"),this.profilesCacheHome=$(this.environmentService.cacheHome,"CachedProfilesData")}static{this.PROFILES_KEY="userDataProfiles"}static{this.PROFILE_ASSOCIATIONS_KEY="profileAssociations"}get defaultProfile(){return this.profiles[0]}get profiles(){return[...this.profilesObject.profiles,...this.transientProfilesObject.profiles]}init(){this._profilesObject=void 0}get profilesObject(){if(!this._profilesObject){let e=this.createDefaultProfile(),t=[e];try{for(let i of this.getStoredProfiles()){if(this.isInvalidProfile(i)){this.logService.warn("Skipping the invalid stored profile",i.location||i.name);continue}let s=Nn(i.location);t.push(zu(s,i.name,i.location,this.profilesCacheHome,{icon:i.icon,useDefaultFlags:i.useDefaultFlags},e))}}catch(i){this.logService.error(i)}let n=new Map;if(t.length)try{let i=this.getStoredProfileAssociations();if(i.workspaces)for(let[s,a]of Object.entries(i.workspaces)){let l=P.parse(s),c=t.find(d=>d.id===a);if(c){let d=c.workspaces?c.workspaces.slice(0):[];d.push(l),c.workspaces=d}}if(i.emptyWindows)for(let[s,a]of Object.entries(i.emptyWindows)){let l=t.find(c=>c.id===a);l&&n.set(s,l)}}catch(i){this.logService.error(i)}this._profilesObject={profiles:t,emptyWindows:n}}return this._profilesObject}isInvalidProfile(e){return!!(!e.name||!ue(e.name)||!e.location||e.isSystem||this.uriIdentityService.extUri.basename(this.uriIdentityService.extUri.dirname(e.location))==="builtin")}createDefaultProfile(){let e=zu("__default__profile__",S(2707,null),this.environmentService.userRoamingDataHome,this.profilesCacheHome);return{...e,extensionsResource:this.getDefaultProfileExtensionsLocation()??e.extensionsResource,isDefault:!0}}async createTransientProfile(e){let t="Temp",n=new RegExp(`${zr(t)}\\s(\\d+)`),i=0;for(let a of this.profiles){let l=n.exec(a.name),c=l?parseInt(l[1]):0;i=c>i?c:i}let s=`${t} ${i+1}`;return this.createProfile(rn(Le()).toString(16),s,{transient:!0},e)}async createNamedProfile(e,t,n){return this.createProfile(rn(Le()).toString(16),e,t,n)}async createProfile(e,t,n,i){return await this.doCreateProfile(e,t,n,i)}async doCreateProfile(e,t,n,i){if(!ue(t)||!t)throw new Error("Name of the profile is mandatory and must be of type `string`");let s=this.profileCreationPromises.get(t);return s||(s=(async()=>{try{if(this.profiles.find(u=>u.id===e||!u.isTransient&&!n?.transient&&u.name===t))throw new Error(`Profile with ${t} name already exists`);let l=i?this.getWorkspace(i):void 0;P.isUri(l)&&(n={...n,workspaces:[l]});let c=zu(e,t,this.uriIdentityService.extUri.joinPath(this.profilesHome,e),this.profilesCacheHome,n,this.defaultProfile);await this.fileService.createFolder(c.location);let d=[];return this._onWillCreateProfile.fire({profile:c,join(u){d.push(u)}}),await Ke.settled(d),l&&!P.isUri(l)&&this.updateEmptyWindowAssociation(l,c,!!c.isTransient),this.updateProfiles([c],[],[]),c}finally{this.profileCreationPromises.delete(t)}})(),this.profileCreationPromises.set(t,s)),s}async updateProfile(e,t){let n=[];for(let s of this.profiles){let a;if(e.id===s.id)s.isDefault?t.workspaces&&(a=s,a.workspaces=t.workspaces):a=zu(s.id,t.name??s.name,s.location,this.profilesCacheHome,{icon:t.icon===null?void 0:t.icon??s.icon,transient:t.transient??s.isTransient,useDefaultFlags:t.useDefaultFlags??s.useDefaultFlags,workspaces:t.workspaces??s.workspaces},this.defaultProfile);else if(t.workspaces){let l=s.workspaces?.filter(c=>!t.workspaces?.some(d=>this.uriIdentityService.extUri.isEqual(c,d)));s.workspaces?.length!==l?.length&&(a=s,a.workspaces=l)}a&&n.push(a)}if(!n.length)throw e.isDefault?new Error("Cannot update default profile"):new Error(`Profile '${e.name}' does not exist`);this.updateProfiles([],[],n);let i=this.profiles.find(s=>s.id===e.id);if(!i)throw new Error(`Profile '${e.name}' was not updated`);return i}async removeProfile(e){if(e.isDefault)throw new Error("Cannot remove default profile");let t=this.profiles.find(i=>i.id===e.id);if(!t)throw new Error(`Profile '${e.name}' does not exist`);let n=[];this._onWillRemoveProfile.fire({profile:t,join(i){n.push(i)}});try{await Promise.allSettled(n)}catch(i){this.logService.error(i)}this.updateProfiles([],[t],[]);try{await this.fileService.del(t.cacheHome,{recursive:!0})}catch(i){_e(i)!==1&&this.logService.error(i)}}async setProfileForWorkspace(e,t){let n=this.profiles.find(s=>s.id===t.id);if(!n)throw new Error(`Profile '${t.name}' does not exist`);let i=this.getWorkspace(e);if(P.isUri(i)){let s=n.workspaces?[...n.workspaces]:[];s.some(a=>this.uriIdentityService.extUri.isEqual(a,i))||(s.push(i),await this.updateProfile(n,{workspaces:s}))}else this.updateEmptyWindowAssociation(i,n,!1),this.updateStoredProfiles(this.profiles)}unsetWorkspace(e,t=!1){let n=this.getWorkspace(e);if(P.isUri(n)){let i=this.getProfileForWorkspace(e);i&&this.updateProfile(i,{workspaces:i.workspaces?.filter(s=>!this.uriIdentityService.extUri.isEqual(s,n))})}else this.updateEmptyWindowAssociation(n,void 0,t),this.updateStoredProfiles(this.profiles)}async resetWorkspaces(){this.transientProfilesObject.emptyWindows.clear(),this.profilesObject.emptyWindows.clear();for(let e of this.profiles)e.workspaces=void 0;this.updateProfiles([],[],this.profiles),this._onDidResetWorkspaces.fire()}async cleanUp(){try{if(await this.fileService.exists(this.profilesHome)){let e=this.uriIdentityService.extUri.joinPath(this.profilesHome,"builtin");if(await this.fileService.exists(e))try{await this.fileService.del(e,{recursive:!0})}catch(n){this.logService.error(n)}let t=await this.fileService.resolve(this.profilesHome);await Promise.all((t.children||[]).filter(n=>n.isDirectory&&this.profiles.every(i=>!this.uriIdentityService.extUri.isEqual(i.location,n.resource))).map(n=>this.fileService.del(n.resource,{recursive:!0})))}}catch(e){this.logService.error("Error deleting redundant profile folders",e)}try{let e=this.getStoredProfiles(),t=[];for(let n of this.getStoredProfiles())this.isInvalidProfile(n)?this.logService.warn(`Invalid user data profile found: ${n.name}`):t.push(n);e.length!==t.length&&this.saveStoredProfiles(t)}catch(e){this.logService.error("Error removing invalid stored profiles",e)}}async cleanUpTransientProfiles(){let e=this.transientProfilesObject.profiles.filter(t=>!this.isProfileAssociatedToWorkspace(t));await Promise.allSettled(e.map(t=>this.removeProfile(t)))}getProfileForWorkspace(e){let t=this.getWorkspace(e);return P.isUri(t)?this.profiles.find(n=>n.workspaces?.some(i=>this.uriIdentityService.extUri.isEqual(i,t))):this.profilesObject.emptyWindows.get(t)??this.transientProfilesObject.emptyWindows.get(t)}getWorkspace(e){return zI(e)?e.uri:jI(e)?e.configPath:e.id}isProfileAssociatedToWorkspace(e){return!!(e.workspaces?.length||[...this.profilesObject.emptyWindows.values()].some(t=>this.uriIdentityService.extUri.isEqual(t.location,e.location))||[...this.transientProfilesObject.emptyWindows.values()].some(t=>this.uriIdentityService.extUri.isEqual(t.location,e.location)))}updateProfiles(e,t,n,i=!1){let s=[...this.profiles,...e],a=this.transientProfilesObject.profiles;this.transientProfilesObject.profiles=[];let l=[];for(let c of s){if(t.some(d=>c.id===d.id)){for(let d of[...this.profilesObject.emptyWindows.keys()])c.id===this.profilesObject.emptyWindows.get(d)?.id&&this.profilesObject.emptyWindows.delete(d);continue}if(!c.isDefault){c=n.find(u=>c.id===u.id)??c;let d=a.find(u=>c.id===u.id);if(c.isTransient)this.transientProfilesObject.profiles.push(c);else if(d){for(let[u,p]of this.transientProfilesObject.emptyWindows.entries())if(c.id===p.id){this.transientProfilesObject.emptyWindows.delete(u),this.profilesObject.emptyWindows.set(u,c);break}}}c.workspaces?.length===0&&(c.workspaces=void 0),l.push(c)}this.updateStoredProfiles(l),i||this.triggerProfilesChanges(e,t,n)}triggerProfilesChanges(e,t,n){this._onDidChangeProfiles.fire({added:e,removed:t,updated:n,all:this.profiles})}updateEmptyWindowAssociation(e,t,n){n=t?.isTransient?!0:n,n?t?this.transientProfilesObject.emptyWindows.set(e,t):this.transientProfilesObject.emptyWindows.delete(e):(this.transientProfilesObject.emptyWindows.delete(e),t?this.profilesObject.emptyWindows.set(e,t):this.profilesObject.emptyWindows.delete(e))}updateStoredProfiles(e){let t=[],n={},i={};for(let s of e)if(!s.isTransient&&(s.isDefault||t.push({location:s.location,name:s.name,icon:s.icon,useDefaultFlags:s.useDefaultFlags}),s.workspaces))for(let a of s.workspaces)n[a.toString()]=s.id;for(let[s,a]of this.profilesObject.emptyWindows.entries())i[s.toString()]=a.id;this.saveStoredProfileAssociations({workspaces:n,emptyWindows:i}),this.saveStoredProfiles(t),this._profilesObject=void 0}getStoredProfiles(){return[]}saveStoredProfiles(e){throw new Error("not implemented")}getStoredProfileAssociations(){return{}}saveStoredProfileAssociations(e){throw new Error("not implemented")}getDefaultProfileExtensionsLocation(){}};Ku=b([g(0,X),g(1,W),g(2,te),g(3,V)],Ku);var LP="__$__isNewStorageMarker",Hu="__$__targetStorageMarker",K=L("storageService");function MP(o){let r=o.get(Hu);if(r)try{return JSON.parse(r)}catch{}return Object.create(null)}var Vs=class o extends T{constructor(e={flushInterval:o.DEFAULT_FLUSH_INTERVAL}){super();this._onDidChangeValue=this._register(new ri);this._onDidChangeTarget=this._register(new ri);this.onDidChangeTarget=this._onDidChangeTarget.event;this._onWillSaveState=this._register(new w);this.onWillSaveState=this._onWillSaveState.event;this.runFlushWhenIdle=this._register(new kt);this._workspaceKeyTargets=void 0;this._profileKeyTargets=void 0;this._applicationKeyTargets=void 0;this.flushWhenIdleScheduler=this._register(new It(()=>this.doFlushWhenIdle(),e.flushInterval))}static{this.DEFAULT_FLUSH_INTERVAL=60*1e3}onDidChangeValue(e,t,n){return k.filter(this._onDidChangeValue.event,i=>i.scope===e&&(t===void 0||i.key===t),n)}doFlushWhenIdle(){this.runFlushWhenIdle.value=Jm(()=>{this.shouldFlushWhenIdle()&&this.flush(),this.flushWhenIdleScheduler.schedule()})}shouldFlushWhenIdle(){return!0}stopFlushWhenIdle(){$t([this.runFlushWhenIdle,this.flushWhenIdleScheduler])}initialize(){return this.initializationPromise||(this.initializationPromise=(async()=>{Tn("code/willInitStorage");try{await this.doInitialize()}finally{Tn("code/didInitStorage")}this.flushWhenIdleScheduler.schedule()})()),this.initializationPromise}emitDidChangeValue(e,t){let{key:n,external:i}=t;if(n===Hu){switch(e){case-1:this._applicationKeyTargets=void 0;break;case 0:this._profileKeyTargets=void 0;break;case 1:this._workspaceKeyTargets=void 0;break}this._onDidChangeTarget.fire({scope:e})}else this._onDidChangeValue.fire({scope:e,key:n,target:this.getKeyTargets(e)[n],external:i})}emitWillSaveState(e){this._onWillSaveState.fire({reason:e})}get(e,t,n){return this.getStorage(t)?.get(e,n)}getBoolean(e,t,n){return this.getStorage(t)?.getBoolean(e,n)}getNumber(e,t,n){return this.getStorage(t)?.getNumber(e,n)}getObject(e,t,n){return this.getStorage(t)?.getObject(e,n)}storeAll(e,t){this.withPausedEmitters(()=>{for(let n of e)this.store(n.key,n.value,n.scope,n.target,t)})}store(e,t,n,i,s=!1){if(ft(t)){this.remove(e,n,s);return}this.withPausedEmitters(()=>{this.updateKeyTarget(e,n,i),this.getStorage(n)?.set(e,t,s)})}remove(e,t,n=!1){this.withPausedEmitters(()=>{this.updateKeyTarget(e,t,void 0),this.getStorage(t)?.delete(e,n)})}withPausedEmitters(e){this._onDidChangeValue.pause(),this._onDidChangeTarget.pause();try{e()}finally{this._onDidChangeValue.resume(),this._onDidChangeTarget.resume()}}keys(e,t){let n=[],i=this.getKeyTargets(e);for(let s of Object.keys(i))i[s]===t&&n.push(s);return n}updateKeyTarget(e,t,n,i=!1){let s=this.getKeyTargets(t);typeof n=="number"?s[e]!==n&&(s[e]=n,this.getStorage(t)?.set(Hu,JSON.stringify(s),i)):typeof s[e]=="number"&&(delete s[e],this.getStorage(t)?.set(Hu,JSON.stringify(s),i))}get workspaceKeyTargets(){return this._workspaceKeyTargets||(this._workspaceKeyTargets=this.loadKeyTargets(1)),this._workspaceKeyTargets}get profileKeyTargets(){return this._profileKeyTargets||(this._profileKeyTargets=this.loadKeyTargets(0)),this._profileKeyTargets}get applicationKeyTargets(){return this._applicationKeyTargets||(this._applicationKeyTargets=this.loadKeyTargets(-1)),this._applicationKeyTargets}getKeyTargets(e){switch(e){case-1:return this.applicationKeyTargets;case 0:return this.profileKeyTargets;default:return this.workspaceKeyTargets}}loadKeyTargets(e){let t=this.getStorage(e);return t?MP(t):Object.create(null)}isNew(e){return this.getBoolean(LP,e)===!0}async flush(e=0){this._onWillSaveState.fire({reason:e});let t=this.getStorage(-1),n=this.getStorage(0),i=this.getStorage(1);switch(e){case 0:await Ke.settled([t?.whenFlushed()??Promise.resolve(),n?.whenFlushed()??Promise.resolve(),i?.whenFlushed()??Promise.resolve()]);break;case 1:await Ke.settled([t?.flush(0)??Promise.resolve(),n?.flush(0)??Promise.resolve(),i?.flush(0)??Promise.resolve()]);break}}async log(){let e=this.getStorage(-1)?.items??new Map,t=this.getStorage(0)?.items??new Map,n=this.getStorage(1)?.items??new Map;return AP(e,t,n,this.getLogDetails(-1)??"",this.getLogDetails(0)??"",this.getLogDetails(1)??"")}async optimize(e){return await this.flush(),this.getStorage(e)?.optimize()}async switch(e,t){return this.emitWillSaveState(0),ju(e)?this.switchToProfile(e,t):this.switchToWorkspace(e,t)}canSwitchProfile(e,t){return!(e.id===t.id||Ws(t)&&Ws(e))}switchData(e,t,n){this.withPausedEmitters(()=>{let i=new Set;for(let[s,a]of e)i.add(s),t.get(s)!==a&&this.emitDidChangeValue(n,{key:s,external:!0});for(let[s]of t.items)i.has(s)||this.emitDidChangeValue(n,{key:s,external:!0})})}};function Ws(o){return o.isDefault||!!o.useDefaultFlags?.globalState}async function AP(o,r,e,t,n,i){let s=v=>{try{return JSON.parse(v)}catch{return v}},a=new Map,l=new Map;o.forEach((v,y)=>{a.set(y,v),l.set(y,s(v))});let c=new Map,d=new Map;r.forEach((v,y)=>{c.set(y,v),d.set(y,s(v))});let u=new Map,p=new Map;e.forEach((v,y)=>{u.set(y,v),p.set(y,s(v))}),console.group(t!==n?`Storage: Application (path: ${t})`:`Storage: Application & Profile (path: ${t}, default profile)`);let m=[];if(a.forEach((v,y)=>{m.push({key:y,value:v})}),console.table(m),console.groupEnd(),console.log(l),t!==n){console.group(`Storage: Profile (path: ${n}, profile specific)`);let v=[];c.forEach((y,x)=>{v.push({key:x,value:y})}),console.table(v),console.groupEnd(),console.log(d)}console.group(`Storage: Workspace (path: ${i})`);let h=[];u.forEach((v,y)=>{h.push({key:y,value:v})}),console.table(h),console.groupEnd(),console.log(p)}var Ii=class extends T{constructor(e,t){super();this._onDidChangeEnablement=this._register(new w);this.onDidChangeEnablement=this._onDidChangeEnablement.event;this.storageManager=this._register(new Xg(e)),this._register(this.storageManager.onDidChange(n=>this._onDidChangeEnablement.fire({extensions:n,source:"storage"}))),this._register(t.onDidInstallExtensions(n=>n.forEach(({local:i,operation:s})=>{i&&s===4&&this._removeFromDisabledExtensions(i.identifier)})))}async enableExtension(e,t){return this._removeFromDisabledExtensions(e)?(this._onDidChangeEnablement.fire({extensions:[e],source:t}),!0):!1}async disableExtension(e,t){return this._addToDisabledExtensions(e)?(this._onDidChangeEnablement.fire({extensions:[e],source:t}),!0):!1}getDisabledExtensions(){return this._getExtensions(nc)}async getDisabledExtensionsAsync(){return this.getDisabledExtensions()}_addToDisabledExtensions(e){let t=this.getDisabledExtensions();return t.every(n=>!j(n,e))?(t.push(e),this._setDisabledExtensions(t),!0):!1}_removeFromDisabledExtensions(e){let t=this.getDisabledExtensions();for(let n=0;n<t.length;n++){let i=t[n];if(j(i,e))return t.splice(n,1),this._setDisabledExtensions(t),!0}return!1}_setDisabledExtensions(e){this._setExtensions(nc,e)}_getExtensions(e){return this.storageManager.get(e,0)}_setExtensions(e,t){this.storageManager.set(e,t,0)}};Ii=b([g(0,K),g(1,rr)],Ii);var Xg=class extends T{constructor(e){super();this.storageService=e;this.storage=Object.create(null);this._onDidChange=this._register(new w);this.onDidChange=this._onDidChange.event;this._register(e.onDidChangeValue(0,void 0,this._store)(t=>this.onDidStorageChange(t)))}get(e,t){let n;return t===0?(ft(this.storage[e])&&(this.storage[e]=this._get(e,t)),n=this.storage[e]):n=this._get(e,t),JSON.parse(n)}set(e,t,n){let i=JSON.stringify(t.map(({id:a,uuid:l})=>({id:a,uuid:l})));this._get(e,n)!==i&&(n===0&&(t.length?this.storage[e]=i:delete this.storage[e]),this._set(e,t.length?i:void 0,n))}onDidStorageChange(e){if(!ft(this.storage[e.key])&&this._get(e.key,e.scope)!==this.storage[e.key]){let n=this.get(e.key,e.scope);delete this.storage[e.key];let i=this.get(e.key,e.scope),s=n.filter(l=>!i.some(c=>j(l,c))),a=i.filter(l=>!n.some(c=>j(c,l)));(s.length||a.length)&&this._onDidChange.fire([...s,...a])}}_get(e,t){return this.storageService.get(e,t,"[]")}_set(e,t,n){t?this.storageService.store(e,t,n,1):this.storageService.remove(e,n)}};var Qu={},we={exports:Qu};(function(o,r){if(typeof Qu=="object"&&typeof we=="object")we.exports=r();else if(typeof define=="function"&&define.amd)define([],r);else{var e=r();for(var t in e)(typeof Qu=="object"?Qu:o)[t]=e[t]}})(typeof self<"u"?self:void 0,(function(){return(function(o){var r={};function e(t){if(r[t])return r[t].exports;var n=r[t]={i:t,l:!1,exports:{}};return o[t].call(n.exports,n,n.exports,e),n.l=!0,n.exports}return e.m=o,e.c=r,e.d=function(t,n,i){e.o(t,n)||Object.defineProperty(t,n,{enumerable:!0,get:i})},e.r=function(t){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},e.t=function(t,n){if(1&n&&(t=e(t)),8&n||4&n&&typeof t=="object"&&t&&t.__esModule)return t;var i=Object.create(null);if(e.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&n&&typeof t!="string")for(var s in t)e.d(i,s,function(a){return t[a]}.bind(null,s));return i},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},e.p="",e(e.s=0)})([function(o,r,e){(function(t){var n;r=o.exports=Ne,n=typeof t=="object"&&t.env&&t.env.NODE_DEBUG&&/\bsemver\b/i.test(t.env.NODE_DEBUG)?function(){var I=Array.prototype.slice.call(arguments,0);I.unshift("SEMVER"),console.log.apply(console,I)}:function(){},r.SEMVER_SPEC_VERSION="2.0.0";var i=256,s=Number.MAX_SAFE_INTEGER||9007199254740991,a=r.re=[],l=r.src=[],c=0,d=c++;l[d]="0|[1-9]\\d*";var u=c++;l[u]="[0-9]+";var p=c++;l[p]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var m=c++;l[m]="("+l[d]+")\\.("+l[d]+")\\.("+l[d]+")";var h=c++;l[h]="("+l[u]+")\\.("+l[u]+")\\.("+l[u]+")";var v=c++;l[v]="(?:"+l[d]+"|"+l[p]+")";var y=c++;l[y]="(?:"+l[u]+"|"+l[p]+")";var x=c++;l[x]="(?:-("+l[v]+"(?:\\."+l[v]+")*))";var E=c++;l[E]="(?:-?("+l[y]+"(?:\\."+l[y]+")*))";var R=c++;l[R]="[0-9A-Za-z-]+";var F=c++;l[F]="(?:\\+("+l[R]+"(?:\\."+l[R]+")*))";var H=c++,qe="v?"+l[m]+l[x]+"?"+l[F]+"?";l[H]="^"+qe+"$";var B="[v=\\s]*"+l[h]+l[E]+"?"+l[F]+"?",C=c++;l[C]="^"+B+"$";var A=c++;l[A]="((?:<|>)?=?)";var ae=c++;l[ae]=l[u]+"|x|X|\\*";var J=c++;l[J]=l[d]+"|x|X|\\*";var ge=c++;l[ge]="[v=\\s]*("+l[J]+")(?:\\.("+l[J]+")(?:\\.("+l[J]+")(?:"+l[x]+")?"+l[F]+"?)?)?";var Xe=c++;l[Xe]="[v=\\s]*("+l[ae]+")(?:\\.("+l[ae]+")(?:\\.("+l[ae]+")(?:"+l[E]+")?"+l[F]+"?)?)?";var Ze=c++;l[Ze]="^"+l[A]+"\\s*"+l[ge]+"$";var N=c++;l[N]="^"+l[A]+"\\s*"+l[Xe]+"$";var O=c++;l[O]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var q=c++;l[q]="(?:~>?)";var z=c++;l[z]="(\\s*)"+l[q]+"\\s+",a[z]=new RegExp(l[z],"g");var Z=c++;l[Z]="^"+l[q]+l[ge]+"$";var pe=c++;l[pe]="^"+l[q]+l[Xe]+"$";var Ee=c++;l[Ee]="(?:\\^)";var ot=c++;l[ot]="(\\s*)"+l[Ee]+"\\s+",a[ot]=new RegExp(l[ot],"g");var Ye=c++;l[Ye]="^"+l[Ee]+l[ge]+"$";var Kt=c++;l[Kt]="^"+l[Ee]+l[Xe]+"$";var Yt=c++;l[Yt]="^"+l[A]+"\\s*("+B+")$|^$";var Rr=c++;l[Rr]="^"+l[A]+"\\s*("+qe+")$|^$";var sr=c++;l[sr]="(\\s*)"+l[A]+"\\s*("+B+"|"+l[ge]+")",a[sr]=new RegExp(l[sr],"g");var mn=c++;l[mn]="^\\s*("+l[ge]+")\\s+-\\s+("+l[ge]+")\\s*$";var dl=c++;l[dl]="^\\s*("+l[Xe]+")\\s+-\\s+("+l[Xe]+")\\s*$";var ul=c++;l[ul]="(<|>)?=?\\s*\\*";for(var le=0;le<35;le++)n(le,l[le]),a[le]||(a[le]=new RegExp(l[le]));function $i(I,D){if(I instanceof Ne)return I;if(typeof I!="string"||I.length>i||!(D?a[C]:a[H]).test(I))return null;try{return new Ne(I,D)}catch{return null}}function Ne(I,D){if(I instanceof Ne){if(I.loose===D)return I;I=I.version}else if(typeof I!="string")throw new TypeError("Invalid Version: "+I);if(I.length>i)throw new TypeError("version is longer than "+i+" characters");if(!(this instanceof Ne))return new Ne(I,D);n("SemVer",I,D),this.loose=D;var _=I.trim().match(D?a[C]:a[H]);if(!_)throw new TypeError("Invalid Version: "+I);if(this.raw=I,this.major=+_[1],this.minor=+_[2],this.patch=+_[3],this.major>s||this.major<0)throw new TypeError("Invalid major version");if(this.minor>s||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>s||this.patch<0)throw new TypeError("Invalid patch version");_[4]?this.prerelease=_[4].split(".").map((function(ie){if(/^[0-9]+$/.test(ie)){var ve=+ie;if(ve>=0&&ve<s)return ve}return ie})):this.prerelease=[],this.build=_[5]?_[5].split("."):[],this.format()}r.parse=$i,r.valid=function(I,D){var _=$i(I,D);return _?_.version:null},r.clean=function(I,D){var _=$i(I.trim().replace(/^[=v]+/,""),D);return _?_.version:null},r.SemVer=Ne,Ne.prototype.format=function(){return this.version=this.major+"."+this.minor+"."+this.patch,this.prerelease.length&&(this.version+="-"+this.prerelease.join(".")),this.version},Ne.prototype.toString=function(){return this.version},Ne.prototype.compare=function(I){return n("SemVer.compare",this.version,this.loose,I),I instanceof Ne||(I=new Ne(I,this.loose)),this.compareMain(I)||this.comparePre(I)},Ne.prototype.compareMain=function(I){return I instanceof Ne||(I=new Ne(I,this.loose)),Wo(this.major,I.major)||Wo(this.minor,I.minor)||Wo(this.patch,I.patch)},Ne.prototype.comparePre=function(I){if(I instanceof Ne||(I=new Ne(I,this.loose)),this.prerelease.length&&!I.prerelease.length)return-1;if(!this.prerelease.length&&I.prerelease.length)return 1;if(!this.prerelease.length&&!I.prerelease.length)return 0;var D=0;do{var _=this.prerelease[D],ie=I.prerelease[D];if(n("prerelease compare",D,_,ie),_===void 0&&ie===void 0)return 0;if(ie===void 0)return 1;if(_===void 0)return-1;if(_!==ie)return Wo(_,ie)}while(++D)},Ne.prototype.inc=function(I,D){switch(I){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",D);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",D);break;case"prepatch":this.prerelease.length=0,this.inc("patch",D),this.inc("pre",D);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",D),this.inc("pre",D);break;case"major":this.minor===0&&this.patch===0&&this.prerelease.length!==0||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":this.patch===0&&this.prerelease.length!==0||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":if(this.prerelease.length===0)this.prerelease=[0];else{for(var _=this.prerelease.length;--_>=0;)typeof this.prerelease[_]=="number"&&(this.prerelease[_]++,_=-2);_===-1&&this.prerelease.push(0)}D&&(this.prerelease[0]===D?isNaN(this.prerelease[1])&&(this.prerelease=[D,0]):this.prerelease=[D,0]);break;default:throw new Error("invalid increment argument: "+I)}return this.format(),this.raw=this.version,this},r.inc=function(I,D,_,ie){typeof _=="string"&&(ie=_,_=void 0);try{return new Ne(I,_).inc(D,ie).version}catch{return null}},r.diff=function(I,D){if(cm(I,D))return null;var _=$i(I),ie=$i(D);if(_.prerelease.length||ie.prerelease.length){for(var ve in _)if((ve==="major"||ve==="minor"||ve==="patch")&&_[ve]!==ie[ve])return"pre"+ve;return"prerelease"}for(var ve in _)if((ve==="major"||ve==="minor"||ve==="patch")&&_[ve]!==ie[ve])return ve},r.compareIdentifiers=Wo;var fy=/^[0-9]+$/;function Wo(I,D){var _=fy.test(I),ie=fy.test(D);return _&&ie&&(I=+I,D=+D),_&&!ie?-1:ie&&!_?1:I<D?-1:I>D?1:0}function kn(I,D,_){return new Ne(I,_).compare(new Ne(D,_))}function Hc(I,D,_){return kn(I,D,_)>0}function Jc(I,D,_){return kn(I,D,_)<0}function cm(I,D,_){return kn(I,D,_)===0}function my(I,D,_){return kn(I,D,_)!==0}function dm(I,D,_){return kn(I,D,_)>=0}function um(I,D,_){return kn(I,D,_)<=0}function Qc(I,D,_,ie){var ve;switch(D){case"===":typeof I=="object"&&(I=I.version),typeof _=="object"&&(_=_.version),ve=I===_;break;case"!==":typeof I=="object"&&(I=I.version),typeof _=="object"&&(_=_.version),ve=I!==_;break;case"":case"=":case"==":ve=cm(I,_,ie);break;case"!=":ve=my(I,_,ie);break;case">":ve=Hc(I,_,ie);break;case">=":ve=dm(I,_,ie);break;case"<":ve=Jc(I,_,ie);break;case"<=":ve=um(I,_,ie);break;default:throw new TypeError("Invalid operator: "+D)}return ve}function Br(I,D){if(I instanceof Br){if(I.loose===D)return I;I=I.value}if(!(this instanceof Br))return new Br(I,D);n("comparator",I,D),this.loose=D,this.parse(I),this.semver===pl?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}r.rcompareIdentifiers=function(I,D){return Wo(D,I)},r.major=function(I,D){return new Ne(I,D).major},r.minor=function(I,D){return new Ne(I,D).minor},r.patch=function(I,D){return new Ne(I,D).patch},r.compare=kn,r.compareLoose=function(I,D){return kn(I,D,!0)},r.rcompare=function(I,D,_){return kn(D,I,_)},r.sort=function(I,D){return I.sort((function(_,ie){return r.compare(_,ie,D)}))},r.rsort=function(I,D){return I.sort((function(_,ie){return r.rcompare(_,ie,D)}))},r.gt=Hc,r.lt=Jc,r.eq=cm,r.neq=my,r.gte=dm,r.lte=um,r.cmp=Qc,r.Comparator=Br;var pl={};function vt(I,D){if(I instanceof vt)return I.loose===D?I:new vt(I.raw,D);if(I instanceof Br)return new vt(I.value,D);if(!(this instanceof vt))return new vt(I,D);if(this.loose=D,this.raw=I,this.set=I.split(/\s*\|\|\s*/).map((function(_){return this.parseRange(_.trim())}),this).filter((function(_){return _.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+I);this.format()}function ar(I){return!I||I.toLowerCase()==="x"||I==="*"}function H1(I,D,_,ie,ve,Wt,Ve,gr,Et,Zt,gn,wt,jt){return((D=ar(_)?"":ar(ie)?">="+_+".0.0":ar(ve)?">="+_+"."+ie+".0":">="+D)+" "+(gr=ar(Et)?"":ar(Zt)?"<"+(+Et+1)+".0.0":ar(gn)?"<"+Et+"."+(+Zt+1)+".0":wt?"<="+Et+"."+Zt+"."+gn+"-"+wt:"<="+gr)).trim()}function J1(I,D){for(var _=0;_<I.length;_++)if(!I[_].test(D))return!1;if(D.prerelease.length){for(_=0;_<I.length;_++)if(n(I[_].semver),I[_].semver!==pl&&I[_].semver.prerelease.length>0){var ie=I[_].semver;if(ie.major===D.major&&ie.minor===D.minor&&ie.patch===D.patch)return!0}return!1}return!0}function Xc(I,D,_){try{D=new vt(D,_)}catch{return!1}return D.test(I)}function pm(I,D,_,ie){var ve,Wt,Ve,gr,Et;switch(I=new Ne(I,ie),D=new vt(D,ie),_){case">":ve=Hc,Wt=um,Ve=Jc,gr=">",Et=">=";break;case"<":ve=Jc,Wt=dm,Ve=Hc,gr="<",Et="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Xc(I,D,ie))return!1;for(var Zt=0;Zt<D.set.length;++Zt){var gn=D.set[Zt],wt=null,jt=null;if(gn.forEach((function(hr){hr.semver===pl&&(hr=new Br(">=0.0.0")),wt=wt||hr,jt=jt||hr,ve(hr.semver,wt.semver,ie)?wt=hr:Ve(hr.semver,jt.semver,ie)&&(jt=hr)})),wt.operator===gr||wt.operator===Et||(!jt.operator||jt.operator===gr)&&Wt(I,jt.semver)||jt.operator===Et&&Ve(I,jt.semver))return!1}return!0}Br.prototype.parse=function(I){var D=this.loose?a[Yt]:a[Rr],_=I.match(D);if(!_)throw new TypeError("Invalid comparator: "+I);this.operator=_[1],this.operator==="="&&(this.operator=""),_[2]?this.semver=new Ne(_[2],this.loose):this.semver=pl},Br.prototype.toString=function(){return this.value},Br.prototype.test=function(I){return n("Comparator.test",I,this.loose),this.semver===pl||(typeof I=="string"&&(I=new Ne(I,this.loose)),Qc(I,this.operator,this.semver,this.loose))},Br.prototype.intersects=function(I,D){if(!(I instanceof Br))throw new TypeError("a Comparator is required");var _;if(this.operator==="")return _=new vt(I.value,D),Xc(this.value,_,D);if(I.operator==="")return _=new vt(this.value,D),Xc(I.semver,_,D);var ie=!(this.operator!==">="&&this.operator!==">"||I.operator!==">="&&I.operator!==">"),ve=!(this.operator!=="<="&&this.operator!=="<"||I.operator!=="<="&&I.operator!=="<"),Wt=this.semver.version===I.semver.version,Ve=!(this.operator!==">="&&this.operator!=="<="||I.operator!==">="&&I.operator!=="<="),gr=Qc(this.semver,"<",I.semver,D)&&(this.operator===">="||this.operator===">")&&(I.operator==="<="||I.operator==="<"),Et=Qc(this.semver,">",I.semver,D)&&(this.operator==="<="||this.operator==="<")&&(I.operator===">="||I.operator===">");return ie||ve||Wt&&Ve||gr||Et},r.Range=vt,vt.prototype.format=function(){return this.range=this.set.map((function(I){return I.join(" ").trim()})).join("||").trim(),this.range},vt.prototype.toString=function(){return this.range},vt.prototype.parseRange=function(I){var D=this.loose;I=I.trim(),n("range",I,D);var _=D?a[dl]:a[mn];I=I.replace(_,H1),n("hyphen replace",I),I=I.replace(a[sr],"$1$2$3"),n("comparator trim",I,a[sr]),I=(I=(I=I.replace(a[z],"$1~")).replace(a[ot],"$1^")).split(/\s+/).join(" ");var ie=D?a[Yt]:a[Rr],ve=I.split(" ").map((function(Wt){return(function(Ve,gr){return n("comp",Ve),Ve=(function(Et,Zt){return Et.trim().split(/\s+/).map((function(gn){return(function(wt,jt){n("caret",wt,jt);var hr=jt?a[Kt]:a[Ye];return wt.replace(hr,(function(Zr,Ie,Pe,tt,pt){var Ht;return n("caret",wt,Zr,Ie,Pe,tt,pt),ar(Ie)?Ht="":ar(Pe)?Ht=">="+Ie+".0.0 <"+(+Ie+1)+".0.0":ar(tt)?Ht=Ie==="0"?">="+Ie+"."+Pe+".0 <"+Ie+"."+(+Pe+1)+".0":">="+Ie+"."+Pe+".0 <"+(+Ie+1)+".0.0":pt?(n("replaceCaret pr",pt),pt.charAt(0)!=="-"&&(pt="-"+pt),Ht=Ie==="0"?Pe==="0"?">="+Ie+"."+Pe+"."+tt+pt+" <"+Ie+"."+Pe+"."+(+tt+1):">="+Ie+"."+Pe+"."+tt+pt+" <"+Ie+"."+(+Pe+1)+".0":">="+Ie+"."+Pe+"."+tt+pt+" <"+(+Ie+1)+".0.0"):(n("no pr"),Ht=Ie==="0"?Pe==="0"?">="+Ie+"."+Pe+"."+tt+" <"+Ie+"."+Pe+"."+(+tt+1):">="+Ie+"."+Pe+"."+tt+" <"+Ie+"."+(+Pe+1)+".0":">="+Ie+"."+Pe+"."+tt+" <"+(+Ie+1)+".0.0"),n("caret return",Ht),Ht}))})(gn,Zt)})).join(" ")})(Ve,gr),n("caret",Ve),Ve=(function(Et,Zt){return Et.trim().split(/\s+/).map((function(gn){return(function(wt,jt){var hr=jt?a[pe]:a[Z];return wt.replace(hr,(function(Zr,Ie,Pe,tt,pt){var Ht;return n("tilde",wt,Zr,Ie,Pe,tt,pt),ar(Ie)?Ht="":ar(Pe)?Ht=">="+Ie+".0.0 <"+(+Ie+1)+".0.0":ar(tt)?Ht=">="+Ie+"."+Pe+".0 <"+Ie+"."+(+Pe+1)+".0":pt?(n("replaceTilde pr",pt),pt.charAt(0)!=="-"&&(pt="-"+pt),Ht=">="+Ie+"."+Pe+"."+tt+pt+" <"+Ie+"."+(+Pe+1)+".0"):Ht=">="+Ie+"."+Pe+"."+tt+" <"+Ie+"."+(+Pe+1)+".0",n("tilde return",Ht),Ht}))})(gn,Zt)})).join(" ")})(Ve,gr),n("tildes",Ve),Ve=(function(Et,Zt){return n("replaceXRanges",Et,Zt),Et.split(/\s+/).map((function(gn){return(function(wt,jt){wt=wt.trim();var hr=jt?a[N]:a[Ze];return wt.replace(hr,(function(Zr,Ie,Pe,tt,pt,Ht){n("xRange",wt,Zr,Ie,Pe,tt,pt,Ht);var gy=ar(Pe),fl=gy||ar(tt),ml=fl||ar(pt);return Ie==="="&&ml&&(Ie=""),gy?Zr=Ie===">"||Ie==="<"?"<0.0.0":"*":Ie&&ml?(fl&&(tt=0),ml&&(pt=0),Ie===">"?(Ie=">=",fl?(Pe=+Pe+1,tt=0,pt=0):ml&&(tt=+tt+1,pt=0)):Ie==="<="&&(Ie="<",fl?Pe=+Pe+1:tt=+tt+1),Zr=Ie+Pe+"."+tt+"."+pt):fl?Zr=">="+Pe+".0.0 <"+(+Pe+1)+".0.0":ml&&(Zr=">="+Pe+"."+tt+".0 <"+Pe+"."+(+tt+1)+".0"),n("xRange return",Zr),Zr}))})(gn,Zt)})).join(" ")})(Ve,gr),n("xrange",Ve),Ve=(function(Et,Zt){return n("replaceStars",Et,Zt),Et.trim().replace(a[ul],"")})(Ve,gr),n("stars",Ve),Ve})(Wt,D)})).join(" ").split(/\s+/);return this.loose&&(ve=ve.filter((function(Wt){return!!Wt.match(ie)}))),ve=ve.map((function(Wt){return new Br(Wt,D)}))},vt.prototype.intersects=function(I,D){if(!(I instanceof vt))throw new TypeError("a Range is required");return this.set.some((function(_){return _.every((function(ie){return I.set.some((function(ve){return ve.every((function(Wt){return ie.intersects(Wt,D)}))}))}))}))},r.toComparators=function(I,D){return new vt(I,D).set.map((function(_){return _.map((function(ie){return ie.value})).join(" ").trim().split(" ")}))},vt.prototype.test=function(I){if(!I)return!1;typeof I=="string"&&(I=new Ne(I,this.loose));for(var D=0;D<this.set.length;D++)if(J1(this.set[D],I))return!0;return!1},r.satisfies=Xc,r.maxSatisfying=function(I,D,_){var ie=null,ve=null;try{var Wt=new vt(D,_)}catch{return null}return I.forEach((function(Ve){Wt.test(Ve)&&(ie&&ve.compare(Ve)!==-1||(ve=new Ne(ie=Ve,_)))})),ie},r.minSatisfying=function(I,D,_){var ie=null,ve=null;try{var Wt=new vt(D,_)}catch{return null}return I.forEach((function(Ve){Wt.test(Ve)&&(ie&&ve.compare(Ve)!==1||(ve=new Ne(ie=Ve,_)))})),ie},r.validRange=function(I,D){try{return new vt(I,D).range||"*"}catch{return null}},r.ltr=function(I,D,_){return pm(I,D,"<",_)},r.gtr=function(I,D,_){return pm(I,D,">",_)},r.outside=pm,r.prerelease=function(I,D){var _=$i(I,D);return _&&_.prerelease.length?_.prerelease:null},r.intersects=function(I,D,_){return I=new vt(I,_),D=new vt(D,_),I.intersects(D)},r.coerce=function(I){if(I instanceof Ne)return I;if(typeof I!="string")return null;var D=I.match(a[O]);return D==null?null:$i((D[1]||"0")+"."+(D[2]||"0")+"."+(D[3]||"0"))}}).call(this,e(1))},function(o,r){var e,t,n=o.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(y){if(e===setTimeout)return setTimeout(y,0);if((e===i||!e)&&setTimeout)return e=setTimeout,setTimeout(y,0);try{return e(y,0)}catch{try{return e.call(null,y,0)}catch{return e.call(this,y,0)}}}(function(){try{e=typeof setTimeout=="function"?setTimeout:i}catch{e=i}try{t=typeof clearTimeout=="function"?clearTimeout:s}catch{t=s}})();var l,c=[],d=!1,u=-1;function p(){d&&l&&(d=!1,l.length?c=l.concat(c):u=-1,c.length&&m())}function m(){if(!d){var y=a(p);d=!0;for(var x=c.length;x;){for(l=c,c=[];++u<x;)l&&l[u].run();u=-1,x=c.length}l=null,d=!1,(function(E){if(t===clearTimeout)return clearTimeout(E);if((t===s||!t)&&clearTimeout)return t=clearTimeout,clearTimeout(E);try{t(E)}catch{try{return t.call(null,E)}catch{return t.call(this,E)}}})(y)}}function h(y,x){this.fun=y,this.array=x}function v(){}n.nextTick=function(y){var x=new Array(arguments.length-1);if(arguments.length>1)for(var E=1;E<arguments.length;E++)x[E-1]=arguments[E];c.push(new h(y,x)),c.length!==1||d||a(m)},h.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=v,n.addListener=v,n.once=v,n.off=v,n.removeListener=v,n.removeAllListeners=v,n.emit=v,n.prependListener=v,n.prependOnceListener=v,n.listeners=function(y){return[]},n.binding=function(y){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(y){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}}])}));var jF=we.exports.SEMVER_SPEC_VERSION,HF=we.exports.parse,Pb=we.exports.valid,JF=we.exports.coerce,QF=we.exports.clean,XF=we.exports.inc,YF=we.exports.major,ZF=we.exports.minor,eO=we.exports.patch,tO=we.exports.prerelease,Hn=we.exports.gt,rO=we.exports.gte,nO=we.exports.lt,Rb=we.exports.lte,Tb=we.exports.eq,iO=we.exports.neq,oO=we.exports.cmp,sO=we.exports.compare,Xu=we.exports.rcompare,aO=we.exports.compareIdentifiers,lO=we.exports.rcompareIdentifiers,cO=we.exports.compareBuild,dO=we.exports.sort,uO=we.exports.rsort,pO=we.exports.diff,fO=we.exports.validRange,Cb=we.exports.satisfies,mO=we.exports.maxSatisfying,gO=we.exports.minSatisfying,hO=we.exports.minVersion,vO=we.exports.gtr,yO=we.exports.ltr,SO=we.exports.outside,IO=we.exports.intersects,bO=we.exports.SemVer,xO=we.exports.Comparator,EO=we.exports.Range;var Yg="Offline";function eh(o){return o instanceof Zg?!0:o instanceof Error&&o.name===Yg&&o.message===Yg}var Zg=class extends Error{constructor(){super(Yg),this.name=this.message}};var Yu=(n=>(n[n.Ignore=0]="Ignore",n[n.Info=1]="Info",n[n.Warning=2]="Warning",n[n.Error=3]="Error",n))(Yu||{});(a=>{let o="error",r="warning",e="warn",t="info",n="ignore";function i(l){return l?yr(o,l)?3:yr(r,l)||yr(e,l)?2:yr(t,l)?1:0:0}a.fromValue=i;function s(l){switch(l){case 3:return o;case 2:return r;case 1:return t;default:return n}}a.toString=s})(Yu||={});var Dt=Yu;var FP={activeComment:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.activeComment.d.ts"},agentSessionsWorkspace:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.agentSessionsWorkspace.d.ts"},aiRelatedInformation:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.aiRelatedInformation.d.ts"},aiSettingsSearch:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.aiSettingsSearch.d.ts"},aiTextSearchProvider:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.aiTextSearchProvider.d.ts",version:2},authIssuers:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authIssuers.d.ts"},authLearnMore:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authLearnMore.d.ts"},authProviderSpecific:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authProviderSpecific.d.ts"},authSession:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authSession.d.ts"},authenticationChallenges:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authenticationChallenges.d.ts"},canonicalUriProvider:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.canonicalUriProvider.d.ts"},chatContextProvider:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatContextProvider.d.ts"},chatDebug:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatDebug.d.ts",version:2},chatHooks:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatHooks.d.ts",version:6},chatOutputRenderer:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatOutputRenderer.d.ts"},chatParticipantAdditions:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatParticipantAdditions.d.ts",version:3},chatParticipantPrivate:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatParticipantPrivate.d.ts",version:14},chatPromptFiles:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatPromptFiles.d.ts",version:1},chatProvider:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatProvider.d.ts",version:4},chatReferenceBinaryData:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatReferenceBinaryData.d.ts"},chatReferenceDiagnostic:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatReferenceDiagnostic.d.ts"},chatSessionsProvider:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatSessionsProvider.d.ts",version:3},chatStatusItem:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatStatusItem.d.ts"},chatTab:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatTab.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"},contribChatEditorInlineGutterMenu:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribChatEditorInlineGutterMenu.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"},contribLanguageModelToolSets:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribLanguageModelToolSets.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"},contribSourceControlArtifactGroupMenu:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlArtifactGroupMenu.d.ts"},contribSourceControlArtifactMenu:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribSourceControlArtifactMenu.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"},css:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.css.d.ts"},customEditorMove:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.customEditorMove.d.ts"},dataChannels:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.dataChannels.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:4},devDeviceId:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.devDeviceId.d.ts"},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"},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"},envIsConnectionMetered:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.envIsConnectionMetered.d.ts"},environmentPower:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.environmentPower.d.ts"},extensionAffinity:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.extensionAffinity.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"},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"},inlineCompletionsAdditions:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.inlineCompletionsAdditions.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"},languageModelCapabilities:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageModelCapabilities.d.ts"},languageModelProxy:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageModelProxy.d.ts"},languageModelSystem:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageModelSystem.d.ts"},languageModelThinkingPart:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageModelThinkingPart.d.ts",version:1},languageModelToolResultAudience:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageModelToolResultAudience.d.ts"},languageModelToolSupportsModel:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.languageModelToolSupportsModel.d.ts",version:1},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"},markdownAlertSyntax:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.markdownAlertSyntax.d.ts"},mcpServerDefinitions:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.mcpServerDefinitions.d.ts"},mcpToolDefinitions:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.mcpToolDefinitions.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"},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"},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"},remoteCodingAgents:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.remoteCodingAgents.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"},scmArtifactProvider:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmArtifactProvider.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"},scmProviderOptions:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmProviderOptions.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"},speech:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.speech.d.ts"},statusBarItemTooltip:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.statusBarItemTooltip.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"},taskExecutionTerminal:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.taskExecutionTerminal.d.ts"},taskPresentationGroup:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.taskPresentationGroup.d.ts"},taskProblemMatcherStatus:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.taskProblemMatcherStatus.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"},terminalShellEnv:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalShellEnv.d.ts"},terminalTitle:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalTitle.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"},textDocumentChangeReason:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textDocumentChangeReason.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"},toolProgress:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.toolProgress.d.ts"},treeItemMarkdownLabel:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeItemMarkdownLabel.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"},windsurfAcp:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfAcp.d.ts"},windsurfAnnotations:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfAnnotations.d.ts"},windsurfAudio:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfAudio.d.ts"},windsurfAuth:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfAuth.d.ts"},windsurfCascade:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfCascade.d.ts"},windsurfCommandPopup:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfCommandPopup.d.ts"},windsurfDevContainers:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfDevContainers.d.ts"},windsurfDiffZone:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfDiffZone.d.ts"},windsurfEditorCommandPopup:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfEditorCommandPopup.d.ts"},windsurfEditorNudge:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfEditorNudge.d.ts"},windsurfExtensionManager:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfExtensionManager.d.ts"},windsurfExtensionMetadata:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfExtensionMetadata.d.ts"},windsurfFiles:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfFiles.d.ts"},windsurfGenerateCommitMessageButton:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfGenerateCommitMessageButton.d.ts"},windsurfInlineCompletions:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfInlineCompletions.d.ts"},windsurfLanguageServer:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfLanguageServer.d.ts"},windsurfMarkers:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfMarkers.d.ts"},windsurfMcp:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfMcp.d.ts"},windsurfProductEducation:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfProductEducation.d.ts"},windsurfSettings:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfSettings.d.ts"},windsurfSideHint:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfSideHint.d.ts"},windsurfStatusBar:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfStatusBar.d.ts"},windsurfTabToJump:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfTabToJump.d.ts"},windsurfTerminalCommandPopup:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfTerminalCommandPopup.d.ts"},windsurfUndoRedo:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.windsurfUndoRedo.d.ts"},workspaceTrust:{proposal:"https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.workspaceTrust.d.ts"}},Db=Object.freeze(FP);var _b=/^(\^|>=)?((\d+)|x)\.((\d+)|x)\.((\d+)|x)(\-.*)?$/,OP=/^-(\d{4})(\d{2})(\d{2})(\d{2})?(\d{2})?$/;function NP(o){return o=o.trim(),o==="*"||_b.test(o)}function rh(o){if(!NP(o))return null;if(o=o.trim(),o==="*")return{hasCaret:!1,hasGreaterEquals:!1,majorBase:0,majorMustEqual:!1,minorBase:0,minorMustEqual:!1,patchBase:0,patchMustEqual:!1,preRelease:null};let r=o.match(_b);return r?{hasCaret:r[1]==="^",hasGreaterEquals:r[1]===">=",majorBase:r[2]==="x"?0:parseInt(r[2],10),majorMustEqual:r[2]!=="x",minorBase:r[4]==="x"?0:parseInt(r[4],10),minorMustEqual:r[4]!=="x",patchBase:r[6]==="x"?0:parseInt(r[6],10),patchMustEqual:r[6]!=="x",preRelease:r[8]||null}:null}function nh(o){if(!o)return null;let r=o.majorBase,e=o.majorMustEqual,t=o.minorBase,n=o.minorMustEqual,i=o.patchBase,s=o.patchMustEqual;o.hasCaret&&(r===0||(n=!1),s=!1);let a=0;if(o.preRelease){let l=OP.exec(o.preRelease);if(l){let[,c,d,u,p,m]=l;a=Date.UTC(Number(c),Number(d)-1,Number(u),Number(p)||0,Number(m)||0)}}return{majorBase:r,majorMustEqual:e,minorBase:t,minorMustEqual:n,patchBase:i,patchMustEqual:s,isMinimum:o.hasGreaterEquals,notBefore:a}}function VP(o,r,e){let t;typeof o=="string"?t=nh(rh(o)):t=o;let n;r instanceof Date?n=r.getTime():typeof r=="string"&&(n=new Date(r).getTime());let i;if(typeof e=="string"?i=nh(rh(e)):i=e,!t||!i)return!1;let s=t.majorBase,a=t.minorBase,l=t.patchBase,c=i.majorBase,d=i.minorBase,u=i.patchBase,p=i.notBefore,m=i.majorMustEqual,h=i.minorMustEqual,v=i.patchMustEqual;return i.isMinimum?s>c?!0:s<c?!1:a>d?!0:a<d||n&&n<p?!1:l>=u:(s===1&&c===0&&(!m||!h||!v)&&(c=1,d=0,u=0,m=!0,h=!1,v=!1),s<c?!1:s>c?!m:a<d?!1:a>d?!h:l<u?!1:l>u?!v:!(n&&n<p))}function kb(o,r,e,t,n,i){let s=[];if(typeof t.publisher<"u"&&typeof t.publisher!="string")return s.push([Dt.Error,S(2049,null)]),s;if(typeof t.name!="string")return s.push([Dt.Error,S(2048,null,"name")]),s;if(typeof t.version!="string")return s.push([Dt.Error,S(2050,null,"version")]),s;if(!t.engines)return s.push([Dt.Error,S(2041,null,"engines")]),s;if(typeof t.engines.vscode!="string")return s.push([Dt.Error,S(2042,null,"engines.vscode")]),s;if(typeof t.extensionDependencies<"u"&&!th(t.extensionDependencies))return s.push([Dt.Error,S(2044,null,"extensionDependencies")]),s;if(typeof t.extensionAffinity<"u"&&!th(t.extensionAffinity))return s.push([Dt.Error,S(2043,null,"extensionAffinity")]),s;if(typeof t.activationEvents<"u"){if(!th(t.activationEvents))return s.push([Dt.Error,S(2037,null,"activationEvents")]),s;if(typeof t.main>"u"&&typeof t.browser>"u")return s.push([Dt.Error,S(2038,null,"activationEvents","main","browser")]),s}if(typeof t.extensionKind<"u"&&typeof t.main>"u"&&s.push([Dt.Warning,S(2045,null,"extensionKind")]),typeof t.main<"u"){if(typeof t.main!="string")return s.push([Dt.Error,S(2046,null,"main")]),s;{let c=$(e,t.main);zm(c,e)||s.push([Dt.Warning,S(2047,null,c.path,e.path)])}}if(typeof t.browser<"u"){if(typeof t.browser!="string")return s.push([Dt.Error,S(2039,null,"browser")]),s;{let c=$(e,t.browser);zm(c,e)||s.push([Dt.Warning,S(2040,null,c.path,e.path)])}}if(!Pb(t.version))return s.push([Dt.Error,S(2051,null)]),s;let a=[];if(!WP(o,r,t,n,a))for(let c of a)s.push([Dt.Error,c]);if(i&&t.enabledApiProposals?.length){let c=[];if(!uc([...t.enabledApiProposals],c))for(let d of c)s.push([Dt.Error,d])}return s}function WP(o,r,e,t,n){return t||typeof e.main>"u"&&typeof e.browser>"u"?!0:Ub(o,r,e.engines.vscode,n)}function Bs(o,r,e){return o==="*"||Ub(r,e,o)}function uc(o,r){if(o.length===0)return!0;let e=Array.isArray(r)?r:void 0,t=(Array.isArray(r)?void 0:r)??Db,n=[],i=_I(o);for(let{proposalName:s,version:a}of i){if(!a)continue;t[s]?.version!==a&&n.push(s)}return n.length?(e&&(n.length===1?e.push(S(2035,null,n[0])):e.push(S(2036,null,n.slice(0,n.length-1).map(s=>`'${s}'`).join(", "),n[n.length-1]))),!1):!0}function Ub(o,r,e,t=[]){let n=nh(rh(e));if(!n)return t.push(S(2055,null,e)),!1;if(n.majorBase===0){if(!n.majorMustEqual||!n.minorMustEqual)return t.push(S(2053,null,e)),!1}else if(!n.majorMustEqual)return t.push(S(2054,null,e)),!1;return VP(o,r,n)?!0:(t.push(S(2052,null,o,e)),!1)}function th(o){if(!Array.isArray(o))return!1;for(let r=0,e=o.length;r<e;r++)if(typeof o[r]!="string")return!1;return!0}async function Hr(o,r,e){let t=e&&e.get("storage.serviceMachineId",-1)||null;if(t)return t;try{let i=(await r.readFile(o.serviceMachineIdResource)).value.toString();t=rb(i)?i:null}catch{t=null}if(!t){t=Le();try{await r.writeFile(o.serviceMachineIdResource,U.fromString(t))}catch{}}return e?.store("storage.serviceMachineId",t,-1,1),t}async function Lb(o,r,e,t,n,i,s){let a={"X-Market-Client-Id":`VSCode ${o}`,"User-Agent":`VSCode ${o} (${r.nameShort})`};if(Vu(r,e)&&Bu(t)===3){let l=await Hr(e,n,i);a["X-Market-User-Id"]=l,a["VSCode-SessionId"]=s.machineId||l}return a}var bi=L("IExtensionGalleryManifestService");function lo(o,r){let[e,t]=r.split("/");for(let n of o.resources){let[i,s]=n.type.split("/");if(i===e){if(!t||s===t)return n.id;break}}}var Zu=ze?"web":mu(In,yd),rp="X-Market-Search-Activity-Id",ih="Activityid",oh="Server",sh="X-Vss-E2eid",Ft={Icon:"Microsoft.VisualStudio.Services.Icons.Default",Details:"Microsoft.VisualStudio.Services.Content.Details",Changelog:"Microsoft.VisualStudio.Services.Content.Changelog",Manifest:"Microsoft.VisualStudio.Code.Manifest",VSIX:"Microsoft.VisualStudio.Services.VSIXPackage",License:"Microsoft.VisualStudio.Services.Content.License",Repository:"Microsoft.VisualStudio.Services.Links.Source",Signature:"Microsoft.VisualStudio.Services.VsixSignature"},ln={Dependency:"Microsoft.VisualStudio.Code.ExtensionDependencies",ExtensionPack:"Microsoft.VisualStudio.Code.ExtensionPack",Engine:"Microsoft.VisualStudio.Code.Engine",PreRelease:"Microsoft.VisualStudio.Code.PreRelease",EnabledApiProposals:"Microsoft.VisualStudio.Code.EnabledApiProposals",LocalizedLanguages:"Microsoft.VisualStudio.Code.LocalizedLanguages",WebExtension:"Microsoft.VisualStudio.Code.WebExtension",SponsorLink:"Microsoft.VisualStudio.Code.SponsorLink",SupportLink:"Microsoft.VisualStudio.Services.Links.Support",ExecutesCode:"Microsoft.VisualStudio.Code.ExecutesCode",Private:"PrivateMarketplace"},KP=10,jP={pageNumber:1,pageSize:KP,sortBy:"NoneOrRelevance",sortOrder:0,flags:[],criteria:[],assetTypes:[]};var $s=class o{constructor(r=jP){this.state=r}get pageNumber(){return this.state.pageNumber}get pageSize(){return this.state.pageSize}get sortBy(){return this.state.sortBy}get sortOrder(){return this.state.sortOrder}get flags(){return this.state.flags}get criteria(){return this.state.criteria}get assetTypes(){return this.state.assetTypes}get source(){return this.state.source}get searchText(){let r=this.state.criteria.filter(e=>e.filterType==="SearchText")[0];return r&&r.value?r.value:""}withPage(r,e=this.state.pageSize){return new o({...this.state,pageNumber:r,pageSize:e})}withFilter(r,...e){let t=[...this.state.criteria,...e.length?e.map(n=>({filterType:r,value:n})):[{filterType:r}]];return new o({...this.state,criteria:t})}withSortBy(r){return new o({...this.state,sortBy:r})}withSortOrder(r){return new o({...this.state,sortOrder:r})}withFlags(...r){return new o({...this.state,flags:dt(r)})}withAssetTypes(...r){return new o({...this.state,assetTypes:r})}withSource(r){return new o({...this.state,source:r})}};function ah(o,r){let e=(o||[]).filter(t=>t.statisticName===r)[0];return e?e.value:0}function HP(o){let r="Microsoft.VisualStudio.Code.Translation.";return o.files.filter(t=>t.assetType.indexOf(r)===0).reduce((t,n)=>{let i=an(o,n.assetType);return i&&t.push([n.assetType.substring(r.length),i]),t},[])}function JP(o){if(o.properties){let r=o.properties.filter(n=>n.key===Ft.Repository),e=new RegExp("((git|ssh|http(s)?)|(git@[\\w.]+))(:(//)?)([\\w.@:/\\-~]+)(.git)(/)?"),t=r.filter(n=>e.test(n.value))[0];return t?{uri:t.value,fallbackUri:t.value}:null}return an(o,Ft.Repository)}function QP(o){return{uri:`${o.fallbackAssetUri}/${Ft.VSIX}?redirect=true${o.targetPlatform?`&targetPlatform=${o.targetPlatform}`:""}`,fallbackUri:`${o.fallbackAssetUri}/${Ft.VSIX}${o.targetPlatform?`?targetPlatform=${o.targetPlatform}`:""}`}}function an(o,r){return o.files.filter(t=>t.assetType===r)[0]?{uri:`${o.assetUri}/${r}${o.targetPlatform?`?targetPlatform=${o.targetPlatform}`:""}`,fallbackUri:`${o.fallbackAssetUri}/${r}${o.targetPlatform?`?targetPlatform=${o.targetPlatform}`:""}`}:null}function Mb(o,r){let e=o.properties?o.properties.filter(n=>n.key===r):[],t=e.length>0&&e[0].value;return t?t.split(",").map(n=>oo(n)):[]}function np(o){let r=o.properties?o.properties.filter(e=>e.key===ln.Engine):[];return r.length>0&&r[0].value||""}function XP(o,r){o.properties=o.properties??[],o.properties.push({key:ln.Engine,value:r})}function zs(o){let r=o.properties?o.properties.filter(e=>e.key===ln.PreRelease):[];return r.length>0&&r[0].value==="true"}function Nb(o,r){return r.extensionProperties?.[o.toLowerCase()]?.hasPrereleaseVersion}function YP(o,r){return r.extensionProperties?.[o.toLowerCase()]?.excludeVersionRange}function ZP(o){let r=o.properties?o.properties.filter(e=>e.key===ln.Private):[];return r.length>0&&r[0].value==="true"}function e0(o){let r=o.properties?o.properties.filter(e=>e.key===ln.ExecutesCode):[];return r.length>0?r[0].value==="true":void 0}function ch(o){let r=o.properties?o.properties.filter(t=>t.key===ln.EnabledApiProposals):[],e=r.length>0&&r[0].value||"";return e?e.split(","):[]}function t0(o){let r=o.properties?o.properties.filter(t=>t.key===ln.LocalizedLanguages):[],e=r.length>0&&r[0].value||"";return e?e.split(","):[]}function r0(o){return o.properties?.find(r=>r.key===ln.SponsorLink)?.value}function n0(o){return o.properties?.find(r=>r.key===ln.SupportLink)?.value}function i0(o){return o.indexOf("preview")!==-1}function co(o){return o.targetPlatform?WI(o.targetPlatform):"undefined"}function ep(o){let r=dt(o.versions.map(co)),e=!!o.tags?.includes(FI),t=r.indexOf("web");return e?t===-1&&r.push("web"):t!==-1&&r.splice(t,1),r}function Ab(o,r){for(let e=0;e<o.length;e++){let t=o[e];if(t.version===o[e-1]?.version){let n=e;if(co(t)===r)for(;n>0&&o[n-1].version===t.version;)n--;n!==e&&(o.splice(e,1),o.splice(n,0,t))}}return o}function o0(o,r,e){let t=[],n=-1,i=-1;for(let s of o){let a=co(s);if(!rc(a,e,r)){t.push(s);continue}zs(s)?n===-1?(n=t.length,t.push(s)):a===r&&t[n].version===s.version&&(t[n]=s):i===-1?(i=t.length,t.push(s)):a===r&&t[i].version===s.version&&(t[i]=s)}return t}function Fb(o,r,e){o.telemetryData={index:r,querySource:e,queryActivityId:o.queryContext?.[rp]}}function lh(o,r,e,t,n,i){let s=o.versions[0],a={manifest:an(r,Ft.Manifest),readme:an(r,Ft.Details),changelog:an(r,Ft.Changelog),license:an(r,Ft.License),repository:JP(r),download:QP(r),icon:an(r,Ft.Icon),signature:an(r,Ft.Signature),coreTranslations:HP(r)},l=lo(t,o.linkType??"ExtensionDetailsViewUriTemplate"),c=lo(t,o.publisher.linkType??"PublisherViewUriTemplate"),d=lo(t,o.ratingLinkType??"ExtensionRatingViewUriTemplate"),u=Er(o.publisher.publisherName,o.extensionName);return{type:"gallery",identifier:{id:u,uuid:o.extensionId},name:o.extensionName,version:r.version,displayName:o.displayName,publisherId:o.publisher.publisherId,publisher:o.publisher.publisherName,publisherDisplayName:n.extensionPublisherDisplayNameOverrides?.[o.publisher.publisherName.toLowerCase()]??o.publisher.displayName,publisherDomain:o.publisher.domain?{link:o.publisher.domain,verified:!!o.publisher.isDomainVerified}:n.verifiedExtensionPublishers?.[o.publisher.publisherName.toLowerCase()]?{link:n.verifiedExtensionPublishers[o.publisher.publisherName.toLowerCase()],verified:!0}:void 0,publisherSponsorLink:r0(s),description:o.shortDescription??"",installCount:ah(o.statistics,"install"),rating:ah(o.statistics,"averagerating"),ratingCount:ah(o.statistics,"ratingcount"),categories:o.categories||[],tags:o.tags||[],releaseDate:Date.parse(o.releaseDate),lastUpdated:Date.parse(o.lastUpdated),allTargetPlatforms:e,assets:a,properties:{dependencies:Mb(r,ln.Dependency),extensionPack:Mb(r,ln.ExtensionPack),engine:np(r),enabledApiProposals:ch(r),localizedLanguages:t0(r),targetPlatform:co(r),isPreReleaseVersion:zs(r),executesCode:e0(r)},hasPreReleaseVersion:Nb(u,n)??zs(s),hasReleaseVersion:!0,private:ZP(s),preview:i0(o.flags),isSigned:!!a.signature,queryContext:i,supportLink:n0(s),detailsLink:l?Dr(l,{publisher:o.publisher.publisherName,name:o.extensionName}):void 0,publisherLink:c?Dr(c,{publisher:o.publisher.publisherName}):void 0,ratingLink:d?Dr(d,{publisher:o.publisher.publisherName,name:o.extensionName}):void 0}}var Gs=class{constructor(r,e,t,n,i,s,a,l,c,d){this.requestService=e;this.logService=t;this.environmentService=n;this.telemetryService=i;this.fileService=s;this.productService=a;this.configurationService=l;this.allowedExtensionsService=c;this.extensionGalleryManifestService=d;let u=a.extensionsGallery,p=l.inspect("devin.marketplaceGalleryItemURL")?.userValue??l.inspect("windsurf.marketplaceGalleryItemURL")?.userValue;u&&p&&(u.itemUrl=p),this.extensionsControlUrl=a.extensionsGallery?.controlUrl,this.unpkgResourceApi=a.extensionsGallery?.extensionUrlTemplate,this.extensionsEnabledWithApiProposalVersion=a.extensionsEnabledWithApiProposalVersion?.map(m=>m.toLowerCase())??[],this.commonHeadersPromise=Lb(a.version,a,this.environmentService,this.configurationService,this.fileService,r,this.telemetryService)}isEnabled(){return this.extensionGalleryManifestService.extensionGalleryManifestStatus==="available"}async getExtensions(r,e,t){let n=await this.extensionGalleryManifestService.getExtensionGalleryManifest();if(!n)throw new Error("No extension gallery service configured.");let i=Y.isCancellationToken(e)?{}:e,s=Y.isCancellationToken(e)?e:t,a=this.getResourceApi(n),l=a?await this.getExtensionsUsingResourceApi(r,i,a,n,s):await this.getExtensionsUsingQueryApi(r,i,n,s),c=l.map(u=>u.identifier.uuid),d=[];for(let u of r)u.uuid&&!c.includes(u.uuid)&&d.push({...u,uuid:void 0});if(d.length){this.telemetryService.publicLog2("galleryService:additionalQueryByName",{count:d.length});let u=await this.getExtensionsUsingQueryApi(d,i,n,s);l.push(...u)}return l}getResourceApi(r){let e=lo(r,"ExtensionLatestVersionUriTemplate");if(e)return{uri:e,fallback:this.unpkgResourceApi}}async getExtensionsUsingQueryApi(r,e,t,n){let i=[],s=[],a=[],l=[],c=!0;for(let p of r)p.uuid?s.push(p.uuid):i.push(p.id),p.version?l.push({id:p.id,uuid:p.uuid,version:p.version}):a.push({id:p.id,uuid:p.uuid,includePreRelease:!!p.preRelease}),c=c&&!!p.hasPreRelease&&!p.preRelease;if(!s.length&&!i.length)return[];let d=new $s().withPage(1,r.length);s.length&&(d=d.withFilter("ExtensionId",...s)),i.length&&(d=d.withFilter("ExtensionName",...i)),e.queryAllVersions&&(d=d.withFlags(...d.flags,"IncludeVersions")),e.source&&(d=d.withSource(e.source));let{extensions:u}=await this.queryGalleryExtensions(d,{targetPlatform:e.targetPlatform??Zu,includePreRelease:a,versions:l,compatible:!!e.compatible,productVersion:e.productVersion??{version:this.productService.version,date:this.productService.date},isQueryForReleaseVersionFromPreReleaseVersion:c},t,n);return e.source&&u.forEach((p,m)=>Fb(p,m,e.source)),u}async getExtensionsUsingResourceApi(r,e,t,n,i){let s=[],a=[],l=[];for(let c of r)Eg.test(c.id)&&(c.version?a.push(c):l.push(c));if(await Promise.all(l.map(async c=>{let d;if(c.id!=="codeium.codeium-dev")try{d=await this.getLatestGalleryExtension(c,e,t,n,i),ue(d)?(this.telemetryService.publicLog2("galleryService:fallbacktoquery",{extension:c.id,preRelease:!!c.preRelease,compatible:!!e.compatible,errorCode:d}),a.push(c)):s.push(d)}catch(u){if(u instanceof Or)switch(u.code){case"Offline":case"Cancelled":case"Timeout":throw u}this.logService.error(`Error while getting the latest version for the extension ${c.id}.`,ee(u)),this.telemetryService.publicLog2("galleryService:fallbacktoquery",{extension:c.id,preRelease:!!c.preRelease,compatible:!!e.compatible,errorCode:u instanceof Or?u.code:"Unknown"}),a.push(c)}})),a.length){let c=await this.getExtensionsUsingQueryApi(a,e,n,i);s.push(...c)}return s}async getLatestGalleryExtension(r,e,t,n,i){let s=await this.getLatestRawGalleryExtensionWithFallback(r,t,i);if(!s)return"NOT_FOUND";let a=ep(s),l=await this.getValidRawGalleryExtensionVersionFromLatestVersions(s,s.versions,r,e,a);return l?lh(s,l,a,n,this.productService):"NOT_COMPATIBLE"}async getValidRawGalleryExtensionVersionFromLatestVersions(r,e,t,n,i){let s=n.targetPlatform??Zu,a=o0(e,s,i),l=await this.getValidRawGalleryExtensionVersion(r,a,{targetPlatform:s,compatible:!!n.compatible,productVersion:n.productVersion??{version:this.productService.version,date:this.productService.date},version:t.preRelease?1:0},i);if(!t.preRelease)return l;let c=l,d=await this.getValidRawGalleryExtensionVersion(r,a,{targetPlatform:s,compatible:!!n.compatible,productVersion:n.productVersion??{version:this.productService.version,date:this.productService.date},version:0},i);if(c&&d)return Hn(d.version,c.version)?d:c;if(n.compatible){if(d){let u=await this.getValidRawGalleryExtensionVersion(r,a,{targetPlatform:s,compatible:!1,productVersion:n.productVersion??{version:this.productService.version,date:this.productService.date},version:1},i);if(!u||Hn(d.version,u.version))return d}return c}return c??d??null}async getCompatibleExtension(r,e,t,n={version:this.productService.version,date:this.productService.date}){return Is(r.allTargetPlatforms,t)?null:await this.isExtensionCompatible(r,e,t)?r:this.allowedExtensionsService.isAllowed({id:r.identifier.id,publisherDisplayName:r.publisherDisplayName})!==!0?null:(await this.getExtensions([{...r.identifier,preRelease:e,hasPreRelease:r.hasPreReleaseVersion}],{compatible:!0,productVersion:n,queryAllVersions:!0,targetPlatform:t},Y.None))[0]??null}async isExtensionCompatible(r,e,t,n={version:this.productService.version,date:this.productService.date}){return this.isValidVersion({id:r.identifier.id,version:r.version,isPreReleaseVersion:r.properties.isPreReleaseVersion,targetPlatform:r.properties.targetPlatform,manifestAsset:r.assets.manifest,engine:r.properties.engine,enabledApiProposals:r.properties.enabledApiProposals},{targetPlatform:t,compatible:!0,productVersion:n,version:e?2:0},r.publisherDisplayName,r.allTargetPlatforms)}async isValidVersion(r,{targetPlatform:e,compatible:t,productVersion:n,version:i},s,a){let l=Nb(r.id,this.productService),c=YP(r.id,this.productService);if(r.isPreReleaseVersion&&l===!1||c&&Cb(r.version,c))return!1;if(ue(i)){if(r.version!==i)return!1}else if((i===0||i===1)&&r.isPreReleaseVersion!==(i===1))return!1;return!(e&&!rc(r.targetPlatform,a,e)||t&&(this.allowedExtensionsService.isAllowed({id:r.id,publisherDisplayName:s,version:r.version,prerelease:r.isPreReleaseVersion,targetPlatform:r.targetPlatform})!==!0||!this.areApiProposalsCompatible(r.id,r.enabledApiProposals)||!await this.isEngineValid(r.id,r.version,r.engine,r.manifestAsset,n)))}areApiProposalsCompatible(r,e){return!e||!this.extensionsEnabledWithApiProposalVersion.includes(r.toLowerCase())?!0:uc(e)}async isEngineValid(r,e,t,n,i){if(!t)try{t=await this.getEngine(r,e,n)}catch(s){return this.logService.error(`Error while getting the engine for the version ${e}.`,ee(s)),!1}return t?Bs(t,i.version,i.date):(this.logService.error(`Missing engine for the extension ${r} with version ${e}`),!1)}async getEngine(r,e,t){if(!t){this.logService.error(`Missing engine and manifest asset for the extension ${r} with version ${e}`);return}try{this.telemetryService.publicLog2("galleryService:engineFallback",{extension:r,extensionVersion:e});let n={"Accept-Encoding":"gzip"},i=await this.getAsset(r,t,Ft.Manifest,e,{headers:n}),s=await jr(i);if(!s){this.logService.error(`Manifest was not found for the extension ${r} with version ${e}`);return}return s.engines.vscode}catch(n){this.logService.error(`Error while getting the engine for the version ${e}.`,ee(n));return}}async query(r,e){let t=await this.extensionGalleryManifestService.getExtensionGalleryManifest();if(!t)throw new Error("No extension gallery service configured.");let n=r.text||"",i=r.pageSize??50,s=new $s().withPage(1,i);n?(n=n.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g,(u,p,m)=>(s=s.withFilter("Category",m||p),"")),n=n.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g,(u,p,m)=>(s=s.withFilter("Tag",m||p),"")),n=n.replace(/\bfeatured(\s+|\b|$)/g,()=>(s=s.withFilter("Featured"),"")),n=n.trim(),n&&(n=n.length<200?n:n.substring(0,200),s=s.withFilter("SearchText",n)),t.capabilities.extensionQuery.sorting?.some(u=>u.name==="NoneOrRelevance")&&(s=s.withSortBy("NoneOrRelevance"))):t.capabilities.extensionQuery.sorting?.some(u=>u.name==="InstallCount")&&(s=s.withSortBy("InstallCount")),r.sortBy&&t.capabilities.extensionQuery.sorting?.some(u=>u.name===r.sortBy)&&(s=s.withSortBy(r.sortBy)),typeof r.sortOrder=="number"&&(s=s.withSortOrder(r.sortOrder)),r.source&&(s=s.withSource(r.source));let a=async(u,p)=>{let{extensions:m,total:h}=await this.queryGalleryExtensions(u,{targetPlatform:Zu,compatible:!1,includePreRelease:!!r.includePreRelease,productVersion:r.productVersion??{version:this.productService.version,date:this.productService.date}},t,p),v=[],y;for(let x=0;x<m.length;x++){let E=m[x];Fb(E,(u.pageNumber-1)*u.pageSize+x,r.source),j(E.identifier,{id:this.productService.defaultChatAgent.extensionId})?y=E:v.push(E)}return y&&v.push(y),{extensions:v,total:h}},{extensions:l,total:c}=await a(s,e),d=async(u,p)=>{if(p.isCancellationRequested)throw new We;let{extensions:m}=await a(s.withPage(u+1),p);return m};return{firstPage:l,total:c,pageSize:s.pageSize,getPage:d}}async queryGalleryExtensions(r,e,t,n){let i=r.flags;r.flags.includes("IncludeLatestVersionOnly")&&r.flags.includes("IncludeVersions")&&(r=r.withFlags(...r.flags.filter(p=>p!=="IncludeVersions"))),!r.flags.includes("IncludeLatestVersionOnly")&&!r.flags.includes("IncludeVersions")&&(r=r.withFlags(...r.flags,"IncludeLatestVersionOnly")),(e.versions?.length||e.isQueryForReleaseVersionFromPreReleaseVersion)&&(r=r.withFlags(...r.flags.filter(p=>p!=="IncludeLatestVersionOnly"),"IncludeVersions")),r=r.withFlags(...r.flags,"IncludeAssetUri","IncludeCategoryAndTags","IncludeFiles","IncludeStatistics","IncludeVersionProperties");let{galleryExtensions:s,total:a,context:l}=await this.queryRawGalleryExtensions(r,t,n);if(!r.flags.includes("IncludeLatestVersionOnly")){let p=[];for(let m of s){let h=ep(m),v={id:Er(m.publisher.publisherName,m.extensionName),uuid:m.extensionId},y=Bt(e.includePreRelease)?e.includePreRelease:!!e.includePreRelease.find(E=>j(E,v))?.includePreRelease,x=await this.getValidRawGalleryExtensionVersion(m,m.versions,{compatible:e.compatible,targetPlatform:e.targetPlatform,productVersion:e.productVersion,version:e.versions?.find(E=>j(E,v))?.version??(y?2:0)},h);x&&p.push(lh(m,x,h,t,this.productService,l))}return{extensions:p,total:a}}let d=[],u=new Map;for(let p=0;p<s.length;p++){let m=s[p],h={id:Er(m.publisher.publisherName,m.extensionName),uuid:m.extensionId},v=Bt(e.includePreRelease)?e.includePreRelease:!!e.includePreRelease.find(R=>j(R,h))?.includePreRelease,y=ep(m);if(e.compatible&&(Is(y,e.targetPlatform)||this.allowedExtensionsService.isAllowed({id:h.id,publisherDisplayName:m.publisher.displayName})!==!0))continue;let x=await this.getValidRawGalleryExtensionVersion(m,m.versions,{compatible:e.compatible,targetPlatform:e.targetPlatform,productVersion:e.productVersion,version:e.versions?.find(R=>j(R,h))?.version??(v?2:0)},y),E=x?lh(m,x,y,t,this.productService,l):null;!E||E.properties.isPreReleaseVersion&&(!v||!E.hasReleaseVersion)||!E.properties.isPreReleaseVersion&&E.properties.targetPlatform!==e.targetPlatform&&E.hasPreReleaseVersion?u.set(m.extensionId,p):d.push([p,E])}if(u.size){let p=new qr,m=new $s().withFlags(...i.filter(v=>v!=="IncludeLatestVersionOnly"),"IncludeVersions").withPage(1,u.size).withFilter("ExtensionId",...u.keys()),{extensions:h}=await this.queryGalleryExtensions(m,e,t,n);this.telemetryService.publicLog2("galleryService:additionalQuery",{duration:p.elapsed(),count:u.size});for(let v of h){let y=u.get(v.identifier.uuid);d.push([y,v])}}return{extensions:d.sort((p,m)=>p[0]-m[0]).map(([,p])=>p),total:a}}async getValidRawGalleryExtensionVersion(r,e,t,n){let i={id:Er(r.publisher.publisherName,r.extensionName),uuid:r.extensionId},s=Ab(e,t.targetPlatform);if(t.compatible&&Is(n,t.targetPlatform))return null;let a=ue(t.version)?t.version:void 0;for(let l=0;l<s.length;l++){let c=s[l];if(t.compatible&&await this.setEngineIfNotExists(i.id,c),await this.isValidVersion({id:i.id,version:c.version,isPreReleaseVersion:zs(c),targetPlatform:co(c),engine:np(c),manifestAsset:an(c,Ft.Manifest),enabledApiProposals:ch(c)},t,r.publisher.displayName,n))return c;if(a&&c.version===a)return null}return a||t.compatible?null:r.versions[0]}async setEngineIfNotExists(r,e){if(!np(e))try{let t=await this.getEngine(r,e.version,an(e,Ft.Manifest));t&&XP(e,t)}catch(t){this.logService.error(`Error while getting the engine for the version ${e.version}.`,ee(t))}}async queryRawGalleryExtensions(r,e,t){let n=lo(e,"ExtensionQueryService");if(!n)throw new Error("No extension gallery query service configured.");r=r.withFlags(...r.flags,"ExcludeNonValidated").withFilter("Target","Microsoft.VisualStudio.Code");let i=e.capabilities.extensionQuery.flags?.find(m=>m.name==="Unpublished");i&&(r=r.withFilter("ExcludeWithFlags",String(i.value)));let s=JSON.stringify({filters:[{criteria:r.criteria.reduce((m,h)=>{let v=e.capabilities.extensionQuery.filtering?.find(y=>y.name===h.filterType);return v&&m.push({filterType:v.value,value:h.value}),m},[]),pageNumber:r.pageNumber,pageSize:r.pageSize,sortBy:e.capabilities.extensionQuery.sorting?.find(m=>m.name===r.sortBy)?.value,sortOrder:r.sortOrder}],assetTypes:r.assetTypes,flags:r.flags.reduce((m,h)=>{let v=e.capabilities.extensionQuery.flags?.find(y=>y.name===h);return v&&(m|=v.value),m},0)}),l={...await this.commonHeadersPromise,"Content-Type":"application/json",Accept:"application/json;api-version=3.0-preview.1","Accept-Encoding":"gzip","Content-Length":String(s.length)},c=new qr,d,u,p=0;try{if(d=await this.requestService.request({type:"POST",url:n,data:s,headers:l},t),d.res.statusCode&&d.res.statusCode>=400&&d.res.statusCode<500)return{galleryExtensions:[],total:p};let m=await jr(d);if(m){let h=m.results[0],v=h.extensions,y=h.resultMetadata&&h.resultMetadata.filter(x=>x.metadataType==="ResultCount")[0];return p=y&&y.metadataItems.filter(x=>x.name==="TotalCount")[0].count||0,{galleryExtensions:v,total:p,context:d.res.headers.activityid?{[rp]:d.res.headers.activityid}:{}}}return{galleryExtensions:[],total:p}}catch(m){if(lr(m))throw u="Cancelled",m;{let h=ee(m);throw u=eh(m)?"Offline":h.startsWith("XHR timeout")?"Timeout":"Failed",new Or(h,u)}}finally{this.telemetryService.publicLog2("galleryService:query",{filterTypes:r.criteria.map(m=>m.filterType),flags:r.flags,sortBy:r.sortBy,sortOrder:String(r.sortOrder),pageNumber:String(r.pageNumber),source:r.source,searchTextLength:r.searchText.length,requestBodySize:String(s.length),duration:c.elapsed(),success:!!d&&Kn(d),responseBodySize:d?.res.headers["Content-Length"],statusCode:d?String(d.res.statusCode):void 0,errorCode:u,count:String(p),server:this.getHeaderValue(d?.res.headers,oh),activityId:this.getHeaderValue(d?.res.headers,ih),endToEndId:this.getHeaderValue(d?.res.headers,sh)})}}getHeaderValue(r,e){let t=r?.[e.toLowerCase()],n=Array.isArray(t)?t[0]:t;return n?new Si(n):void 0}async getLatestRawGalleryExtensionWithFallback(r,e,t){let[n,i]=r.id.split("."),s;try{let a=P.parse(Dr(e.uri,{publisher:n,name:i}));return await this.getLatestRawGalleryExtension(r.id,a,t)}catch(a){if(a instanceof Or)switch(s=a.code,a.code){case"Offline":case"Cancelled":case"Timeout":case"ClientError":throw a}else s="Unknown";if(!e.fallback)throw a}finally{this.telemetryService.publicLog2("galleryService:getmarketplacelatest",{extension:r.id,errorCode:s})}this.logService.error(`Error while getting the latest version for the extension ${r.id} from ${e.uri}. Trying the fallback ${e.fallback}`,s);try{let a=P.parse(Dr(e.fallback,{publisher:n,name:i}));return await this.getLatestRawGalleryExtension(r.id,a,t)}catch(a){throw s=a instanceof Or?a.code:"Unknown",a}finally{this.telemetryService.publicLog2("galleryService:fallbacktounpkg",{extension:r.id,errorCode:s})}}async getLatestRawGalleryExtension(r,e,t){let n,i,s=new qr;try{let l={...await this.commonHeadersPromise,"Content-Type":"application/json",Accept:"application/json;api-version=7.2-preview","Accept-Encoding":"gzip"};if(n=await this.requestService.request({type:"GET",url:e.toString(!0),headers:l,timeout:this.getRequestTimeout()},t),n.res.statusCode===404)return i="NotFound",null;if(n.res.statusCode&&n.res.statusCode!==200)throw new Error("Unexpected HTTP response: "+n.res.statusCode);let c=await jr(n);return c||(i="NoData"),c}catch(a){let l;throw lr(a)?l="Cancelled":eh(a)?l="Offline":ee(a).startsWith("XHR timeout")?l="Timeout":n&&cb(n)?l="ClientError":n&&db(n)?l="ServerError":l="Failed",i=l,new Or(a,l)}finally{this.telemetryService.publicLog2("galleryService:getLatest",{extension:r,host:e.authority,duration:s.elapsed(),errorCode:i,statusCode:n?.res.statusCode&&n?.res.statusCode!==200?`${n.res.statusCode}`:void 0,server:this.getHeaderValue(n?.res.headers,oh),activityId:this.getHeaderValue(n?.res.headers,ih),endToEndId:this.getHeaderValue(n?.res.headers,sh)})}}async reportStatistic(r,e,t,n){if(ze){this.logService.info("ExtensionGalleryService#reportStatistic: Skipped in web");return}let i=await this.extensionGalleryManifestService.getExtensionGalleryManifest();if(!i)return;let s=lo(i,"ExtensionStatisticsUriTemplate");if(!s)return;let a=Dr(s,{publisher:r,name:e,version:t,statTypeName:n}),d={...await this.commonHeadersPromise,Accept:"*/*;api-version=4.0-preview.1"};try{await this.requestService.request({type:"POST",url:a,headers:d},Y.None)}catch{}}async download(r,e,t){this.logService.trace("ExtensionGalleryService#download",r.identifier.id);let n=dc(r),i=new Date().getTime(),s=t===2?"install":t===3?"update":"",a=s?{uri:`${r.assets.download.uri}${P.parse(r.assets.download.uri).query?"&":"?"}${s}=true`,fallbackUri:`${r.assets.download.fallbackUri}${P.parse(r.assets.download.fallbackUri).query?"&":"?"}${s}=true`}:r.assets.download,l=r.queryContext?.[rp],c=l&&typeof l=="string"?{[rp]:l}:void 0,d=await this.getAsset(r.identifier.id,a,Ft.VSIX,r.version,c?{headers:c}:void 0);try{await this.fileService.writeFile(e,d.stream)}catch(u){try{await this.fileService.del(e)}catch(p){this.logService.warn(`Error while deleting the file ${e.toString()}`,ee(p))}throw new Or(ee(u),"DownloadFailedWriting")}this.telemetryService.publicLog("galleryService:downloadVSIX",{...n,duration:new Date().getTime()-i})}async downloadSignatureArchive(r,e){if(!r.assets.signature)throw new Error("No signature asset found");this.logService.trace("ExtensionGalleryService#downloadSignatureArchive",r.identifier.id);let t=await this.getAsset(r.identifier.id,r.assets.signature,Ft.Signature,r.version);try{await this.fileService.writeFile(e,t.stream)}catch(n){try{await this.fileService.del(e)}catch(i){this.logService.warn(`Error while deleting the file ${e.toString()}`,ee(i))}throw new Or(ee(n),"DownloadFailedWriting")}}async getReadme(r,e){if(r.assets.readme){let t=await this.getAsset(r.identifier.id,r.assets.readme,Ft.Details,r.version,{},e);return await Vr(t)||""}return""}async getManifest(r,e){if(r.assets.manifest){let t=await this.getAsset(r.identifier.id,r.assets.manifest,Ft.Manifest,r.version,{},e),n=await Vr(t);return n?JSON.parse(n):null}return null}async getCoreTranslation(r,e){let t=r.assets.coreTranslations.filter(n=>n[0]===e.toUpperCase())[0];if(t){let n=await this.getAsset(r.identifier.id,t[1],t[0],r.version),i=await Vr(n);return i?JSON.parse(i):null}return null}async getChangelog(r,e){if(r.assets.changelog){let t=await this.getAsset(r.identifier.id,r.assets.changelog,Ft.Changelog,r.version,{},e);return await Vr(t)||""}return""}async getAllVersions(r){return this.getVersions(r)}async getAllCompatibleVersions(r,e,t){return this.getVersions(r,{version:e?2:0,targetPlatform:t})}async getVersions(r,e){let t=await this.extensionGalleryManifestService.getExtensionGalleryManifest();if(!t)throw new Error("No extension gallery service configured.");let n=new $s().withFlags("IncludeVersions","IncludeCategoryAndTags","IncludeFiles","IncludeVersionProperties").withPage(1,1);r.uuid?n=n.withFilter("ExtensionId",r.uuid):n=n.withFilter("ExtensionName",r.id);let{galleryExtensions:i}=await this.queryRawGalleryExtensions(n,t,Y.None);if(!i.length)return[];let s=ep(i[0]);if(e&&Is(s,e.targetPlatform))return[];let a=[],l={version:this.productService.version,date:this.productService.date};await Promise.all(i[0].versions.map(async u=>{try{await this.isValidVersion({id:r.id,version:u.version,isPreReleaseVersion:zs(u),targetPlatform:co(u),engine:np(u),manifestAsset:an(u,Ft.Manifest),enabledApiProposals:ch(u)},{compatible:!!e,productVersion:l,targetPlatform:e?.targetPlatform,version:e?.version??u.version},i[0].publisher.displayName,s)&&a.push(u)}catch{}}));let c=[],d=new Map;for(let u of Ab(a,e?.targetPlatform??Zu)){let p=d.get(u.version),m=p!==void 0?c[p]:void 0,h=co(u);m?m.targetPlatforms.push(h):(d.set(u.version,c.length),c.push({version:u.version,date:u.lastUpdated,isPreReleaseVersion:zs(u),targetPlatforms:[h]}))}return c}async getAsset(r,e,t,n,i={},s=Y.None){let a=await this.commonHeadersPromise,l={type:"GET"},c={...a,...i.headers||{}};i={...i,...l,headers:c};let d=e.uri,u=e.fallbackUri,p={...i,url:d,timeout:this.getRequestTimeout()},m;try{if(m=await this.requestService.request(p,s),m.res.statusCode===200)return m;let h=await Vr(m);throw new Error(`Expected 200, got back ${m.res.statusCode} instead.

${h}`)}catch(h){if(lr(h))throw h;let v=ee(h);this.telemetryService.publicLog2("galleryService:cdnFallback",{extension:r,assetType:t,message:v,extensionVersion:n,server:this.getHeaderValue(m?.res.headers,oh),activityId:this.getHeaderValue(m?.res.headers,ih),endToEndId:this.getHeaderValue(m?.res.headers,sh)});let y={...i,url:u,timeout:this.getRequestTimeout()};return this.requestService.request(y,s)}}async getExtensionsControlManifest(){if(!await this.extensionGalleryManifestService.getExtensionGalleryManifest())throw new Error("No extension gallery service configured.");if(!this.extensionsControlUrl)return{malicious:[],deprecated:{},search:[],autoUpdate:{}};let e=await this.requestService.request({type:"GET",url:this.extensionsControlUrl,timeout:this.getRequestTimeout()},Y.None);if(e.res.statusCode!==200)throw new Error("Could not get extensions report.");let t=await jr(e),n=[],i={},s=[],a=t?.autoUpdate??{};if(t){for(let l of t.malicious){if(!ue(l))continue;let c=Eg.test(l)?{id:l}:l;n.push({extensionOrPublisher:c,learnMoreLink:t.learnMoreLinks?.[l]})}if(t.migrateToPreRelease)for(let[l,c]of Object.entries(t.migrateToPreRelease))(!c.engine||Bs(c.engine,this.productService.version,this.productService.date))&&(i[l.toLowerCase()]={disallowInstall:!0,extension:{id:c.id,displayName:c.displayName,autoMigrate:{storage:!!c.migrateStorage},preRelease:!0}});if(t.deprecated)for(let[l,c]of Object.entries(t.deprecated))c&&(i[l.toLowerCase()]=Bt(c)?{}:c);if(t.search)for(let l of t.search)s.push(l)}return i[this.productService.defaultChatAgent.extensionId.toLowerCase()]={disallowInstall:!0,extension:{id:this.productService.defaultChatAgent.chatExtensionId,displayName:"GitHub Copilot Chat",autoMigrate:{storage:!1,donotDisable:!0},preRelease:this.productService.quality!=="stable"}},{malicious:n,deprecated:i,search:s,autoUpdate:a}}getRequestTimeout(){let r=this.configurationService.getValue(GI);return Un(r)&&r>=0?r:6e4}};Gs=b([g(1,Nr),g(2,V),g(3,X),g(4,de),g(5,W),g(6,ne),g(7,Q),g(8,sn),g(9,bi)],Gs);var qs=class extends Gs{constructor(r,e,t,n,i,s,a,l,c,d){super(r,e,t,n,i,s,a,l,c,d)}};qs=b([g(0,K),g(1,Nr),g(2,V),g(3,X),g(4,de),g(5,W),g(6,ne),g(7,Q),g(8,sn),g(9,bi)],qs);var tp=class extends Gs{constructor(r,e,t,n,i,s,a,l,c){super(void 0,r,e,t,n,i,s,a,l,c)}};tp=b([g(0,Nr),g(1,V),g(2,X),g(3,de),g(4,W),g(5,ne),g(6,Q),g(7,sn),g(8,bi)],tp);var ip=L("IExtensionSignatureVerificationService"),Ks=class{constructor(r,e){this.logService=r;this.telemetryService=e}vsceSign(){return this.moduleLoadingPromise||(this.moduleLoadingPromise=this.resolveVsceSign()),this.moduleLoadingPromise}async resolveVsceSign(){return import("@vscode/vsce-sign")}async verify(r,e,t,n,i){let s;try{s=await this.vsceSign()}catch(d){this.logService.error("Could not load vsce-sign module",ee(d)),this.logService.info(`Extension signature verification is not done: ${r}`);return}let a=new Date().getTime(),l;try{this.logService.trace(`Verifying extension signature for ${r}...`),l=await s.verify(t,n,this.logService.getLevel()===1)}catch(d){l={code:"UnknownError",didExecute:!1,output:ee(d)}}let c=new Date().getTime()-a;return this.logService.info(`Extension signature verification result for ${r}: ${l.code}. ${rd(l.internalCode)?`Internal Code: ${l.internalCode}. `:""}Executed: ${l.didExecute}. Duration: ${c}ms.`),this.logService.trace(`Extension signature verification output for ${r}:
${l.output}`),this.telemetryService.publicLog2("extensionsignature:verification",{extensionId:r,extensionVersion:e,code:l.code,internalCode:l.internalCode,duration:c,didExecute:l.didExecute,clientTargetPlatform:i}),{code:l.code}}};Ks=b([g(0,V),g(1,de)],Ks);var js=new class{transformIncoming(o){return o}transformOutgoing(o){return o}transformOutgoingURI(o){return o}transformOutgoingScheme(o){return o}};function Vb(o,r,e,t){if(!o||t>200)return null;if(typeof o=="object"){if(o.$mid===1)return e?P.revive(r.transformIncoming(o)):r.transformIncoming(o);if(o instanceof U)return null;for(let n in o)if(Object.hasOwnProperty.call(o,n)){let i=Vb(o[n],r,e,t+1);i!==null&&(o[n]=i)}}return null}function Hs(o,r){let e=Vb(o,r,!0,0);return e===null?o:e}var e9=new Uint32Array(10);var t9=new Uint8Array([114,82,115,101,69,102,97,113,81,116,84,100,119,87,99,122,120,118,103]),r9=new Uint16Array([107,111,105,79,106,112,117,80,104,27496,28520,27752,121,110,27246,28782,27758,98,109,27757,108]),n9=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]),i9=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]);function Bb(...o){return function(r,e){for(let t=0,n=o.length;t<n;t++){let i=o[t](r,e);if(i)return i}return null}}var f9=Gb.bind(void 0,!1),$b=Gb.bind(void 0,!0);function Gb(o,r,e){if(!e||e.length<r.length)return null;let t;return o?t=ji(e,r):t=e.indexOf(r)===0,t?r.length>0?[{start:0,end:r.length}]:[]:null}function a0(o,r){if(o.length>r.length)return null;let e=r.toLowerCase().indexOf(o.toLowerCase());return e===-1?null:[{start:e,end:e+o.length}]}function l0(o,r){return o.length>r.length?null:uh(o.toLowerCase(),r.toLowerCase(),0,0)}function uh(o,r,e,t){if(e===o.length)return[];if(t===r.length)return null;if(o[e]===r[t]){let n=null;return(n=uh(o,r,e+1,t+1))?zb({start:t,end:t+1},n):null}return uh(o,r,e,t+1)}function fh(o){return 97<=o&&o<=122}function sp(o){return 65<=o&&o<=90}function mh(o){return 48<=o&&o<=57}function c0(o){return o===32||o===9||o===10||o===13}var d0=new Set;"()[]{}<>`'\"-/;:,.?!".split("").forEach(o=>d0.add(o.charCodeAt(0)));function qb(o){return fh(o)||sp(o)||mh(o)}function zb(o,r){return r.length===0?r=[o]:o.end===r[0].start?r[0].start=o.start:r.unshift(o),r}function Kb(o,r){for(let e=r;e<o.length;e++){let t=o.charCodeAt(e);if(sp(t)||mh(t)||e>0&&!qb(o.charCodeAt(e-1)))return e}return o.length}function ph(o,r,e,t){if(e===o.length)return[];if(t===r.length)return null;if(o[e]!==r[t].toLowerCase())return null;{let n=null,i=t+1;for(n=ph(o,r,e+1,t+1);!n&&(i=Kb(r,i))<r.length;)n=ph(o,r,e+1,i),i++;return n===null?null:zb({start:t,end:t+1},n)}}function u0(o){let r=0,e=0,t=0,n=0,i=0;for(let d=0;d<o.length;d++)i=o.charCodeAt(d),sp(i)&&r++,fh(i)&&e++,qb(i)&&t++,mh(i)&&n++;let s=r/o.length,a=e/o.length,l=t/o.length,c=n/o.length;return{upperPercent:s,lowerPercent:a,alphaPercent:l,numericPercent:c}}function p0(o){let{upperPercent:r,lowerPercent:e}=o;return e===0&&r>.6}function f0(o){let{upperPercent:r,lowerPercent:e,alphaPercent:t,numericPercent:n}=o;return e>.2&&r<.8&&t>.6&&n<.2}function m0(o){let r=0,e=0,t=0,n=0;for(let i=0;i<o.length;i++)t=o.charCodeAt(i),sp(t)&&r++,fh(t)&&e++,c0(t)&&n++;return(r===0||e===0)&&n===0?o.length<=30:r<=5}function jb(o,r){if(!r||(r=r.trim(),r.length===0)||!m0(o))return null;r.length>60&&(r=r.substring(0,60));let e=u0(r);if(!f0(e)){if(!p0(e))return null;r=r.toLowerCase()}let t=null,n=0;for(o=o.toLowerCase();n<r.length&&(t=ph(o,r,0,n))===null;)n=Kb(r,n+1);return t}var m9=Bb($b,jb,a0),g9=Bb($b,jb,l0),h9=new yn(1e4);var op=128;function gh(){let o=[],r=[];for(let e=0;e<=op;e++)r[e]=0;for(let e=0;e<=op;e++)o.push(r.slice(0));return o}function Hb(o){let r=[];for(let e=0;e<=o;e++)r[e]=0;return r}var v9=Hb(2*op),y9=Hb(2*op),S9=gh(),I9=gh(),b9=gh();var g0;(e=>{e.Default=[-100,0];function r(t){return!t||t.length===2&&t[0]===-100&&t[1]===0}e.isDefault=r})(g0||={});var Wb=class{constructor(r,e){this.firstMatchCanBeWeak=r;this.boostFullMatch=e}static{this.default={boostFullMatch:!0,firstMatchCanBeWeak:!1}}};var Jb=Object.create(null);function f(o,r){if(ue(r)){let e=Jb[r];if(e===void 0)throw new Error(`${o} references an unknown codicon: ${r}`);r=e}return Jb[o]=r,{id:o}}var Qb={add:f("add",6e4),plus:f("plus",6e4),gistNew:f("gist-new",6e4),repoCreate:f("repo-create",6e4),lightbulb:f("lightbulb",60001),lightBulb:f("light-bulb",60001),repo:f("repo",60002),repoDelete:f("repo-delete",60002),gistFork:f("gist-fork",60003),repoForked:f("repo-forked",60003),gitPullRequest:f("git-pull-request",60004),gitPullRequestAbandoned:f("git-pull-request-abandoned",60004),recordKeys:f("record-keys",60005),keyboard:f("keyboard",60005),tag:f("tag",60006),gitPullRequestLabel:f("git-pull-request-label",60006),tagAdd:f("tag-add",60006),tagRemove:f("tag-remove",60006),person:f("person",60007),personFollow:f("person-follow",60007),personOutline:f("person-outline",60007),personFilled:f("person-filled",60007),sourceControl:f("source-control",60008),mirror:f("mirror",60009),mirrorPublic:f("mirror-public",60009),star:f("star",60010),starAdd:f("star-add",60010),starDelete:f("star-delete",60010),starEmpty:f("star-empty",60010),comment:f("comment",60011),commentAdd:f("comment-add",60011),alert:f("alert",60012),warning:f("warning",60012),search:f("search",60013),searchSave:f("search-save",60013),logOut:f("log-out",60014),signOut:f("sign-out",60014),logIn:f("log-in",60015),signIn:f("sign-in",60015),eye:f("eye",60016),eyeUnwatch:f("eye-unwatch",60016),eyeWatch:f("eye-watch",60016),circleFilled:f("circle-filled",60017),primitiveDot:f("primitive-dot",60017),closeDirty:f("close-dirty",60017),debugBreakpoint:f("debug-breakpoint",60017),debugBreakpointDisabled:f("debug-breakpoint-disabled",60017),debugHint:f("debug-hint",60017),terminalDecorationSuccess:f("terminal-decoration-success",60017),primitiveSquare:f("primitive-square",60018),edit:f("edit",60019),pencil:f("pencil",60019),info:f("info",60020),issueOpened:f("issue-opened",60020),gistPrivate:f("gist-private",60021),gitForkPrivate:f("git-fork-private",60021),lock:f("lock",60021),mirrorPrivate:f("mirror-private",60021),close:f("close",60022),removeClose:f("remove-close",60022),x:f("x",60022),repoSync:f("repo-sync",60023),sync:f("sync",60023),clone:f("clone",60024),desktopDownload:f("desktop-download",60024),beaker:f("beaker",60025),microscope:f("microscope",60025),vm:f("vm",60026),deviceDesktop:f("device-desktop",60026),file:f("file",60027),more:f("more",60028),ellipsis:f("ellipsis",60028),kebabHorizontal:f("kebab-horizontal",60028),mailReply:f("mail-reply",60029),reply:f("reply",60029),organization:f("organization",60030),organizationFilled:f("organization-filled",60030),organizationOutline:f("organization-outline",60030),newFile:f("new-file",60031),fileAdd:f("file-add",60031),newFolder:f("new-folder",60032),fileDirectoryCreate:f("file-directory-create",60032),trash:f("trash",60033),trashcan:f("trashcan",60033),history:f("history",60034),clock:f("clock",60034),folder:f("folder",60035),fileDirectory:f("file-directory",60035),symbolFolder:f("symbol-folder",60035),logoGithub:f("logo-github",60036),markGithub:f("mark-github",60036),github:f("github",60036),terminal:f("terminal",60037),console:f("console",60037),repl:f("repl",60037),zap:f("zap",60038),symbolEvent:f("symbol-event",60038),error:f("error",60039),stop:f("stop",60039),variable:f("variable",60040),symbolVariable:f("symbol-variable",60040),array:f("array",60042),symbolArray:f("symbol-array",60042),symbolModule:f("symbol-module",60043),symbolPackage:f("symbol-package",60043),symbolNamespace:f("symbol-namespace",60043),symbolObject:f("symbol-object",60043),symbolMethod:f("symbol-method",60044),symbolFunction:f("symbol-function",60044),symbolConstructor:f("symbol-constructor",60044),symbolBoolean:f("symbol-boolean",60047),symbolNull:f("symbol-null",60047),symbolNumeric:f("symbol-numeric",60048),symbolNumber:f("symbol-number",60048),symbolStructure:f("symbol-structure",60049),symbolStruct:f("symbol-struct",60049),symbolParameter:f("symbol-parameter",60050),symbolTypeParameter:f("symbol-type-parameter",60050),symbolKey:f("symbol-key",60051),symbolText:f("symbol-text",60051),symbolReference:f("symbol-reference",60052),goToFile:f("go-to-file",60052),symbolEnum:f("symbol-enum",60053),symbolValue:f("symbol-value",60053),symbolRuler:f("symbol-ruler",60054),symbolUnit:f("symbol-unit",60054),activateBreakpoints:f("activate-breakpoints",60055),archive:f("archive",60056),arrowBoth:f("arrow-both",60057),arrowDown:f("arrow-down",60058),arrowLeft:f("arrow-left",60059),arrowRight:f("arrow-right",60060),arrowSmallDown:f("arrow-small-down",60061),arrowSmallLeft:f("arrow-small-left",60062),arrowSmallRight:f("arrow-small-right",60063),arrowSmallUp:f("arrow-small-up",60064),arrowUp:f("arrow-up",60065),bell:f("bell",60066),bold:f("bold",60067),book:f("book",60068),bookmark:f("bookmark",60069),debugBreakpointConditionalUnverified:f("debug-breakpoint-conditional-unverified",60070),debugBreakpointConditional:f("debug-breakpoint-conditional",60071),debugBreakpointConditionalDisabled:f("debug-breakpoint-conditional-disabled",60071),debugBreakpointDataUnverified:f("debug-breakpoint-data-unverified",60072),debugBreakpointData:f("debug-breakpoint-data",60073),debugBreakpointDataDisabled:f("debug-breakpoint-data-disabled",60073),debugBreakpointLogUnverified:f("debug-breakpoint-log-unverified",60074),debugBreakpointLog:f("debug-breakpoint-log",60075),debugBreakpointLogDisabled:f("debug-breakpoint-log-disabled",60075),briefcase:f("briefcase",60076),broadcast:f("broadcast",60077),browser:f("browser",60078),bug:f("bug",60079),calendar:f("calendar",60080),caseSensitive:f("case-sensitive",60081),check:f("check",60082),checklist:f("checklist",60083),chevronDown:f("chevron-down",60084),chevronLeft:f("chevron-left",60085),chevronRight:f("chevron-right",60086),chevronUp:f("chevron-up",60087),chromeClose:f("chrome-close",60088),chromeMaximize:f("chrome-maximize",60089),chromeMinimize:f("chrome-minimize",60090),chromeRestore:f("chrome-restore",60091),circleOutline:f("circle-outline",60092),circle:f("circle",60092),debugBreakpointUnverified:f("debug-breakpoint-unverified",60092),terminalDecorationIncomplete:f("terminal-decoration-incomplete",60092),circleSlash:f("circle-slash",60093),circuitBoard:f("circuit-board",60094),clearAll:f("clear-all",60095),clippy:f("clippy",60096),closeAll:f("close-all",60097),cloudDownload:f("cloud-download",60098),cloudUpload:f("cloud-upload",60099),code:f("code",60100),collapseAll:f("collapse-all",60101),colorMode:f("color-mode",60102),commentDiscussion:f("comment-discussion",60103),creditCard:f("credit-card",60105),dash:f("dash",60108),dashboard:f("dashboard",60109),database:f("database",60110),debugContinue:f("debug-continue",60111),debugDisconnect:f("debug-disconnect",60112),debugPause:f("debug-pause",60113),debugRestart:f("debug-restart",60114),debugStart:f("debug-start",60115),debugStepInto:f("debug-step-into",60116),debugStepOut:f("debug-step-out",60117),debugStepOver:f("debug-step-over",60118),debugStop:f("debug-stop",60119),debug:f("debug",60120),deviceCameraVideo:f("device-camera-video",60121),deviceCamera:f("device-camera",60122),deviceMobile:f("device-mobile",60123),diffAdded:f("diff-added",60124),diffIgnored:f("diff-ignored",60125),diffModified:f("diff-modified",60126),diffRemoved:f("diff-removed",60127),diffRenamed:f("diff-renamed",60128),diff:f("diff",60129),diffSidebyside:f("diff-sidebyside",60129),discard:f("discard",60130),editorLayout:f("editor-layout",60131),emptyWindow:f("empty-window",60132),exclude:f("exclude",60133),extensions:f("extensions",60134),eyeClosed:f("eye-closed",60135),fileBinary:f("file-binary",60136),fileCode:f("file-code",60137),fileMedia:f("file-media",60138),filePdf:f("file-pdf",60139),fileSubmodule:f("file-submodule",60140),fileSymlinkDirectory:f("file-symlink-directory",60141),fileSymlinkFile:f("file-symlink-file",60142),fileZip:f("file-zip",60143),files:f("files",60144),filter:f("filter",60145),flame:f("flame",60146),foldDown:f("fold-down",60147),foldUp:f("fold-up",60148),fold:f("fold",60149),folderActive:f("folder-active",60150),folderOpened:f("folder-opened",60151),gear:f("gear",60152),gift:f("gift",60153),gistSecret:f("gist-secret",60154),gist:f("gist",60155),gitCommit:f("git-commit",60156),gitCompare:f("git-compare",60157),compareChanges:f("compare-changes",60157),gitMerge:f("git-merge",60158),githubAction:f("github-action",60159),githubAlt:f("github-alt",60160),globe:f("globe",60161),grabber:f("grabber",60162),graph:f("graph",60163),gripper:f("gripper",60164),heart:f("heart",60165),home:f("home",60166),horizontalRule:f("horizontal-rule",60167),hubot:f("hubot",60168),inbox:f("inbox",60169),issueReopened:f("issue-reopened",60171),issues:f("issues",60172),italic:f("italic",60173),jersey:f("jersey",60174),json:f("json",60175),bracket:f("bracket",60175),kebabVertical:f("kebab-vertical",60176),key:f("key",60177),law:f("law",60178),lightbulbAutofix:f("lightbulb-autofix",60179),linkExternal:f("link-external",60180),link:f("link",60181),listOrdered:f("list-ordered",60182),listUnordered:f("list-unordered",60183),liveShare:f("live-share",60184),loading:f("loading",60185),location:f("location",60186),mailRead:f("mail-read",60187),mail:f("mail",60188),markdown:f("markdown",60189),megaphone:f("megaphone",60190),mention:f("mention",60191),milestone:f("milestone",60192),gitPullRequestMilestone:f("git-pull-request-milestone",60192),mortarBoard:f("mortar-board",60193),move:f("move",60194),multipleWindows:f("multiple-windows",60195),mute:f("mute",60196),noNewline:f("no-newline",60197),note:f("note",60198),octoface:f("octoface",60199),openPreview:f("open-preview",60200),package:f("package",60201),paintcan:f("paintcan",60202),pin:f("pin",60203),play:f("play",60204),run:f("run",60204),plug:f("plug",60205),preserveCase:f("preserve-case",60206),preview:f("preview",60207),project:f("project",60208),pulse:f("pulse",60209),question:f("question",60210),quote:f("quote",60211),radioTower:f("radio-tower",60212),reactions:f("reactions",60213),references:f("references",60214),refresh:f("refresh",60215),regex:f("regex",60216),remoteExplorer:f("remote-explorer",60217),remote:f("remote",60218),remove:f("remove",60219),replaceAll:f("replace-all",60220),replace:f("replace",60221),repoClone:f("repo-clone",60222),repoForcePush:f("repo-force-push",60223),repoPull:f("repo-pull",60224),repoPush:f("repo-push",60225),report:f("report",60226),requestChanges:f("request-changes",60227),rocket:f("rocket",60228),rootFolderOpened:f("root-folder-opened",60229),rootFolder:f("root-folder",60230),rss:f("rss",60231),ruby:f("ruby",60232),saveAll:f("save-all",60233),saveAs:f("save-as",60234),save:f("save",60235),screenFull:f("screen-full",60236),screenNormal:f("screen-normal",60237),searchStop:f("search-stop",60238),server:f("server",60240),settingsGear:f("settings-gear",60241),settings:f("settings",60242),shield:f("shield",60243),smiley:f("smiley",60244),sortPrecedence:f("sort-precedence",60245),splitHorizontal:f("split-horizontal",60246),splitVertical:f("split-vertical",60247),squirrel:f("squirrel",60248),starFull:f("star-full",60249),starHalf:f("star-half",60250),symbolClass:f("symbol-class",60251),symbolColor:f("symbol-color",60252),symbolConstant:f("symbol-constant",60253),symbolEnumMember:f("symbol-enum-member",60254),symbolField:f("symbol-field",60255),symbolFile:f("symbol-file",60256),symbolInterface:f("symbol-interface",60257),symbolKeyword:f("symbol-keyword",60258),symbolMisc:f("symbol-misc",60259),symbolOperator:f("symbol-operator",60260),symbolProperty:f("symbol-property",60261),wrench:f("wrench",60261),wrenchSubaction:f("wrench-subaction",60261),symbolSnippet:f("symbol-snippet",60262),tasklist:f("tasklist",60263),telescope:f("telescope",60264),textSize:f("text-size",60265),threeBars:f("three-bars",60266),thumbsdown:f("thumbsdown",60267),thumbsup:f("thumbsup",60268),tools:f("tools",60269),triangleDown:f("triangle-down",60270),triangleLeft:f("triangle-left",60271),triangleRight:f("triangle-right",60272),triangleUp:f("triangle-up",60273),twitter:f("twitter",60274),unfold:f("unfold",60275),unlock:f("unlock",60276),unmute:f("unmute",60277),unverified:f("unverified",60278),verified:f("verified",60279),versions:f("versions",60280),vmActive:f("vm-active",60281),vmOutline:f("vm-outline",60282),vmRunning:f("vm-running",60283),watch:f("watch",60284),whitespace:f("whitespace",60285),wholeWord:f("whole-word",60286),window:f("window",60287),wordWrap:f("word-wrap",60288),zoomIn:f("zoom-in",60289),zoomOut:f("zoom-out",60290),listFilter:f("list-filter",60291),listFlat:f("list-flat",60292),listSelection:f("list-selection",60293),selection:f("selection",60293),listTree:f("list-tree",60294),debugBreakpointFunctionUnverified:f("debug-breakpoint-function-unverified",60295),debugBreakpointFunction:f("debug-breakpoint-function",60296),debugBreakpointFunctionDisabled:f("debug-breakpoint-function-disabled",60296),debugStackframeActive:f("debug-stackframe-active",60297),circleSmallFilled:f("circle-small-filled",60298),debugStackframeDot:f("debug-stackframe-dot",60298),terminalDecorationMark:f("terminal-decoration-mark",60298),debugStackframe:f("debug-stackframe",60299),debugStackframeFocused:f("debug-stackframe-focused",60299),debugBreakpointUnsupported:f("debug-breakpoint-unsupported",60300),symbolString:f("symbol-string",60301),debugReverseContinue:f("debug-reverse-continue",60302),debugStepBack:f("debug-step-back",60303),debugRestartFrame:f("debug-restart-frame",60304),debugAlt:f("debug-alt",60305),callIncoming:f("call-incoming",60306),callOutgoing:f("call-outgoing",60307),menu:f("menu",60308),expandAll:f("expand-all",60309),feedback:f("feedback",60310),gitPullRequestReviewer:f("git-pull-request-reviewer",60310),groupByRefType:f("group-by-ref-type",60311),ungroupByRefType:f("ungroup-by-ref-type",60312),account:f("account",60313),gitPullRequestAssignee:f("git-pull-request-assignee",60313),bellDot:f("bell-dot",60314),debugConsole:f("debug-console",60315),library:f("library",60316),output:f("output",60317),runAll:f("run-all",60318),syncIgnored:f("sync-ignored",60319),pinned:f("pinned",60320),githubInverted:f("github-inverted",60321),serverProcess:f("server-process",60322),serverEnvironment:f("server-environment",60323),pass:f("pass",60324),issueClosed:f("issue-closed",60324),stopCircle:f("stop-circle",60325),playCircle:f("play-circle",60326),record:f("record",60327),debugAltSmall:f("debug-alt-small",60328),vmConnect:f("vm-connect",60329),cloud:f("cloud",60330),merge:f("merge",60331),export:f("export",60332),graphLeft:f("graph-left",60333),magnet:f("magnet",60334),notebook:f("notebook",60335),redo:f("redo",60336),checkAll:f("check-all",60337),pinnedDirty:f("pinned-dirty",60338),passFilled:f("pass-filled",60339),circleLargeFilled:f("circle-large-filled",60340),circleLarge:f("circle-large",60341),circleLargeOutline:f("circle-large-outline",60341),combine:f("combine",60342),gather:f("gather",60342),table:f("table",60343),variableGroup:f("variable-group",60344),typeHierarchy:f("type-hierarchy",60345),typeHierarchySub:f("type-hierarchy-sub",60346),typeHierarchySuper:f("type-hierarchy-super",60347),gitPullRequestCreate:f("git-pull-request-create",60348),runAbove:f("run-above",60349),runBelow:f("run-below",60350),notebookTemplate:f("notebook-template",60351),debugRerun:f("debug-rerun",60352),workspaceTrusted:f("workspace-trusted",60353),workspaceUntrusted:f("workspace-untrusted",60354),workspaceUnknown:f("workspace-unknown",60355),terminalCmd:f("terminal-cmd",60356),terminalDebian:f("terminal-debian",60357),terminalLinux:f("terminal-linux",60358),terminalPowershell:f("terminal-powershell",60359),terminalTmux:f("terminal-tmux",60360),terminalUbuntu:f("terminal-ubuntu",60361),terminalBash:f("terminal-bash",60362),arrowSwap:f("arrow-swap",60363),copy:f("copy",60364),personAdd:f("person-add",60365),filterFilled:f("filter-filled",60366),wand:f("wand",60367),debugLineByLine:f("debug-line-by-line",60368),inspect:f("inspect",60369),layers:f("layers",60370),layersDot:f("layers-dot",60371),layersActive:f("layers-active",60372),compass:f("compass",60373),compassDot:f("compass-dot",60374),compassActive:f("compass-active",60375),azure:f("azure",60376),issueDraft:f("issue-draft",60377),gitPullRequestClosed:f("git-pull-request-closed",60378),gitPullRequestDraft:f("git-pull-request-draft",60379),debugAll:f("debug-all",60380),debugCoverage:f("debug-coverage",60381),runErrors:f("run-errors",60382),folderLibrary:f("folder-library",60383),debugContinueSmall:f("debug-continue-small",60384),beakerStop:f("beaker-stop",60385),graphLine:f("graph-line",60386),graphScatter:f("graph-scatter",60387),pieChart:f("pie-chart",60388),bracketDot:f("bracket-dot",60389),bracketError:f("bracket-error",60390),lockSmall:f("lock-small",60391),azureDevops:f("azure-devops",60392),verifiedFilled:f("verified-filled",60393),newline:f("newline",60394),layout:f("layout",60395),layoutActivitybarLeft:f("layout-activitybar-left",60396),layoutActivitybarRight:f("layout-activitybar-right",60397),layoutPanelLeft:f("layout-panel-left",60398),layoutPanelCenter:f("layout-panel-center",60399),layoutPanelJustify:f("layout-panel-justify",60400),layoutPanelRight:f("layout-panel-right",60401),layoutPanel:f("layout-panel",60402),layoutSidebarLeft:f("layout-sidebar-left",60403),layoutSidebarRight:f("layout-sidebar-right",60404),layoutStatusbar:f("layout-statusbar",60405),layoutMenubar:f("layout-menubar",60406),layoutCentered:f("layout-centered",60407),target:f("target",60408),indent:f("indent",60409),recordSmall:f("record-small",60410),errorSmall:f("error-small",60411),terminalDecorationError:f("terminal-decoration-error",60411),arrowCircleDown:f("arrow-circle-down",60412),arrowCircleLeft:f("arrow-circle-left",60413),arrowCircleRight:f("arrow-circle-right",60414),arrowCircleUp:f("arrow-circle-up",60415),layoutSidebarRightOff:f("layout-sidebar-right-off",60416),layoutPanelOff:f("layout-panel-off",60417),layoutSidebarLeftOff:f("layout-sidebar-left-off",60418),blank:f("blank",60419),heartFilled:f("heart-filled",60420),map:f("map",60421),mapHorizontal:f("map-horizontal",60421),foldHorizontal:f("fold-horizontal",60421),mapFilled:f("map-filled",60422),mapHorizontalFilled:f("map-horizontal-filled",60422),foldHorizontalFilled:f("fold-horizontal-filled",60422),circleSmall:f("circle-small",60423),bellSlash:f("bell-slash",60424),bellSlashDot:f("bell-slash-dot",60425),commentUnresolved:f("comment-unresolved",60426),gitPullRequestGoToChanges:f("git-pull-request-go-to-changes",60427),gitPullRequestNewChanges:f("git-pull-request-new-changes",60428),searchFuzzy:f("search-fuzzy",60429),commentDraft:f("comment-draft",60430),send:f("send",60431),sparkle:f("sparkle",60432),insert:f("insert",60433),mic:f("mic",60434),thumbsdownFilled:f("thumbsdown-filled",60435),thumbsupFilled:f("thumbsup-filled",60436),coffee:f("coffee",60437),snake:f("snake",60438),game:f("game",60439),vr:f("vr",60440),chip:f("chip",60441),piano:f("piano",60442),music:f("music",60443),micFilled:f("mic-filled",60444),repoFetch:f("repo-fetch",60445),copilot:f("copilot",60446),lightbulbSparkle:f("lightbulb-sparkle",60447),robot:f("robot",60448),sparkleFilled:f("sparkle-filled",60449),diffSingle:f("diff-single",60450),diffMultiple:f("diff-multiple",60451),surroundWith:f("surround-with",60452),share:f("share",60453),gitStash:f("git-stash",60454),gitStashApply:f("git-stash-apply",60455),gitStashPop:f("git-stash-pop",60456),vscode:f("vscode",60457),vscodeInsiders:f("vscode-insiders",60458),codeOss:f("code-oss",60459),runCoverage:f("run-coverage",60460),runAllCoverage:f("run-all-coverage",60461),coverage:f("coverage",60462),githubProject:f("github-project",60463),mapVertical:f("map-vertical",60464),foldVertical:f("fold-vertical",60464),mapVerticalFilled:f("map-vertical-filled",60465),foldVerticalFilled:f("fold-vertical-filled",60465),goToSearch:f("go-to-search",60466),percentage:f("percentage",60467),sortPercentage:f("sort-percentage",60467),attach:f("attach",60468),goToEditingSession:f("go-to-editing-session",60469),editSession:f("edit-session",60470),codeReview:f("code-review",60471),copilotWarning:f("copilot-warning",60472),python:f("python",60473),copilotLarge:f("copilot-large",60474),copilotWarningLarge:f("copilot-warning-large",60475),keyboardTab:f("keyboard-tab",60476),copilotBlocked:f("copilot-blocked",60477),copilotNotConnected:f("copilot-not-connected",60478),flag:f("flag",60479),lightbulbEmpty:f("lightbulb-empty",60480),symbolMethodArrow:f("symbol-method-arrow",60481),copilotUnavailable:f("copilot-unavailable",60482),repoPinned:f("repo-pinned",60483),keyboardTabAbove:f("keyboard-tab-above",60484),keyboardTabBelow:f("keyboard-tab-below",60485),gitPullRequestDone:f("git-pull-request-done",60486),mcp:f("mcp",60487),extensionsLarge:f("extensions-large",60488),layoutPanelDock:f("layout-panel-dock",60489),layoutSidebarLeftDock:f("layout-sidebar-left-dock",60490),layoutSidebarRightDock:f("layout-sidebar-right-dock",60491),copilotInProgress:f("copilot-in-progress",60492),copilotError:f("copilot-error",60493),copilotSuccess:f("copilot-success",60494),chatSparkle:f("chat-sparkle",60495),searchSparkle:f("search-sparkle",60496),editSparkle:f("edit-sparkle",60497),copilotSnooze:f("copilot-snooze",60498),sendToRemoteAgent:f("send-to-remote-agent",60499),commentDiscussionSparkle:f("comment-discussion-sparkle",60500),chatSparkleWarning:f("chat-sparkle-warning",60501),chatSparkleError:f("chat-sparkle-error",60502),collection:f("collection",60503),newCollection:f("new-collection",60504),thinking:f("thinking",60505),build:f("build",60506),commentDiscussionQuote:f("comment-discussion-quote",60507),cursor:f("cursor",60508),eraser:f("eraser",60509),fileText:f("file-text",60510),quotes:f("quotes",60512),rename:f("rename",60513),runWithDeps:f("run-with-deps",60514),debugConnected:f("debug-connected",60515),strikethrough:f("strikethrough",60516),openInProduct:f("open-in-product",60517),indexZero:f("index-zero",60518),agent:f("agent",60519),editCode:f("edit-code",60520),repoSelected:f("repo-selected",60521),skip:f("skip",60522),mergeInto:f("merge-into",60523),gitBranchChanges:f("git-branch-changes",60524),gitBranchStagedChanges:f("git-branch-staged-changes",60525),gitBranchConflicts:f("git-branch-conflicts",60526),gitBranch:f("git-branch",60527),gitBranchCreate:f("git-branch-create",60527),gitBranchDelete:f("git-branch-delete",60527),searchLarge:f("search-large",60528),terminalGitBash:f("terminal-git-bash",60529),windowActive:f("window-active",60530),forward:f("forward",60531),download:f("download",60532),clockface:f("clockface",60533),unarchive:f("unarchive",60534),sessionInProgress:f("session-in-progress",60535),collectionSmall:f("collection-small",60536),vmSmall:f("vm-small",60537),cloudSmall:f("cloud-small",60538),addSmall:f("add-small",60539),removeSmall:f("remove-small",60540),worktreeSmall:f("worktree-small",60541),worktree:f("worktree",60542),screenCut:f("screen-cut",60543),ask:f("ask",60544),openai:f("openai",60545),claude:f("claude",60546),openInWindow:f("open-in-window",60547),newSession:f("new-session",60548),cascade:f("cascade",63742),cascadeBrowser:f("cascade-browser",63743),deepwiki:f("deepwiki",63744)};var h0={dialogError:f("dialog-error","error"),dialogWarning:f("dialog-warning","warning"),dialogInfo:f("dialog-info","info"),dialogClose:f("dialog-close","close"),treeItemExpanded:f("tree-item-expanded","chevron-down"),treeFilterOnTypeOn:f("tree-filter-on-type-on","list-filter"),treeFilterOnTypeOff:f("tree-filter-on-type-off","list-selection"),treeFilterClear:f("tree-filter-clear","close"),treeItemLoading:f("tree-item-loading","loading"),menuSelection:f("menu-selection","check"),menuSubmenu:f("menu-submenu","chevron-right"),menuBarMore:f("menubar-more","more"),scrollbarButtonLeft:f("scrollbar-button-left","triangle-left"),scrollbarButtonRight:f("scrollbar-button-right","triangle-right"),scrollbarButtonUp:f("scrollbar-button-up","triangle-up"),scrollbarButtonDown:f("scrollbar-button-down","triangle-down"),toolBarMore:f("toolbar-more","more"),quickInputBack:f("quick-input-back","arrow-left"),dropDownButton:f("drop-down-button",60084),symbolCustomColor:f("symbol-customcolor",60252),exportIcon:f("export",60332),workspaceUnspecified:f("workspace-unspecified",60355),newLine:f("newline",60394),thumbsDownFilled:f("thumbsdown-filled",60435),thumbsUpFilled:f("thumbsup-filled",60436),gitFetch:f("git-fetch",60445),lightbulbSparkleAutofix:f("lightbulb-sparkle-autofix",60447),debugBreakpointPending:f("debug-breakpoint-pending",60377)},ap={...Qb,...h0};var Xb;(r=>{function o(e){return!!e&&typeof e=="object"&&typeof e.id=="string"}r.isThemeColor=o})(Xb||={});var pc;(x=>{x.iconNameSegment="[A-Za-z0-9]+",x.iconNameExpression="[A-Za-z0-9-]+",x.iconModifierExpression="~[A-Za-z]+",x.iconNameCharacter="[A-Za-z0-9~-]";let n=new RegExp(`^(${x.iconNameExpression})(${x.iconModifierExpression})?$`);function i(E){let R=n.exec(E.id);if(!R)return i(ap.error);let[,F,H]=R,qe=["codicon","codicon-"+F];return H&&qe.push("codicon-modifier-"+H.substring(1)),qe}x.asClassNameArray=i;function s(E){return i(E).join(" ")}x.asClassName=s;function a(E){return"."+i(E).join(".")}x.asCSSSelector=a;function l(E){return!!E&&typeof E=="object"&&typeof E.id=="string"&&(typeof E.color>"u"||Xb.isThemeColor(E.color))}x.isThemeIcon=l;let c=new RegExp(`^\\$\\((${x.iconNameExpression}(?:${x.iconModifierExpression})?)\\)$`);function d(E){let R=c.exec(E);if(!R)return;let[,F]=R;return{id:F}}x.fromString=d;function u(E){return{id:E}}x.fromId=u;function p(E,R){let F=E.id,H=F.lastIndexOf("~");return H!==-1&&(F=F.substring(0,H)),R&&(F=`${F}~${R}`),{id:F}}x.modify=p;function m(E){let R=E.id.lastIndexOf("~");if(R!==-1)return E.id.substring(R+1)}x.getModifier=m;function h(E,R){return E.id===R.id&&E.color?.id===R.color?.id}x.isEqual=h;function v(E){return E?.id===ap.file.id}x.isFile=v;function y(E){return E?.id===ap.folder.id}x.isFolder=y})(pc||={});var hh=new RegExp(`\\$\\(${pc.iconNameExpression}(?:${pc.iconModifierExpression})?\\)`,"g"),v0=new RegExp(`(\\\\)?${hh.source}`,"g");function Yb(o){return o.replace(v0,(r,e)=>e?r:`\\${r}`)}var O9=new RegExp(`\\\\${hh.source}`,"g");var N9=new RegExp(`(\\s)?(\\\\)?${hh.source}(\\s)?`,"g");var V9=new RegExp(`\\$\\(${pc.iconNameCharacter}+\\)`,"g");var Qt=class o{static lift(r){let e=new o(r.value,r);return e.uris=r.uris,e.baseUri=r.baseUri?P.revive(r.baseUri):void 0,e}constructor(r="",e=!1){if(this.value=r,typeof this.value!="string")throw mm("value");typeof e=="boolean"?(this.isTrusted=e,this.supportThemeIcons=!1,this.supportHtml=!1,this.supportAlertSyntax=!1):(this.isTrusted=e.isTrusted??void 0,this.supportThemeIcons=e.supportThemeIcons??!1,this.supportHtml=e.supportHtml??!1,this.supportAlertSyntax=e.supportAlertSyntax??!1)}appendText(r,e=0){return this.value+=y0(this.supportThemeIcons?Yb(r):r).replace(/([ \t]+)/g,(t,n)=>"&nbsp;".repeat(n.length)).replace(/\>/gm,"\\>").replace(/\n/g,e===1?`\\
`:`

`),this}appendMarkdown(r){return this.value+=r,this}appendCodeblock(r,e){return this.value+=`
${S0(e,r)}
`,this}appendLink(r,e,t){return this.value+="[",this.value+=this._escape(e,"]"),this.value+="](",this.value+=this._escape(String(r),")"),t&&(this.value+=` "${this._escape(this._escape(t,'"'),")")}"`),this.value+=")",this}_escape(r,e){let t=new RegExp(zr(e),"g");return r.replace(t,(n,i)=>r.charAt(i-1)!=="\\"?`\\${n}`:n)}};function y0(o){return o.replace(/[\\`*_{}[\]()#+\-!~]/g,"\\$&")}function S0(o,r){let e=o.match(/^`+/gm)?.reduce((n,i)=>n.length>i.length?n:i).length??0,t=e>=3?e+1:3;return[`${"`".repeat(t)}${r}`,o,`${"`".repeat(t)}`].join(`
`)}function Zb(o,...r){return P.from({scheme:re.command,path:o,query:r.length?encodeURIComponent(JSON.stringify(r)):void 0})}var Js=class extends T{constructor(e,t){super();this.productService=e;this.allowedExtensionsService=t;this.preferPreReleases=this.productService.quality!=="stable"}async canInstall(e){let t=this.allowedExtensionsService.isAllowed({id:e.identifier.id,publisherDisplayName:e.publisherDisplayName});if(t!==!0)return new Qt(S(1957,null,t.value));if(!await this.isExtensionPlatformCompatible(e)){let n=ze?"https://aka.ms/vscode-web-extensions-guide":"https://aka.ms/vscode-platform-specific-extensions";return new Qt(`${S(1950,null,e.displayName??e.identifier.id,this.productService.nameLong,wg(await this.getTargetPlatform()))} [${S(1952,null)}](${n})`)}return!0}async isExtensionPlatformCompatible(e){let t=await this.getTargetPlatform();return e.allTargetPlatforms.some(n=>rc(n,e.allTargetPlatforms,t))}};Js=b([g(0,ne),g(1,sn)],Js);var Qs=class extends Js{constructor(e,t,n,i,s,a,l){super(s,a);this.galleryService=e;this.telemetryService=t;this.uriIdentityService=n;this.logService=i;this.userDataProfilesService=l;this.lastReportTimestamp=0;this.installingExtensions=new Map;this.uninstallingExtensions=new Map;this._onInstallExtension=this._register(new w);this._onDidInstallExtensions=this._register(new w);this._onUninstallExtension=this._register(new w);this._onDidUninstallExtension=this._register(new w);this._onDidUpdateExtensionMetadata=this._register(new w);this.participants=[];this._register(oe(()=>{this.installingExtensions.forEach(({task:c})=>c.cancel()),this.uninstallingExtensions.forEach(c=>c.cancel()),this.installingExtensions.clear(),this.uninstallingExtensions.clear()}))}get onInstallExtension(){return this._onInstallExtension.event}get onDidInstallExtensions(){return this._onDidInstallExtensions.event}get onUninstallExtension(){return this._onUninstallExtension.event}get onDidUninstallExtension(){return this._onDidUninstallExtension.event}get onDidUpdateExtensionMetadata(){return this._onDidUpdateExtensionMetadata.event}async installFromGallery(e,t={}){try{let i=(await this.installGalleryExtensions([{extension:e,options:t}])).find(({identifier:s})=>j(s,e.identifier));if(i?.local)return i?.local;throw i?.error?i.error:new Ge(`Unknown error while installing extension ${e.identifier.id}`,"Unknown")}catch(n){throw ct(n)}}async installGalleryExtensions(e){if(!this.galleryService.isEnabled())throw new Ge(S(1954,null),"NotAllowed");let t=[],n=[];return await Promise.allSettled(e.map(async({extension:i,options:s})=>{try{let a=await this.checkAndGetCompatibleVersion(i,!!s?.installGivenVersion,!!s?.installPreReleaseVersion,s.productVersion??{version:this.productService.version,date:this.productService.date});n.push({...a,options:s})}catch(a){t.push({identifier:i.identifier,operation:2,source:i,error:a,profileLocation:s.profileLocation??this.getCurrentExtensionsManifestLocation()})}})),n.length&&t.push(...await this.installExtensions(n)),t}async uninstall(e,t){return this.logService.trace("ExtensionManagementService#uninstall",e.identifier.id),this.uninstallExtensions([{extension:e,options:t}])}async toggleApplicationScope(e,t){if(Ql(e.manifest)||e.isBuiltin)return e;if(e.isApplicationScoped){let n=await this.updateMetadata(e,{isApplicationScoped:!1},this.userDataProfilesService.defaultProfile.extensionsResource);this.uriIdentityService.extUri.isEqual(t,this.userDataProfilesService.defaultProfile.extensionsResource)||(n=await this.copyExtension(e,this.userDataProfilesService.defaultProfile.extensionsResource,t));for(let i of this.userDataProfilesService.profiles){let s=(await this.getInstalled(1,i.extensionsResource)).find(a=>j(a.identifier,e.identifier));s?this._onDidUpdateExtensionMetadata.fire({local:s,profileLocation:i.extensionsResource}):this._onDidUninstallExtension.fire({identifier:e.identifier,profileLocation:i.extensionsResource})}return n}else{let n=this.uriIdentityService.extUri.isEqual(t,this.userDataProfilesService.defaultProfile.extensionsResource)?await this.updateMetadata(e,{isApplicationScoped:!0},this.userDataProfilesService.defaultProfile.extensionsResource):await this.copyExtension(e,t,this.userDataProfilesService.defaultProfile.extensionsResource,{isApplicationScoped:!0});return this._onDidInstallExtensions.fire([{identifier:n.identifier,operation:2,local:n,profileLocation:this.userDataProfilesService.defaultProfile.extensionsResource,applicationScoped:!0}]),n}}getExtensionsControlManifest(){let e=new Date().getTime();return(!this.extensionsControlManifest||e-this.lastReportTimestamp>1e3*60*5)&&(this.extensionsControlManifest=this.updateControlCache(),this.lastReportTimestamp=e),this.extensionsControlManifest}registerParticipant(e){this.participants.push(e)}async resetPinnedStateForAllUserExtensions(e){try{await this.joinAllSettled(this.userDataProfilesService.profiles.map(async t=>{let n=await this.getInstalled(1,t.extensionsResource);await this.joinAllSettled(n.map(async i=>{i.pinned!==e&&await this.updateMetadata(i,{pinned:e},t.extensionsResource)}))}))}catch(t){throw this.logService.error("Error while resetting pinned state for all user extensions",ee(t)),t}}async installExtensions(e){let t=new Map,n=new Map,i=[],s=(c,d)=>`${Lt.create(c).toString()}-${d.toString()}`,a=(c,d,u,p)=>{let m;if(!P.isUri(d)){if(n.has(`${d.identifier.id.toLowerCase()}-${u.profileLocation.toString()}`))return;let y=this.installingExtensions.get(s(d,u.profileLocation));if(y){if(p&&this.canWaitForTask(p,y.task)){let x=y.task.identifier;this.logService.info("Waiting for already requested installing extension",x.id,p.identifier.id,u.profileLocation.toString()),y.waitingTasks.push(p),i.push(k.toPromise(k.filter(this.onDidInstallExtensions,E=>E.some(R=>j(R.identifier,x)))).then(E=>{this.logService.info("Finished waiting for already requested installing extension",x.id,p.identifier.id,u.profileLocation.toString());let R=E.find(F=>j(F.identifier,x));if(!R?.local)throw new Error(`Extension ${x.id} is not installed`);return R.local}))}return}m=this.uninstallingExtensions.get(this.getUninstallExtensionTaskKey(d.identifier,u.profileLocation))}let h=this.createInstallExtensionTask(c,d,u),v=`${Er(c.publisher,c.name)}-${u.profileLocation.toString()}`;n.set(v,{task:h,root:p,uninstallTaskToWaitFor:m}),this._onInstallExtension.fire({identifier:h.identifier,source:d,profileLocation:u.profileLocation}),this.logService.info("Installing extension:",h.identifier.id,u),P.isUri(d)||this.installingExtensions.set(s(d,u.profileLocation),{task:h,waitingTasks:[]})};try{for(let{manifest:d,extension:u,options:p}of e){let m=p.isApplicationScoped||p.isBuiltin||Ql(d),h={...p,isApplicationScoped:m,profileLocation:m?this.userDataProfilesService.defaultProfile.extensionsResource:p.profileLocation??this.getCurrentExtensionsManifestLocation(),productVersion:p.productVersion??{version:this.productService.version,date:this.productService.date}},v=P.isUri(u)?void 0:this.installingExtensions.get(s(u,h.profileLocation));v?(this.logService.info("Extension is already requested to install",v.task.identifier.id,h.profileLocation.toString()),i.push(v.task.waitUntilTaskIsFinished())):a(d,u,h,void 0)}await Promise.all([...n.values()].map(async({task:d})=>{if(d.options.donotIncludePackAndDependencies)this.logService.info("Installing the extension without checking dependencies and pack",d.identifier.id);else try{let u=this.preferPreReleases;d.options.installPreReleaseVersion?u=!0:!P.isUri(d.source)&&d.source.hasPreReleaseVersion&&(u=!1);let p=await this.getInstalled(void 0,d.options.profileLocation,d.options.productVersion),m=await this.getAllDepsAndPackExtensions(d.identifier,d.manifest,u,d.options.productVersion,p),h={...d.options,pinned:!1,installGivenVersion:!1,context:{...d.options.context,[NI]:!0}};for(let{gallery:v,manifest:y}of dt(m,({gallery:x})=>x.identifier.id)){let x=p.find(E=>j(E.identifier,v.identifier));x&&x.isApplicationScoped===!!h.isApplicationScoped||a(y,v,h,d)}}catch(u){if(P.isUri(d.source))Zn(d.manifest.extensionDependencies)&&this.logService.warn("Cannot install dependencies of extension:",d.identifier.id,u.message),Zn(d.manifest.extensionPack)&&this.logService.warn("Cannot install packed extensions of extension:",d.identifier.id,u.message);else throw this.logService.error("Error while preparing to install dependencies and extension packs of the extension:",d.identifier.id),u}}));let c=await this.getOtherProfilesToUpdateExtension([...n.values()].map(({task:d})=>d));for(let[d,u]of c)a(u.manifest,u.source,{...u.options,profileLocation:d},void 0);await this.joinAllSettled([...n.entries()].map(async([d,{task:u,uninstallTaskToWaitFor:p}])=>{let m=new Date().getTime(),h;try{if(p){this.logService.info("Waiting for existing uninstall task to complete before installing",u.identifier.id);try{await p.waitUntilTaskIsFinished(),this.logService.info("Finished waiting for uninstall task, proceeding with install",u.identifier.id)}catch(v){this.logService.info("Uninstall task failed, proceeding with install anyway",u.identifier.id,ee(v))}}h=await u.run(),await this.joinAllSettled(this.participants.map(v=>v.postInstall(h,u.source,u.options,Y.None)),"PostInstall")}catch(v){let y=ct(v);throw P.isUri(u.source)||vh(this.telemetryService,u.operation===3?"extensionGallery:update":"extensionGallery:install",{extensionData:dc(u.source),error:y,source:u.options.context?.[tc]}),t.set(d,{error:y,identifier:u.identifier,operation:u.operation,source:u.source,context:u.options.context,profileLocation:u.options.profileLocation,applicationScoped:u.options.isApplicationScoped}),this.logService.error("Error while installing the extension",u.identifier.id,ee(y),u.options.profileLocation.toString()),y}if(!P.isUri(u.source)){let v=u.operation===3,y=v?void 0:(new Date().getTime()-u.source.lastUpdated)/1e3;vh(this.telemetryService,v?"extensionGallery:update":"extensionGallery:install",{extensionData:dc(u.source),verificationStatus:u.verificationStatus,duration:new Date().getTime()-m,durationSinceUpdate:y,source:u.options.context?.[tc]})}t.set(d,{local:h,identifier:u.identifier,operation:u.operation,source:u.source,context:u.options.context,profileLocation:u.options.profileLocation,applicationScoped:h.isApplicationScoped})})),i.length&&await this.joinAllSettled(i)}catch(c){let d=(m,h,v)=>{let y=[];m.manifest.extensionDependencies?.length&&y.push(...m.manifest.extensionDependencies),m.manifest.extensionPack?.length&&y.push(...m.manifest.extensionPack);for(let x of y){if(v.includes(x.toLowerCase()))continue;v.push(x.toLowerCase());let E=t.get(`${x.toLowerCase()}-${h.toString()}`);E?.local&&(v=d(E.local,h,v))}return v},u=m=>({identifier:m.identifier,operation:2,source:m.source,context:m.options.context,profileLocation:m.options.profileLocation,error:c}),p=[];for(let[m,{task:h,root:v}]of n){let y=t.get(m);y?y.local&&v&&!t.get(`${v.identifier.id.toLowerCase()}-${h.options.profileLocation.toString()}`)?.local&&(p.push(this.createUninstallExtensionTask(y.local,{versionOnly:!0,profileLocation:h.options.profileLocation})),t.set(m,u(h))):(h.cancel(),t.set(m,u(h)))}for(let[m,{task:h}]of n){let v=t.get(m);if(!v?.local||h.options.donotIncludePackAndDependencies)continue;d(v.local,h.options.profileLocation,[v.local.identifier.id.toLowerCase()]).slice(1).some(x=>n.has(`${x.toLowerCase()}-${h.options.profileLocation.toString()}`)&&!t.get(`${x.toLowerCase()}-${h.options.profileLocation.toString()}`)?.local)&&(p.push(this.createUninstallExtensionTask(v.local,{versionOnly:!0,profileLocation:h.options.profileLocation})),t.set(m,u(h)))}p.length&&await Promise.allSettled(p.map(async m=>{try{await m.run(),this.logService.info("Rollback: Uninstalled extension",m.extension.identifier.id)}catch(h){this.logService.warn("Rollback: Error while uninstalling extension",m.extension.identifier.id,ee(h))}}))}finally{for(let{task:c}of n.values())c.source&&!P.isUri(c.source)&&this.installingExtensions.delete(s(c.source,c.options.profileLocation))}let l=[...t.values()];for(let c of l)c.local&&this.logService.info("Extension installed successfully:",c.identifier.id,c.profileLocation.toString());return this._onDidInstallExtensions.fire(l),l}async getOtherProfilesToUpdateExtension(e){let t=[],n=new He;for(let i of e)if(!(i.operation!==3||i.options.isApplicationScoped||i.options.pinned||i.options.installGivenVersion||P.isUri(i.source)))for(let s of this.userDataProfilesService.profiles){if(this.uriIdentityService.extUri.isEqual(s.extensionsResource,i.options.profileLocation))continue;let a=n.get(s.extensionsResource);a||(a=await this.getInstalled(1,s.extensionsResource),n.set(s.extensionsResource,a));let l=a.find(c=>j(c.identifier,i.identifier));l&&!l.pinned&&t.push([s.extensionsResource,i])}return t}canWaitForTask(e,t){for(let[,{task:n,waitingTasks:i}]of this.installingExtensions.entries())if(n===e&&(i.includes(t)||i.some(s=>this.canWaitForTask(s,t)))||n===t&&i[0]&&!this.canWaitForTask(e,i[0]))return!1;return!0}async joinAllSettled(e,t){let n=[],i=[],s=await Promise.allSettled(e);for(let l of s)l.status==="fulfilled"?n.push(l.value):i.push(ct(l.reason,t));if(!i.length)return n;if(i.length===1)throw i[0];let a=new Ge("","Unknown");for(let l of i)a=new Ge(a.message?`${a.message}, ${l.message}`:l.message,l.code!=="Unknown"&&l.code!=="Internal"?l.code:a.code);throw a}async getAllDepsAndPackExtensions(e,t,n,i,s){if(!this.galleryService.isEnabled())return[];let a=[],l=[],c=async(d,u)=>{a.push(d);let p=u.extensionDependencies?u.extensionDependencies.filter(h=>!s.some(v=>j(v.identifier,{id:h}))):[],m=[...p];if(u.extensionPack){let h=s.find(v=>j(v.identifier,d));for(let v of u.extensionPack)h&&h.manifest.extensionPack&&h.manifest.extensionPack.some(y=>j({id:y},{id:v}))||m.every(y=>!j({id:y},{id:v}))&&m.push(v)}if(m.length){let h=m.filter(v=>a.every(y=>!j(y,{id:v})));if(h.length){let v=await this.galleryService.getExtensions(h.map(y=>({id:y,preRelease:n})),Y.None);for(let y of v){if(a.find(R=>j(R,y.identifier)))continue;let x=p.some(R=>j({id:R},y.identifier)),E;try{E=await this.checkAndGetCompatibleVersion(y,!1,n,i)}catch(R){if(x)throw R;this.logService.info("Skipping the packed extension as it cannot be installed",y.identifier.id,ee(R));continue}l.push({gallery:E.extension,manifest:E.manifest}),await c(E.extension.identifier,E.manifest)}}}};return await c(e,t),l}async checkAndGetCompatibleVersion(e,t,n,i){let s,a=await this.getExtensionsControlManifest();if(Eb(e.identifier,a.malicious))throw new Ge(S(1953,null,e.identifier.id),"Malicious");let l=a.deprecated[e.identifier.id.toLowerCase()];if(l?.extension?.autoMigrate){if(this.logService.info(`The '${e.identifier.id}' extension is deprecated, fetching the compatible '${l.extension.id}' extension instead.`),s=(await this.galleryService.getExtensions([{id:l.extension.id,preRelease:l.extension.preRelease}],{targetPlatform:await this.getTargetPlatform(),compatible:!0,productVersion:i},Y.None))[0],!s)throw new Ge(S(1959,null,e.identifier.id,l.extension.id),"Deprecated")}else{if(await this.canInstall(e)!==!0){let d=await this.getTargetPlatform();throw new Ge(S(1950,null,e.identifier.id,this.productService.nameLong,wg(d)),"IncompatibleTargetPlatform")}if(s=await this.getCompatibleVersion(e,t,n,i),!s){let d=[];throw uc(e.properties.enabledApiProposals??[],d)?!n&&e.hasPreReleaseVersion&&e.properties.isPreReleaseVersion&&(await this.galleryService.getExtensions([e.identifier],Y.None))[0]?new Ge(S(1960,null,e.displayName??e.identifier.id),"ReleaseVersionNotFound"):new Ge(S(1958,null,e.identifier.id,this.productService.nameLong,this.productService.version),"Incompatible"):new Ge(S(1951,null,e.displayName??e.identifier.id,d[0]),"IncompatibleApi")}}this.logService.info("Getting Manifest...",s.identifier.id);let c=await this.galleryService.getManifest(s,Y.None);if(c===null)throw new Ge(`Missing manifest for extension ${s.identifier.id}`,"Invalid");if(c.version!==s.version)throw new Ge(`Cannot install '${s.identifier.id}' extension because of version mismatch in Marketplace`,"Invalid");return{extension:s,manifest:c}}async getCompatibleVersion(e,t,n,i){let s=await this.getTargetPlatform(),a=null;return!t&&e.hasPreReleaseVersion&&e.properties.isPreReleaseVersion!==n&&(a=(await this.galleryService.getExtensions([{...e.identifier,preRelease:n}],{targetPlatform:s,compatible:!0,productVersion:i},Y.None))[0]||null),!a&&await this.galleryService.isExtensionCompatible(e,n,s,i)&&(a=e),a||(t?a=(await this.galleryService.getExtensions([{...e.identifier,version:e.version}],{targetPlatform:s,compatible:!0,productVersion:i},Y.None))[0]||null:a=await this.galleryService.getCompatibleExtension(e,n,s,i)),a}getUninstallExtensionTaskKey(e,t,n){return`${e.id.toLowerCase()}${n?`-${n}`:""}@${t.toString()}`}async uninstallExtensions(e){let t=(p,m)=>this.getUninstallExtensionTaskKey(p.identifier,m.profileLocation,m.versionOnly?p.manifest.version:void 0),n=(p,m)=>{let h;for(let{task:y}of this.installingExtensions.values())if(!(y.source instanceof P)&&j(y.identifier,p.identifier)&&this.uriIdentityService.extUri.isEqual(y.options.profileLocation,m.profileLocation)){h=y;break}let v=this.createUninstallExtensionTask(p,m);this.uninstallingExtensions.set(t(v.extension,m),v),this.logService.info("Uninstalling extension from the profile:",`${p.identifier.id}@${p.manifest.version}`,m.profileLocation.toString()),this._onUninstallExtension.fire({identifier:p.identifier,profileLocation:m.profileLocation,applicationScoped:p.isApplicationScoped}),s.push({task:v,installTaskToWaitFor:h})},i=(p,m,h)=>{h?this.logService.error("Failed to uninstall extension from the profile:",`${p.identifier.id}@${p.manifest.version}`,m.profileLocation.toString(),h.message):this.logService.info("Successfully uninstalled extension from the profile",`${p.identifier.id}@${p.manifest.version}`,m.profileLocation.toString()),vh(this.telemetryService,"extensionGallery:uninstall",{extensionData:xb(p),error:h}),this._onDidUninstallExtension.fire({identifier:p.identifier,error:h?.code,profileLocation:m.profileLocation,applicationScoped:p.isApplicationScoped})},s=[],a=[],l=[],c=[],d=new He,u=async p=>{let m=d.get(p);return m||d.set(p,m=await this.getInstalled(1,p)),m};for(let{extension:p,options:m}of e){let h={...m,profileLocation:p.isApplicationScoped?this.userDataProfilesService.defaultProfile.extensionsResource:m?.profileLocation??this.getCurrentExtensionsManifestLocation()},v=this.uninstallingExtensions.get(t(p,h));if(v?(this.logService.info("Extensions is already requested to uninstall",p.identifier.id),l.push(v.waitUntilTaskIsFinished())):n(p,h),h.remove||p.isApplicationScoped){h.remove&&c.push(p);for(let y of this.userDataProfilesService.profiles){if(this.uriIdentityService.extUri.isEqual(y.extensionsResource,h.profileLocation))continue;let E=(await u(y.extensionsResource)).find(R=>j(R.identifier,p.identifier));if(E){let R={...h,profileLocation:y.extensionsResource},F=this.uninstallingExtensions.get(t(E,R));F?(this.logService.info("Extensions is already requested to uninstall",E.identifier.id),l.push(F.waitUntilTaskIsFinished())):n(E,R)}}}}try{for(let{task:p}of s.slice(0)){let m=await u(p.options.profileLocation);if(p.options.donotIncludePack)this.logService.info("Uninstalling the extension without including packed extension",`${p.extension.identifier.id}@${p.extension.manifest.version}`);else{let h=this.getAllPackExtensionsToUninstall(p.extension,m);for(let v of h)this.uninstallingExtensions.has(t(v,p.options))?this.logService.info("Extensions is already requested to uninstall",v.identifier.id):n(v,p.options)}p.options.donotCheckDependents?this.logService.info("Uninstalling the extension without checking dependents",`${p.extension.identifier.id}@${p.extension.manifest.version}`):this.checkForDependents(s.map(({task:h})=>h.extension),m,p.extension)}await this.joinAllSettled(s.map(async({task:p,installTaskToWaitFor:m})=>{try{if(m){this.logService.info("Waiting for existing install task to complete before uninstalling",p.extension.identifier.id);try{await m.waitUntilTaskIsFinished(),this.logService.info("Finished waiting for install task, proceeding with uninstall",p.extension.identifier.id)}catch(h){this.logService.info("Install task failed, proceeding with uninstall anyway",p.extension.identifier.id,ee(h))}}if(await p.run(),await this.joinAllSettled(this.participants.map(h=>h.postUninstall(p.extension,p.options,Y.None))),p.extension.identifier.uuid&&!ze)try{await this.galleryService.reportStatistic(p.extension.manifest.publisher,p.extension.manifest.name,p.extension.manifest.version,"uninstall")}catch{}}catch(h){let v=ct(h);throw i(p.extension,p.options,v),v}finally{a.push(p)}})),l.length&&await this.joinAllSettled(l);for(let{task:p}of s)i(p.extension,p.options);c.length&&await this.joinAllSettled(c.map(p=>this.deleteExtension(p)))}catch(p){let m=ct(p);for(let{task:h}of s){try{h.cancel()}catch{}a.includes(h)||i(h.extension,h.options,m)}throw m}finally{for(let{task:p}of s)this.uninstallingExtensions.delete(t(p.extension,p.options))||this.logService.warn("Uninstallation task is not found in the cache",p.extension.identifier.id)}}checkForDependents(e,t,n){for(let i of e){let s=this.getDependents(i,t);if(s.length){let a=s.filter(l=>!e.some(c=>j(c.identifier,l.identifier)));if(a.length)throw new Error(this.getDependentsErrorMessage(i,a,n))}}}getDependentsErrorMessage(e,t,n){return n===e?t.length===1?S(1961,null,n.manifest.displayName||n.manifest.name,t[0].manifest.displayName||t[0].manifest.name):t.length===2?S(1963,null,n.manifest.displayName||n.manifest.name,t[0].manifest.displayName||t[0].manifest.name,t[1].manifest.displayName||t[1].manifest.name):S(1955,null,n.manifest.displayName||n.manifest.name,t[0].manifest.displayName||t[0].manifest.name,t[1].manifest.displayName||t[1].manifest.name):t.length===1?S(1962,null,n.manifest.displayName||n.manifest.name,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name):t.length===2?S(1964,null,n.manifest.displayName||n.manifest.name,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name,t[1].manifest.displayName||t[1].manifest.name):S(1956,null,n.manifest.displayName||n.manifest.name,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name,t[1].manifest.displayName||t[1].manifest.name)}getAllPackExtensionsToUninstall(e,t,n=[]){if(n.indexOf(e)!==-1)return[];if(j(e.identifier,{id:this.productService.defaultChatAgent.extensionId}))return[];n.push(e);let i=e.manifest.extensionPack?e.manifest.extensionPack:[];if(i.length){let s=t.filter(l=>!l.isBuiltin&&i.some(c=>j({id:c},l.identifier))),a=[];for(let l of s)a.push(...this.getAllPackExtensionsToUninstall(l,t,n));return[...s,...a]}return[]}getDependents(e,t){return t.filter(n=>n.manifest.extensionDependencies&&n.manifest.extensionDependencies.some(i=>j({id:i},e.identifier)))}async updateControlCache(){try{return this.logService.trace("ExtensionManagementService.updateControlCache"),await this.galleryService.getExtensionsControlManifest()}catch(e){return this.logService.trace("ExtensionManagementService.refreshControlCache - failed to get extension control manifest",ee(e)),{malicious:[],deprecated:{},search:[]}}}};Qs=b([g(0,At),g(1,de),g(2,te),g(3,V),g(4,ne),g(5,sn),g(6,fe)],Qs);function ct(o,r){if(o instanceof Ge)return o;let e;return o instanceof Or?e=new Ge(o.message,o.code==="DownloadFailedWriting"?"DownloadFailedWriting":"Gallery"):e=new Ge(o.message,lr(o)?"Cancelled":r??"Internal"),e.stack=o.stack,e}function vh(o,r,{extensionData:e,verificationStatus:t,duration:n,error:i,source:s,durationSinceUpdate:a}){o.publicLog(r,{...e,source:s,duration:n,durationSinceUpdate:a,success:!i,errorcode:i?.code,verificationStatus:t==="Success"?"Verified":t??"Unverified"})}var fc=class{constructor(){this.barrier=new Kr}async waitUntilTaskIsFinished(){return await this.barrier.wait(),this.cancellablePromise}run(){return this.cancellablePromise||(this.cancellablePromise=Je(r=>this.doRun(r))),this.barrier.open(),this.cancellablePromise}cancel(){this.cancellablePromise||(this.cancellablePromise=Je(r=>new Promise((e,t)=>{let n=r.onCancellationRequested(()=>{n.dispose(),t(new We)})})),this.barrier.open()),this.cancellablePromise.cancel()}};function Jr(o,r){return o?P.revive(r?r.transformIncoming(o):o):void 0}function Xs(o,r){return r?r.transformOutgoingURI(o):o}function mc(o,r){r=r||js;let e=o.manifest;return{...Hs({...o,manifest:void 0},r),manifest:e}}function Ys(o,r){return o?.profileLocation?Hs(o,r??js):o}function gc(o,r){return r?_s(o,e=>e instanceof P?r.transformOutgoingURI(e):void 0):o}var cp=class{constructor(r,e){this.service=r;this.getUriTransformer=e;this.onInstallExtension=k.buffer(r.onInstallExtension,!0),this.onDidInstallExtensions=k.buffer(r.onDidInstallExtensions,!0),this.onUninstallExtension=k.buffer(r.onUninstallExtension,!0),this.onDidUninstallExtension=k.buffer(r.onDidUninstallExtension,!0),this.onDidUpdateExtensionMetadata=k.buffer(r.onDidUpdateExtensionMetadata,!0)}listen(r,e){let t=this.getUriTransformer(r);switch(e){case"onInstallExtension":return k.map(this.onInstallExtension,n=>({...n,profileLocation:n.profileLocation?Xs(n.profileLocation,t):n.profileLocation}));case"onDidInstallExtensions":return k.map(this.onDidInstallExtensions,n=>n.map(i=>({...i,local:i.local?gc(i.local,t):i.local,profileLocation:i.profileLocation?Xs(i.profileLocation,t):i.profileLocation})));case"onUninstallExtension":return k.map(this.onUninstallExtension,n=>({...n,profileLocation:n.profileLocation?Xs(n.profileLocation,t):n.profileLocation}));case"onDidUninstallExtension":return k.map(this.onDidUninstallExtension,n=>({...n,profileLocation:n.profileLocation?Xs(n.profileLocation,t):n.profileLocation}));case"onDidUpdateExtensionMetadata":return k.map(this.onDidUpdateExtensionMetadata,n=>({local:gc(n.local,t),profileLocation:Xs(n.profileLocation,t)}))}throw new Error("Invalid listen")}async call(r,e,t){let n=this.getUriTransformer(r);switch(e){case"zip":{let i=mc(t[0],n),s=await this.service.zip(i);return Xs(s,n)}case"install":return this.service.install(Jr(t[0],n),Ys(t[1],n));case"installFromLocation":return this.service.installFromLocation(Jr(t[0],n),Jr(t[1],n));case"installFromDirectory":return this.service.installFromDirectory(Jr(t[0],n),Ys(t[1],n));case"installExtensionsFromProfile":return this.service.installExtensionsFromProfile(t[0],Jr(t[1],n),Jr(t[2],n));case"getManifest":return this.service.getManifest(Jr(t[0],n));case"getTargetPlatform":return this.service.getTargetPlatform();case"installFromGallery":return this.service.installFromGallery(t[0],Ys(t[1],n));case"installGalleryExtensions":{let i=t[0];return this.service.installGalleryExtensions(i.map(({extension:s,options:a})=>({extension:s,options:Ys(a,n)??{}})))}case"uninstall":return this.service.uninstall(mc(t[0],n),Ys(t[1],n));case"uninstallExtensions":{let i=t[0];return this.service.uninstallExtensions(i.map(({extension:s,options:a})=>({extension:mc(s,n),options:Ys(a,n)})))}case"getInstalled":return(await this.service.getInstalled(t[0],Jr(t[1],n),t[2],t[3])).map(s=>gc(s,n));case"toggleApplicationScope":{let i=await this.service.toggleApplicationScope(mc(t[0],n),Jr(t[1],n));return gc(i,n)}case"copyExtensions":return this.service.copyExtensions(Jr(t[0],n),Jr(t[1],n));case"updateMetadata":{let i=await this.service.updateMetadata(mc(t[0],n),t[1],Jr(t[2],n));return gc(i,n)}case"resetPinnedStateForAllUserExtensions":return this.service.resetPinnedStateForAllUserExtensions(t[0]);case"getExtensionsControlManifest":return this.service.getExtensionsControlManifest();case"download":return this.service.download(t[0],t[1],t[2]);case"cleanUp":return this.service.cleanUp()}throw new Error("Invalid call")}};var dp=class{constructor(r){this.service=r}listen(r,e){throw new Error("Invalid listen")}call(r,e,t){switch(e){case"getConfigBasedTips":return this.service.getConfigBasedTips(P.revive(t[0]));case"getImportantExecutableBasedTips":return this.service.getImportantExecutableBasedTips();case"getOtherExecutableBasedTips":return this.service.getOtherExecutableBasedTips()}throw new Error("Invalid call")}};import*as yp from"fs";import{createWriteStream as ex,promises as tx}from"fs";var yh="end of central directory record signature not found",I0=new RegExp(yh),po=class extends Error{constructor(r,e){let t=e.message;r==="CorruptZip"&&(t=`Corrupt ZIP: ${t}`),super(t),this.type=r,this.cause=e}};function b0(o){let r=o.externalFileAttributes>>16||33188;return[448,56,7].map(e=>r&e).reduce((e,t)=>e+t,r&61440)}function rx(o){if(o instanceof po)return o;let r;return I0.test(o.message)&&(r="CorruptZip"),new po(r,o)}function x0(o,r,e,t,n,i){let s=$e(r),a=G(t,s);if(!a.startsWith(t))return Promise.reject(new Error(S(156,null,r)));let l=G(t,r),c;return i.onCancellationRequested(()=>{c?.destroy()}),Promise.resolve(tx.mkdir(a,{recursive:!0})).then(()=>new Promise((d,u)=>{if(!i.isCancellationRequested)try{c=ex(l,{mode:e}),c.once("close",()=>d()),c.once("error",u),o.once("error",u),o.pipe(c)}catch(p){u(p)}}))}function E0(o,r,e,t){let n=Je(()=>Promise.resolve()),i=0,s=t.onCancellationRequested(()=>{n.cancel(),o.close()});return new Promise((a,l)=>{let c=new Rd,d=u=>{u.isCancellationRequested||(i++,o.readEntry())};o.once("error",l),o.once("close",()=>n.then(()=>{t.isCancellationRequested||o.entryCount===i?a():l(new po("Incomplete",new Error(S(155,null,i,o.entryCount))))},l)),o.readEntry(),o.on("entry",u=>{if(t.isCancellationRequested)return;if(!e.sourcePathRegex.test(u.fileName)){d(t);return}let p=u.fileName.replace(e.sourcePathRegex,"");if(/\/$/.test(p)){let v=G(r,p);n=Je(y=>tx.mkdir(v,{recursive:!0}).then(()=>d(y)).then(void 0,l));return}let m=ix(o,u),h=b0(u);n=Je(v=>c.queue(()=>m.then(y=>x0(y,p,h,r,e,v).then(()=>d(v)))).then(null,l))})}).finally(()=>s.dispose())}async function nx(o,r=!1){let{open:e}=await import("yauzl");return new Promise((t,n)=>{e(o,r?{lazyEntries:!0}:void 0,(i,s)=>{i?n(rx(i)):t(Tr(s))})})}function ix(o,r){return new Promise((e,t)=>{o.openReadStream(r,(n,i)=>{n?t(rx(n)):e(Tr(i))})})}async function ox(o,r){let{ZipFile:e}=await import("yazl");return new Promise((t,n)=>{let i=new e;r.forEach(a=>{a.contents?i.addBuffer(typeof a.contents=="string"?Buffer.from(a.contents,"utf8"):a.contents,a.path):a.localPath&&i.addFile(a.localPath,a.path)}),i.end();let s=ex(o);i.outputStream.pipe(s),i.outputStream.once("error",n),s.once("error",n),s.once("finish",()=>t(o))})}function sx(o,r,e={},t){let n=new RegExp(e.sourcePath?`^${e.sourcePath}`:""),i=nx(o,!0);return e.overwrite&&(i=i.then(s=>ce.rm(r).then(()=>s))),i.then(s=>E0(s,r,{sourcePathRegex:n},t))}function w0(o,r){return nx(o).then(e=>new Promise((t,n)=>{e.on("entry",i=>{i.fileName===r&&ix(e,i).then(s=>t(s),s=>n(s))}),e.once("close",()=>n(new Error(S(157,null,r))))}))}function up(o,r){return w0(o,r).then(e=>new Promise((t,n)=>{let i=[];e.once("error",n),e.on("data",s=>i.push(s)),e.on("end",()=>t(Buffer.concat(i)))}))}var fo=class extends Error{constructor(e,t){super(e);this.code=t}},Qr=L("IExtensionsProfileScannerService"),Zs=class extends T{constructor(e,t,n,i,s){super();this.extensionsLocation=e;this.fileService=t;this.userDataProfilesService=n;this.uriIdentityService=i;this.logService=s;this._onAddExtensions=this._register(new w);this.onAddExtensions=this._onAddExtensions.event;this._onDidAddExtensions=this._register(new w);this.onDidAddExtensions=this._onDidAddExtensions.event;this._onRemoveExtensions=this._register(new w);this.onRemoveExtensions=this._onRemoveExtensions.event;this._onDidRemoveExtensions=this._register(new w);this.onDidRemoveExtensions=this._onDidRemoveExtensions.event;this.resourcesAccessQueueMap=new He}scanProfileExtensions(e,t){return this.withProfileExtensions(e,void 0,t)}async addExtensionsToProfile(e,t,n){let i=[],s=[];try{return await this.withProfileExtensions(t,a=>{let l=[];if(n)l.push(...a);else for(let c of a)e.some(([d])=>j(d.identifier,c.identifier)&&d.manifest.version!==c.version)?i.push(c):l.push(c);for(let[c,d]of e){let u=l.findIndex(m=>j(m.identifier,c.identifier)&&m.version===c.manifest.version),p={identifier:c.identifier,version:c.manifest.version,location:c.location,metadata:d};u===-1?(s.push(p),l.push(p)):l.splice(u,1,p)}return s.length&&this._onAddExtensions.fire({extensions:s,profileLocation:t}),i.length&&this._onRemoveExtensions.fire({extensions:i,profileLocation:t}),l}),s.length&&this._onDidAddExtensions.fire({extensions:s,profileLocation:t}),i.length&&this._onDidRemoveExtensions.fire({extensions:i,profileLocation:t}),s}catch(a){throw s.length&&this._onDidAddExtensions.fire({extensions:s,error:a,profileLocation:t}),i.length&&this._onDidRemoveExtensions.fire({extensions:i,error:a,profileLocation:t}),a}}async updateMetadata(e,t){let n=[];return await this.withProfileExtensions(t,i=>{let s=[];for(let a of i){let l=e.find(([c])=>j({id:c.identifier.id},{id:a.identifier.id})&&c.manifest.version===a.version);l&&(a.metadata={...a.metadata,...l[1]},n.push(a)),s.push(a)}return s}),n}async removeExtensionsFromProfile(e,t){let n=[];try{await this.withProfileExtensions(t,i=>{let s=[];for(let a of i)e.some(l=>j(a.identifier,l))?n.push(a):s.push(a);return n.length&&this._onRemoveExtensions.fire({extensions:n,profileLocation:t}),s}),n.length&&this._onDidRemoveExtensions.fire({extensions:n,profileLocation:t})}catch(i){throw n.length&&this._onDidRemoveExtensions.fire({extensions:n,error:i,profileLocation:t}),i}}async withProfileExtensions(e,t,n){return this.getResourceAccessQueue(e).queue(async()=>{let i=[],s;try{let a=await this.fileService.readFile(e);s=JSON.parse(a.value.toString().trim()||"[]")}catch(a){if(_e(a)!==1)throw a;if(this.uriIdentityService.extUri.isEqual(e,this.userDataProfilesService.defaultProfile.extensionsResource)&&(s=await this.migrateFromOldDefaultProfileExtensionsLocation()),!s&&n?.bailOutWhenFileNotFound)throw new fo(ee(a),"ERROR_PROFILE_NOT_FOUND")}if(s){Array.isArray(s)||this.throwInvalidConentError(e);let a=!1;for(let l of s){ax(l)||this.throwInvalidConentError(e);let c;if(ue(l.relativeLocation)&&l.relativeLocation)c=this.resolveExtensionLocation(l.relativeLocation);else if(ue(l.location)){this.logService.warn(`Extensions profile: Ignoring extension with invalid location: ${l.location}`);continue}else{c=P.revive(l.location);let u=this.toRelativePath(c);u&&(a=!0,l.relativeLocation=u)}st(l.metadata?.hasPreReleaseVersion)&&l.metadata?.preRelease&&(a=!0,l.metadata.hasPreReleaseVersion=!0);let d=l.metadata?.id??l.identifier.uuid;i.push({identifier:d?{id:l.identifier.id,uuid:d}:{id:l.identifier.id},location:c,version:l.version,metadata:l.metadata})}a&&await this.fileService.writeFile(e,U.fromString(JSON.stringify(s)))}if(t){i=t(i);let a=i.map(l=>({identifier:l.identifier,version:l.version,location:l.location.toJSON(),relativeLocation:this.toRelativePath(l.location),metadata:l.metadata}));await this.fileService.writeFile(e,U.fromString(JSON.stringify(a)))}return i})}throwInvalidConentError(e){throw new fo(`Invalid extensions content in ${e.toString()}`,"ERROR_INVALID_CONTENT")}toRelativePath(e){return this.uriIdentityService.extUri.isEqual(this.uriIdentityService.extUri.dirname(e),this.extensionsLocation)?this.uriIdentityService.extUri.basename(e):void 0}resolveExtensionLocation(e){return this.uriIdentityService.extUri.joinPath(this.extensionsLocation,e)}async migrateFromOldDefaultProfileExtensionsLocation(){return this._migrationPromise||(this._migrationPromise=(async()=>{let e=this.uriIdentityService.extUri.joinPath(this.userDataProfilesService.defaultProfile.location,"extensions.json"),t=this.uriIdentityService.extUri.joinPath(this.extensionsLocation,".init-default-profile-extensions"),n;try{n=(await this.fileService.readFile(e)).value.toString()}catch(s){if(_e(s)===1)return;throw s}this.logService.info("Migrating extensions from old default profile location",e.toString());let i;try{let s=JSON.parse(n);Array.isArray(s)&&s.every(a=>ax(a))?i=s:this.logService.warn("Skipping migrating from old default profile locaiton: Found invalid data",s)}catch(s){this.logService.error(s)}if(i)try{await this.fileService.createFile(this.userDataProfilesService.defaultProfile.extensionsResource,U.fromString(JSON.stringify(i)),{overwrite:!1}),this.logService.info("Migrated extensions from old default profile location to new location",e.toString(),this.userDataProfilesService.defaultProfile.extensionsResource.toString())}catch(s){if(_e(s)===3)this.logService.info("Migration from old default profile location to new location is done by another window",e.toString(),this.userDataProfilesService.defaultProfile.extensionsResource.toString());else throw s}try{await this.fileService.del(e)}catch(s){_e(s)!==1&&this.logService.error(s)}try{await this.fileService.del(t)}catch(s){_e(s)!==1&&this.logService.error(s)}return i})()),this._migrationPromise}getResourceAccessQueue(e){let t=this.resourcesAccessQueueMap.get(e);return t||(t=new kr,this.resourcesAccessQueueMap.set(e,t)),t}};Zs=b([g(1,W),g(2,fe),g(3,te),g(4,V)],Zs);function ax(o){let r=o;return Re(r)&&BI(r.identifier)&&(P0(r.location)||ue(r.location)&&!!r.location)&&(st(r.relativeLocation)||ue(r.relativeLocation))&&!!r.version&&ue(r.version)}function P0(o){if(!o)return!1;let r=o;return typeof r?.path=="string"&&typeof r?.scheme=="string"}function pp(o){switch(o){case 1:return S(126,null);case 2:return S(125,null);case 3:return S(127,null);case 4:return S(128,null);case 5:return S(122,null);case 6:return S(123,null);case 7:return S(120,null);case 8:return S(121,null);case 9:return S(124,null);default:return""}}function lx(o,r,e,t){try{R0(o,r,e,t)}catch(n){o.error(n?.message??n)}return r}function R0(o,r,e,t){let n=(i,s,a)=>{let l=i[s];if(ue(l)){let c=l,d=c.length;if(d>1&&c[0]==="%"&&c[d-1]==="%"){let u=c.substr(1,d-2),p=e[u];p===void 0&&t&&(p=t[u]);let m=typeof p=="string"?p:p?.message,h=t?.[u],v=typeof h=="string"?h:h?.message;if(!m){v||o.warn(`[${r.name}]: ${S(2020,null,u)}`);return}if(a&&(s==="title"||s==="category")&&v&&v!==m){let y={value:m,original:v};i[s]=y}else i[s]=m}}else if(Re(l))for(let c in l)l.hasOwnProperty(c)&&(c==="commands"?n(l,c,!0):n(l,c,a));else if(Array.isArray(l))for(let c=0;c<l.length;c++)n(l,c,a)};for(let i in r)r.hasOwnProperty(i)&&n(r,i)}var cx;(r=>{function o(e,t){if(e===t)return!0;let n=Object.keys(e),i=new Set;for(let s of Object.keys(t))i.add(s);if(n.length!==i.size)return!1;for(let s of n){if(e[s]!==t[s])return!1;i.delete(s)}return i.size===0}r.equals=o})(cx||={});var ra=L("IExtensionsScannerService"),hc=class extends T{constructor(e,t,n,i,s,a,l,c,d,u,p,m){super();this.systemExtensionsLocation=e;this.userExtensionsLocation=t;this.extensionsControlLocation=n;this.userDataProfilesService=s;this.extensionsProfileScannerService=a;this.fileService=l;this.logService=c;this.environmentService=d;this.productService=u;this.uriIdentityService=p;this.instantiationService=m;this._onDidChangeCache=this._register(new w);this.onDidChangeCache=this._onDidChangeCache.event;this.initializeDefaultProfileExtensionsPromise=void 0;this.systemExtensionsCachedScanner=this._register(this.instantiationService.createInstance(ta,i)),this.userExtensionsCachedScanner=this._register(this.instantiationService.createInstance(ta,i)),this.extensionsScanner=this._register(this.instantiationService.createInstance(ea)),this._register(this.systemExtensionsCachedScanner.onDidChangeCache(()=>this._onDidChangeCache.fire(0))),this._register(this.userExtensionsCachedScanner.onDidChangeCache(()=>this._onDidChangeCache.fire(1)))}getTargetPlatform(){return this._targetPlatformPromise||(this._targetPlatformPromise=qu(this.fileService,this.logService)),this._targetPlatformPromise}async scanAllExtensions(e,t){let[n,i]=await Promise.all([this.scanSystemExtensions(e),this.scanUserExtensions(t)]);return this.dedupExtensions(n,i,[],await this.getTargetPlatform(),!0)}async scanSystemExtensions(e){let t=[];t.push(this.scanDefaultSystemExtensions(e.language)),t.push(this.scanDevSystemExtensions(e.language,!!e.checkControlFile));let[n,i]=await Promise.all(t);return this.applyScanOptions([...n,...i],0,{pickLatest:!1})}async scanUserExtensions(e){this.logService.trace("Started scanning user extensions",e.profileLocation);let t=this.uriIdentityService.extUri.isEqual(e.profileLocation,this.userDataProfilesService.defaultProfile.extensionsResource)?{bailOutWhenFileNotFound:!0}:void 0,n=await this.createExtensionScannerInput(e.profileLocation,!0,1,e.language,!0,t,e.productVersion??this.getProductVersion()),i=e.useCache&&!n.devMode?this.userExtensionsCachedScanner:this.extensionsScanner,s;try{s=await i.scanExtensions(n)}catch(a){if(a instanceof fo&&a.code==="ERROR_PROFILE_NOT_FOUND")await this.doInitializeDefaultProfileExtensions(),s=await i.scanExtensions(n);else throw a}return s=await this.applyScanOptions(s,1,{includeInvalid:e.includeInvalid,pickLatest:!0}),this.logService.trace("Scanned user extensions:",s.length),s}async scanAllUserExtensions(e={includeInvalid:!0,includeAllVersions:!0}){let t=await this.createExtensionScannerInput(this.userExtensionsLocation,!1,1,void 0,!0,void 0,this.getProductVersion()),n=await this.extensionsScanner.scanExtensions(t);return this.applyScanOptions(n,1,{includeAllVersions:e.includeAllVersions,includeInvalid:e.includeInvalid})}async scanExtensionsUnderDevelopment(e,t){if(this.environmentService.isExtensionDevelopment&&this.environmentService.extensionDevelopmentLocationURI){let n=(await Promise.all(this.environmentService.extensionDevelopmentLocationURI.filter(i=>i.scheme===re.file).map(async i=>{let s=await this.createExtensionScannerInput(i,!1,1,t.language,!1,void 0,this.getProductVersion());return(await this.extensionsScanner.scanOneOrMultipleExtensions(s)).map(l=>(l.type=e.find(c=>j(c.identifier,l.identifier))?.type??l.type,this.extensionsScanner.validate(l,s)))}))).flat();return this.applyScanOptions(n,"development",{includeInvalid:t.includeInvalid,pickLatest:!0})}return[]}async scanExistingExtension(e,t,n){let i=await this.createExtensionScannerInput(e,!1,t,n.language,!0,void 0,this.getProductVersion()),s=await this.extensionsScanner.scanExtension(i);return!s||!n.includeInvalid&&!s.isValid?null:s}async scanOneOrMultipleExtensions(e,t,n){let i=await this.createExtensionScannerInput(e,!1,t,n.language,!0,void 0,this.getProductVersion()),s=await this.extensionsScanner.scanOneOrMultipleExtensions(i);return this.applyScanOptions(s,t,{includeInvalid:n.includeInvalid,pickLatest:!0})}async scanMultipleExtensions(e,t,n){let i=[];return await Promise.all(e.map(async s=>{let a=await this.scanOneOrMultipleExtensions(s,t,n);i.push(...a)})),this.applyScanOptions(i,t,{includeInvalid:n.includeInvalid,pickLatest:!0})}async updateManifestMetadata(e,t){let n=$(e,"package.json"),i=(await this.fileService.readFile(n)).value.toString(),s=JSON.parse(i);s.__metadata={...s.__metadata,...t},await this.fileService.writeFile($(e,"package.json"),U.fromString(JSON.stringify(s,null,"	")))}async initializeDefaultProfileExtensions(){try{await this.extensionsProfileScannerService.scanProfileExtensions(this.userDataProfilesService.defaultProfile.extensionsResource,{bailOutWhenFileNotFound:!0})}catch(e){if(e instanceof fo&&e.code==="ERROR_PROFILE_NOT_FOUND")await this.doInitializeDefaultProfileExtensions();else throw e}}async doInitializeDefaultProfileExtensions(){return this.initializeDefaultProfileExtensionsPromise||(this.initializeDefaultProfileExtensionsPromise=(async()=>{try{this.logService.info("Started initializing default profile extensions in extensions installation folder.",this.userExtensionsLocation.toString());let e=await this.scanAllUserExtensions({includeInvalid:!0});if(e.length)await this.extensionsProfileScannerService.addExtensionsToProfile(e.map(t=>[t,t.metadata]),this.userDataProfilesService.defaultProfile.extensionsResource);else try{await this.fileService.createFile(this.userDataProfilesService.defaultProfile.extensionsResource,U.fromString(JSON.stringify([])))}catch(t){_e(t)!==1&&this.logService.warn("Failed to create default profile extensions manifest in extensions installation folder.",this.userExtensionsLocation.toString(),ee(t))}this.logService.info("Completed initializing default profile extensions in extensions installation folder.",this.userExtensionsLocation.toString())}catch(e){this.logService.error(e)}finally{this.initializeDefaultProfileExtensionsPromise=void 0}})()),this.initializeDefaultProfileExtensionsPromise}async applyScanOptions(e,t,n={}){return n.includeAllVersions||(e=this.dedupExtensions(t===0?e:void 0,t===1?e:void 0,t==="development"?e:void 0,await this.getTargetPlatform(),!!n.pickLatest)),n.includeInvalid||(e=e.filter(i=>i.isValid)),e.sort((i,s)=>{let a=lt(i.location.fsPath),l=lt(s.location.fsPath);return a<l?-1:a>l?1:0})}dedupExtensions(e,t,n,i,s){let a=(c,d,u)=>{if(!u){if(c.metadata?.isApplicationScoped&&!d.metadata?.isApplicationScoped)return!1;if(!c.metadata?.isApplicationScoped&&d.metadata?.isApplicationScoped)return!0}if(c.isValid&&!d.isValid)return!1;if(c.isValid===d.isValid){if(s&&Hn(c.manifest.version,d.manifest.version))return this.logService.debug(`Skipping extension ${d.location.path} with lower version ${d.manifest.version} in favour of ${c.location.path} with version ${c.manifest.version}`),!1;if(Tb(c.manifest.version,d.manifest.version)){if(c.type===0)return this.logService.debug(`Skipping extension ${d.location.path} in favour of system extension ${c.location.path} with same version`),!1;if(c.targetPlatform===i)return this.logService.debug(`Skipping extension ${d.location.path} from different target platform ${d.targetPlatform}`),!1}}return u?this.logService.warn(`Overwriting user extension ${c.location.path} with ${d.location.path}.`):this.logService.debug(`Overwriting user extension ${c.location.path} with ${d.location.path}.`),!0},l=new iu;return e?.forEach(c=>{let d=l.get(c.identifier.id);(!d||a(d,c,!1))&&l.set(c.identifier.id,c)}),t?.forEach(c=>{let d=l.get(c.identifier.id);if(!d&&e&&c.type===0){this.logService.debug(`Skipping obsolete system extension ${c.location.path}.`);return}(!d||a(d,c,!1))&&l.set(c.identifier.id,c)}),n?.forEach(c=>{let d=l.get(c.identifier.id);(!d||a(d,c,!0))&&l.set(c.identifier.id,c),l.set(c.identifier.id,c)}),[...l.values()]}async scanDefaultSystemExtensions(e){this.logService.trace("Started scanning system extensions");let t=await this.createExtensionScannerInput(this.systemExtensionsLocation,!1,0,e,!0,void 0,this.getProductVersion()),i=await(t.devMode?this.extensionsScanner:this.systemExtensionsCachedScanner).scanExtensions(t);return this.logService.trace("Scanned system extensions:",i.length),i}async scanDevSystemExtensions(e,t){let n=this.environmentService.isBuilt?[]:this.productService.builtInExtensions;if(!n?.length)return[];this.logService.trace("Started scanning dev system extensions");let i=t?await this.getBuiltInExtensionControl():{},s=[],a=P.file(br(G(dr.asFileUri("").fsPath,"..",".build","builtInExtensions")));for(let c of n){let d=i[c.name]||"marketplace";switch(d){case"disabled":break;case"marketplace":s.push($(a,c.name));break;default:s.push(P.file(d));break}}let l=await Promise.all(s.map(async c=>this.extensionsScanner.scanExtension(await this.createExtensionScannerInput(c,!1,0,e,!0,void 0,this.getProductVersion()))));return this.logService.trace("Scanned dev system extensions:",l.length),hn(l)}async getBuiltInExtensionControl(){try{let e=await this.fileService.readFile(this.extensionsControlLocation);return JSON.parse(e.value.toString())}catch{return{}}}async createExtensionScannerInput(e,t,n,i,s,a,l){let c=await this.getTranslations(i??Cr),d=await this.getMtime(e),u=t&&!this.uriIdentityService.extUri.isEqual(e,this.userDataProfilesService.defaultProfile.extensionsResource)?this.userDataProfilesService.defaultProfile.extensionsResource:void 0,p=u?await this.getMtime(u):void 0;return new mo(e,d,u,p,t,a,n,s,l.version,l.date,this.productService.commit,!this.environmentService.isBuilt,i,c)}async getMtime(e){try{let t=await this.fileService.stat(e);if(typeof t.mtime=="number")return t.mtime}catch{}}getProductVersion(){return{version:this.productService.version,date:this.productService.date}}};hc=b([g(4,fe),g(5,Qr),g(6,W),g(7,V),g(8,X),g(9,ne),g(10,te),g(11,bt)],hc);var mo=class{constructor(r,e,t,n,i,s,a,l,c,d,u,p,m,h){this.location=r;this.mtime=e;this.applicationExtensionslocation=t;this.applicationExtensionslocationMtime=n;this.profile=i;this.profileScanOptions=s;this.type=a;this.validate=l;this.productVersion=c;this.productDate=d;this.productCommit=u;this.devMode=p;this.language=m;this.translations=h}static createNlsConfiguration(r){return{language:r.language,pseudo:r.language==="pseudo",devMode:r.devMode,translations:r.translations}}static equals(r,e){return _r(r.location,e.location)&&r.mtime===e.mtime&&_r(r.applicationExtensionslocation,e.applicationExtensionslocation)&&r.applicationExtensionslocationMtime===e.applicationExtensionslocationMtime&&r.profile===e.profile&&it(r.profileScanOptions,e.profileScanOptions)&&r.type===e.type&&r.validate===e.validate&&r.productVersion===e.productVersion&&r.productDate===e.productDate&&r.productCommit===e.productCommit&&r.devMode===e.devMode&&r.language===e.language&&cx.equals(r.translations,e.translations)}},ea=class extends T{constructor(e,t,n,i,s,a){super();this.extensionsProfileScannerService=e;this.uriIdentityService=t;this.fileService=n;this.environmentService=s;this.logService=a;this.extensionsEnabledWithApiProposalVersion=i.extensionsEnabledWithApiProposalVersion?.map(l=>l.toLowerCase())??[]}async scanExtensions(e){return e.profile?this.scanExtensionsFromProfile(e):this.scanExtensionsFromLocation(e)}async scanExtensionsFromLocation(e){let t=await this.fileService.resolve(e.location);if(!t.children?.length)return[];let n=await Promise.all(t.children.map(async i=>{if(!i.isDirectory||e.type===1&&Nn(i.resource).indexOf(".")===0)return null;let s=new mo(i.resource,e.mtime,e.applicationExtensionslocation,e.applicationExtensionslocationMtime,e.profile,e.profileScanOptions,e.type,e.validate,e.productVersion,e.productDate,e.productCommit,e.devMode,e.language,e.translations);return this.scanExtension(s)}));return hn(n).sort((i,s)=>i.location.path<s.location.path?-1:1)}async scanExtensionsFromProfile(e){let t=await this.scanExtensionsFromProfileResource(e.location,()=>!0,e);if(e.applicationExtensionslocation&&!this.uriIdentityService.extUri.isEqual(e.location,e.applicationExtensionslocation)){t=t.filter(i=>!i.metadata?.isApplicationScoped);let n=await this.scanExtensionsFromProfileResource(e.applicationExtensionslocation,i=>!!i.metadata?.isBuiltin||!!i.metadata?.isApplicationScoped,e);t.push(...n)}return t}async scanExtensionsFromProfileResource(e,t,n){let i=await this.extensionsProfileScannerService.scanProfileExtensions(e,n.profileScanOptions);if(!i.length)return[];let s=await Promise.all(i.map(async a=>{if(t(a)){let l=new mo(a.location,n.mtime,n.applicationExtensionslocation,n.applicationExtensionslocationMtime,n.profile,n.profileScanOptions,n.type,n.validate,n.productVersion,n.productDate,n.productCommit,n.devMode,n.language,n.translations);return this.scanExtension(l,a)}return null}));return hn(s)}async scanOneOrMultipleExtensions(e){try{if(await this.fileService.exists($(e.location,"package.json"))){let t=await this.scanExtension(e);return t?[t]:[]}else return await this.scanExtensions(e)}catch(t){return this.logService.error(`Error scanning extensions at ${e.location.path}:`,ee(t)),[]}}async scanExtension(e,t){let n=[],i=!0,s;try{s=await this.scanExtensionManifest(e.location)}catch(m){if(t){n.push([Dt.Error,ee(m)]),i=!1;let[h,v]=t.identifier.id.split(".");s={name:v,publisher:h,version:t.version,engines:{vscode:""}}}else return e.type!==0&&this.logService.error(m),null}s.publisher||(s.publisher=su);let a;t?a={...t.metadata,size:s.__metadata?.size}:s.__metadata&&(a={installedTimestamp:s.__metadata.installedTimestamp,size:s.__metadata.size,targetPlatform:s.__metadata.targetPlatform}),delete s.__metadata;let l=Er(s.publisher,s.name),c=a?.id?{id:l,uuid:a.id}:{id:l},d=a?.isSystem?0:e.type,u=d===0||!!a?.isBuiltin;try{s=await this.translateManifest(e.location,s,mo.createNlsConfiguration(e))}catch(m){this.logService.warn("Failed to translate manifest",ee(m))}let p={type:d,identifier:c,manifest:s,location:e.location,isBuiltin:u,targetPlatform:a?.targetPlatform??"undefined",publisherDisplayName:a?.publisherDisplayName,metadata:a,isValid:i,validations:n,preRelease:!!a?.preRelease};return e.validate&&(p=this.validate(p,e)),s.enabledApiProposals&&(!this.environmentService.isBuilt||this.extensionsEnabledWithApiProposalVersion.includes(l.toLowerCase()))&&(s.originalEnabledApiProposals=s.enabledApiProposals,s.enabledApiProposals=kI([...s.enabledApiProposals])),p}validate(e,t){let n=e.isValid,i=this.environmentService.isBuilt&&this.extensionsEnabledWithApiProposalVersion.includes(e.identifier.id.toLowerCase()),s=kb(t.productVersion,t.productDate,t.location,e.manifest,e.isBuiltin,i);for(let[a,l]of s)a===Dt.Error&&(n=!1,this.logService.error(this.formatMessage(t.location,l)));return e.isValid=n,e.validations=[...e.validations,...s],e}async scanExtensionManifest(e){let t=$(e,"package.json"),n;try{n=(await this.fileService.readFile(t)).value.toString()}catch(s){throw _e(s)!==1&&this.logService.error(this.formatMessage(e,S(2021,null,t.path,s.message))),s}let i;try{i=JSON.parse(n)}catch(s){let a=[];je(n,a);for(let l of a)this.logService.error(this.formatMessage(e,S(2023,null,t.path,l.offset,l.length,pp(l.error))));throw s}if(hi(i)!=="object"){let s=this.formatMessage(e,S(2024,null,t.path));throw this.logService.error(s),new Error(s)}return i}async translateManifest(e,t,n){let i=await this.getLocalizedMessages(e,t,n);if(i)try{let s=[],a=await this.resolveOriginalMessageBundle(i.default,s);if(s.length>0)return s.forEach(c=>{this.logService.error(this.formatMessage(e,S(2025,null,i.default?.path,pp(c.error))))}),t;if(hi(i)!=="object")return this.logService.error(this.formatMessage(e,S(2022,null,i.default?.path))),t;let l=i.values||Object.create(null);return lx(this.logService,t,l,a)}catch{}return t}async getLocalizedMessages(e,t,n){let i=$(e,"package.nls.json"),s=(d,u)=>{u.forEach(p=>{this.logService.error(this.formatMessage(e,S(2025,null,d?.path,pp(p.error))))})},a=d=>{this.logService.error(this.formatMessage(e,S(2022,null,d?.path)))},l=`${t.publisher}.${t.name}`,c=n.translations[l];if(c)try{let d=P.file(c),u=(await this.fileService.readFile(d)).value.toString(),p=[],m=je(u,p);return p.length>0?(s(d,p),{values:void 0,default:i}):hi(m)!=="object"?(a(d),{values:void 0,default:i}):{values:m.contents?m.contents.package:void 0,default:i}}catch{return{values:void 0,default:i}}else{if(!await this.fileService.exists(i))return;let u;try{u=await this.findMessageBundles(e,n)}catch{return}if(!u.localized)return{values:void 0,default:u.original};try{let p=(await this.fileService.readFile(u.localized)).value.toString(),m=[],h=je(p,m);return m.length>0?(s(u.localized,m),{values:void 0,default:u.original}):hi(h)!=="object"?(a(u.localized),{values:void 0,default:u.original}):{values:h,default:u.original}}catch{return{values:void 0,default:u.original}}}}async resolveOriginalMessageBundle(e,t){if(e)try{let n=(await this.fileService.readFile(e)).value.toString();return je(n,t)}catch{}}findMessageBundles(e,t){return new Promise((n,i)=>{let s=a=>{let l=$(e,`package.nls.${a}.json`);this.fileService.exists(l).then(c=>{c&&n({localized:l,original:$(e,"package.nls.json")});let d=a.lastIndexOf("-");d===-1?n({localized:$(e,"package.nls.json"),original:null}):(a=a.substring(0,d),s(a))})};if(t.devMode||t.pseudo||!t.language)return n({localized:$(e,"package.nls.json"),original:null});s(t.language)})}formatMessage(e,t){return`[${e.path}]: ${t}`}};ea=b([g(0,Qr),g(1,te),g(2,W),g(3,ne),g(4,X),g(5,V)],ea);var ta=class extends ea{constructor(e,t,n,i,s,a,l,c){super(n,i,s,a,l,c);this.currentProfile=e;this.userDataProfilesService=t;this.cacheValidatorThrottler=this._register(new ur(3e3));this._onDidChangeCache=this._register(new w);this.onDidChangeCache=this._onDidChangeCache.event}async scanExtensions(e){let t=this.getCacheFile(e),n=await this.readExtensionCache(t);if(this.input=e,n&&n.input&&mo.equals(n.input,this.input))return this.logService.debug("Using cached extensions scan result",e.type===0?"system":"user",e.location.toString()),this.cacheValidatorThrottler.trigger(()=>this.validateCache()),n.result.map(s=>(s.location=P.revive(s.location),s));let i=await super.scanExtensions(e);return await this.writeExtensionCache(t,{input:e,result:i}),i}async readExtensionCache(e){try{let t=await this.fileService.readFile(e),n=JSON.parse(t.value.toString());return{result:n.result,input:li(n.input)}}catch(t){_e(t)!==1&&this.logService.debug("Error while reading the extension cache file:",e.path,ee(t))}return null}async writeExtensionCache(e,t){try{await this.fileService.writeFile(e,U.fromString(JSON.stringify(t)))}catch(n){this.logService.debug("Error while writing the extension cache file:",e.path,ee(n))}}async validateCache(){if(!this.input)return;let e=this.getCacheFile(this.input),t=await this.readExtensionCache(e);if(!t)return;let n=t.result,i=JSON.parse(JSON.stringify(await super.scanExtensions(this.input)));if(!it(i,n))try{this.logService.info("Invalidating Cache",n,i),await this.fileService.del(e),this._onDidChangeCache.fire()}catch(s){this.logService.error(s)}}getCacheFile(e){let t=this.getProfile(e);return this.uriIdentityService.extUri.joinPath(t.cacheHome,e.type===0?DI:ou)}getProfile(e){return e.type===0?this.userDataProfilesService.defaultProfile:e.profile?this.uriIdentityService.extUri.isEqual(e.location,this.currentProfile.extensionsResource)?this.currentProfile:this.userDataProfilesService.profiles.find(t=>this.uriIdentityService.extUri.isEqual(e.location,t.extensionsResource))??this.currentProfile:this.userDataProfilesService.defaultProfile}};ta=b([g(1,fe),g(2,Qr),g(3,te),g(4,W),g(5,ne),g(6,X),g(7,V)],ta);var fp=class extends hc{constructor(r,e,t,n,i,s,a,l,c,d,u,p){super(r,e,$(t,".vscode-oss-dev","extensions","control.json"),n,i,s,a,l,c,d,u,p),this.translationsPromise=(async()=>{if(Rm)try{let m=await this.fileService.readFile(P.file(Rm));return JSON.parse(m.value.toString())}catch{}return Object.create(null)})()}getTranslations(r){return this.translationsPromise}};function vc(o){let r="Extract";return o instanceof po&&(o.type==="CorruptZip"?r="CorruptZip":o.type==="Incomplete"&&(r="IncompleteZip")),ct(o,r)}async function mp(o){let r;try{r=await up(o,"extension/package.json")}catch(e){throw vc(e)}try{return JSON.parse(r.toString("utf8"))}catch{throw new Ge(S(2034,null),"Invalid")}}var Jn=class extends T{constructor(e,t,n,i,s,a,l){super();this.fileService=t;this.extensionGalleryService=n;this.extensionSignatureVerificationService=i;this.telemetryService=s;this.uriIdentityService=a;this.logService=l;this.extensionsDownloadDir=e.extensionsDownloadLocation,this.extensionsTrashDir=a.extUri.joinPath(e.extensionsDownloadLocation,".trash"),this.cache=20,this.cleanUpPromise=this.cleanUp()}static{this.SignatureArchiveExtension=".sigzip"}async download(e,t,n,i){await this.cleanUpPromise;let s=await this.downloadVSIX(e,t);if(!n)return{location:s,verificationStatus:void 0};if(!e.isSigned)return{location:s,verificationStatus:"NotSigned"};let a;try{a=await this.downloadSignatureArchive(e);let l=(await this.extensionSignatureVerificationService.verify(e.identifier.id,e.version,s.fsPath,a.fsPath,i))?.code;if(l==="PackageIsInvalidZip"||l==="SignatureArchiveIsInvalidZip"){try{await this.delete(s)}catch(c){this.logService.error(c)}throw new Ge(yh,"CorruptZip")}return{location:s,verificationStatus:l}}catch(l){try{await this.delete(s)}catch(c){this.logService.error(c)}throw l}finally{if(a)try{await this.delete(a)}catch(l){this.logService.error(l)}}}async downloadVSIX(e,t){try{let n=$(this.extensionsDownloadDir,this.getName(e)),i=await this.doDownload(e,"vsix",async()=>{await this.downloadFile(e,n,s=>this.extensionGalleryService.download(e,s,t));try{await this.validate(n.fsPath,"extension/package.json")}catch(s){try{await this.fileService.del(n)}catch(a){this.logService.warn(`Error while deleting: ${n.path}`,ee(a))}throw s}},2);return i>1&&this.telemetryService.publicLog2("extensiongallery:downloadvsix:retry",{extensionId:e.identifier.id,attempts:i}),n}catch(n){throw ct(n,"Download")}}async downloadSignatureArchive(e){try{let t=$(this.extensionsDownloadDir,`${this.getName(e)}${Jn.SignatureArchiveExtension}`),n=await this.doDownload(e,"sigzip",async()=>{await this.extensionGalleryService.downloadSignatureArchive(e,t);try{await this.validate(t.fsPath,".signature.p7s")}catch(i){try{await this.fileService.del(t)}catch(s){this.logService.warn(`Error while deleting: ${t.path}`,ee(s))}throw i}},2);return n>1&&this.telemetryService.publicLog2("extensiongallery:downloadsigzip:retry",{extensionId:e.identifier.id,attempts:n}),t}catch(t){throw ct(t,"DownloadSignature")}}async downloadFile(e,t,n){if(await this.fileService.exists(t))return;if(t.scheme!==re.file){await n(t);return}let i=$(this.extensionsDownloadDir,`.${Le()}`);try{await n(i)}catch(s){try{await this.fileService.del(i)}catch{}throw s}try{await ce.rename(i.fsPath,t.fsPath,120*1e3)}catch(s){try{await this.fileService.del(i)}catch{}let a=!1;try{a=await this.fileService.exists(t)}catch{}if(a)this.logService.info("Rename failed because the file was downloaded by another source. So ignoring renaming.",e.identifier.id,t.path);else throw this.logService.info(`Rename failed because of ${ee(s)}. Deleted the file from downloaded location`,i.path),s}}async doDownload(e,t,n,i){let s=1;for(;;)try{return await n(),s}catch(a){if(s++>i)throw a;this.logService.warn(`Failed downloading ${t}. ${ee(a)}. Retry again...`,e.identifier.id)}}async validate(e,t){try{await up(e,t)}catch(n){throw vc(n)}}async delete(e){await this.cleanUpPromise;let t=this.uriIdentityService.extUri.relativePath(this.extensionsDownloadDir,e);t?await this.fileService.move(e,this.uriIdentityService.extUri.joinPath(this.extensionsTrashDir,t),!0):await this.fileService.del(e)}async cleanUp(){try{if(!await this.fileService.exists(this.extensionsDownloadDir)){this.logService.trace("Extension VSIX downloads cache dir does not exist");return}try{await this.fileService.del(this.extensionsTrashDir,{recursive:!0})}catch(t){_e(t)!==1&&this.logService.error(t)}let e=await this.fileService.resolve(this.extensionsDownloadDir,{resolveMetadata:!0});if(e.children){let t=[],n=[],i=[];for(let l of e.children)if(l.name.endsWith(Jn.SignatureArchiveExtension))i.push(l.resource);else{let c=Lt.parse(l.name);c&&n.push([c,l])}let s=Gu(n,([l])=>l),a=[];for(let l of s)l.sort((c,d)=>Xu(c[0].version,d[0].version)),t.push(...l.slice(1).map(c=>c[1].resource)),a.push(l[0][1]);a.sort((l,c)=>l.mtime-c.mtime),t.push(...a.slice(0,Math.max(0,a.length-this.cache)).map(l=>l.resource)),t.push(...i),await Ke.settled(t.map(l=>(this.logService.trace("Deleting from cache",l.path),this.fileService.del(l))))}}catch(e){this.logService.error(e)}}getName(e){return Lt.create(e).toString().toLowerCase()}};Jn=b([g(0,nt),g(1,W),g(2,At),g(3,ip),g(4,de),g(5,te),g(6,V)],Jn);import{fork as T0}from"child_process";var na=class extends T{constructor(e,t){super();this.userDataProfilesService=e;this.logService=t;this.processesLimiter=new Cl(5)}async postUninstall(e){let t=this.parseScript(e,"uninstall");t&&(this.logService.info(e.identifier.id,e.manifest.version,"Running post uninstall script"),await this.processesLimiter.queue(async()=>{try{await this.runLifecycleHook(t.script,"uninstall",t.args,!0,e),this.logService.info("Finished running post uninstall script",e.identifier.id,e.manifest.version)}catch(n){this.logService.error("Failed to run post uninstall script",e.identifier.id,e.manifest.version),this.logService.error(n)}}));try{await ce.rm(this.getExtensionStoragePath(e))}catch(n){this.logService.error("Error while removing extension storage path",e.identifier.id),this.logService.error(n)}}parseScript(e,t){let n=`vscode:${t}`;if(e.location.scheme===re.file&&e.manifest&&e.manifest.scripts&&typeof e.manifest.scripts[n]=="string"){let i=e.manifest.scripts[n].split(" ");return i.length<2||i[0]!=="node"||!i[1]?(this.logService.warn(e.identifier.id,e.manifest.version,`${n} should be a node script`),null):{script:G(e.location.fsPath,i[1]),args:i.slice(2)||[]}}return null}runLifecycleHook(e,t,n,i,s){return new Promise((a,l)=>{let c=this.start(e,t,n,s),d,u=p=>{d&&(clearTimeout(d),d=null),p?l(p):a(void 0)};c.on("error",p=>{u(_t(p)||"Unknown")}),c.on("exit",(p,m)=>{u(p?`post-${t} process exited with code ${p}`:void 0)}),i&&(d=setTimeout(()=>{d=null,c.kill(),l("timed out")},5e3))})}start(e,t,n,i){let s={silent:!0,execArgv:void 0},a=T0(e,[`--type=extension-post-${t}`,...n],s);a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8");let l=k.fromNodeEventEmitter(a.stdout,"data"),c=k.fromNodeEventEmitter(a.stderr,"data");this._register(l(p=>this.logService.info(i.identifier.id,i.manifest.version,`post-${t}`,p))),this._register(c(p=>this.logService.error(i.identifier.id,i.manifest.version,`post-${t}`,p)));let d=k.any(k.map(l,p=>({data:`%c${p}`,format:[""]}),this._store),k.map(c,p=>({data:`%c${p}`,format:["color: red"]}),this._store));return k.debounce(d,(p,m)=>p?{data:p.data+m.data,format:[...p.format,...m.format]}:{data:m.data,format:m.format},100,void 0,void 0,void 0,this._store)(p=>{console.group(i.identifier.id),console.log(p.data,...p.format),console.groupEnd()}),a}getExtensionStoragePath(e){return G(this.userDataProfilesService.defaultProfile.globalStorageHome.fsPath,e.identifier.id.toLowerCase())}};na=b([g(0,fe),g(1,V)],na);var gp=class extends T{constructor(e,t,n,i,s){super();this.userDataProfilesService=e;this.fileService=t;this.uriIdentityService=n;this.logService=s;this._register(i.onDidInstallExtensions(a=>this.onDidInstallExtensions(a))),this._register(i.onDidUninstallExtension(a=>this.onDidUnInstallExtension(a)))}onDidInstallExtensions(e){for(let t of e)t.local&&this.invalidate(t.profileLocation)}onDidUnInstallExtension(e){e.error||this.invalidate(e.profileLocation)}async invalidate(e){if(e)for(let t of this.userDataProfilesService.profiles)this.uriIdentityService.extUri.isEqual(t.extensionsResource,e)&&await this.deleteUserCacheFile(t);else await this.deleteUserCacheFile(this.userDataProfilesService.defaultProfile)}async deleteUserCacheFile(e){try{await this.fileService.del(this.uriIdentityService.extUri.joinPath(e.cacheHome,ou))}catch(t){_e(t)!==1&&this.logService.error(t)}}};var hp=class extends T{constructor(e,t,n,i,s,a,l){super();this.extensionManagementService=e;this.extensionsScannerService=t;this.userDataProfilesService=n;this.extensionsProfileScannerService=i;this.uriIdentityService=s;this.fileService=a;this.logService=l;this._onDidChangeExtensionsByAnotherSource=this._register(new w);this.onDidChangeExtensionsByAnotherSource=this._onDidChangeExtensionsByAnotherSource.event;this.allExtensions=new Map;this.extensionsProfileWatchDisposables=this._register(new Gr);this.initialize().then(null,c=>l.error("Error while initializing Extensions Watcher",ee(c)))}async initialize(){await this.extensionsScannerService.initializeDefaultProfileExtensions(),await this.onDidChangeProfiles(this.userDataProfilesService.profiles),this.registerListeners(),await this.deleteExtensionsNotInProfiles()}registerListeners(){this._register(this.userDataProfilesService.onDidChangeProfiles(e=>this.onDidChangeProfiles(e.added))),this._register(this.extensionsProfileScannerService.onAddExtensions(e=>this.onAddExtensions(e))),this._register(this.extensionsProfileScannerService.onDidAddExtensions(e=>this.onDidAddExtensions(e))),this._register(this.extensionsProfileScannerService.onRemoveExtensions(e=>this.onRemoveExtensions(e))),this._register(this.extensionsProfileScannerService.onDidRemoveExtensions(e=>this.onDidRemoveExtensions(e))),this._register(this.fileService.onDidFilesChange(e=>this.onDidFilesChange(e)))}async onDidChangeProfiles(e){try{e.length&&await Promise.all(e.map(t=>(this.extensionsProfileWatchDisposables.set(t.id,zo(this.fileService.watch(this.uriIdentityService.extUri.dirname(t.extensionsResource)),this.fileService.watch(t.extensionsResource))),this.populateExtensionsFromProfile(t.extensionsResource))))}catch(t){throw this.logService.error(t),t}}async onAddExtensions(e){for(let t of e.extensions)this.addExtensionWithKey(this.getKey(t.identifier,t.version),e.profileLocation)}async onDidAddExtensions(e){for(let t of e.extensions){let n=this.getKey(t.identifier,t.version);e.error?this.removeExtensionWithKey(n,e.profileLocation):this.addExtensionWithKey(n,e.profileLocation)}}async onRemoveExtensions(e){for(let t of e.extensions)this.removeExtensionWithKey(this.getKey(t.identifier,t.version),e.profileLocation)}async onDidRemoveExtensions(e){let t=[],n=[];for(let i of e.extensions){let s=this.getKey(i.identifier,i.version);e.error?this.addExtensionWithKey(s,e.profileLocation):(this.removeExtensionWithKey(s,e.profileLocation),this.allExtensions.has(s)||(this.logService.debug("Extension is removed from all profiles",i.identifier.id,i.version),n.push(this.extensionManagementService.scanInstalledExtensionAtLocation(i.location).then(a=>{a?t.push(a):this.logService.info("Extension not found at the location",i.location.toString())},a=>this.logService.error(a)))))}try{await Promise.all(n),t.length&&await this.deleteExtensionsNotInProfiles(t)}catch(i){this.logService.error(i)}}onDidFilesChange(e){for(let t of this.userDataProfilesService.profiles)e.contains(t.extensionsResource,0,1)&&this.onDidExtensionsProfileChange(t.extensionsResource)}async onDidExtensionsProfileChange(e){let t=[],n=[],i=await this.extensionsProfileScannerService.scanProfileExtensions(e),s=new Set,a=new Set;for(let[l,c]of this.allExtensions)c.has(e)&&a.add(l);for(let l of i){let c=this.getKey(l.identifier,l.version);s.add(c),a.has(c)||(t.push(l.identifier),this.addExtensionWithKey(c,e))}for(let l of a)if(!s.has(l)){let c=this.fromKey(l);c&&(n.push(c.identifier),this.removeExtensionWithKey(l,e))}(t.length||n.length)&&this._onDidChangeExtensionsByAnotherSource.fire({added:t.length?{extensions:t,profileLocation:e}:void 0,removed:n.length?{extensions:n,profileLocation:e}:void 0})}async populateExtensionsFromProfile(e){let t=await this.extensionsProfileScannerService.scanProfileExtensions(e);for(let n of t)this.addExtensionWithKey(this.getKey(n.identifier,n.version),e)}async deleteExtensionsNotInProfiles(e){e||(e=(await this.extensionManagementService.scanAllUserInstalledExtensions()).filter(n=>!this.allExtensions.has(this.getKey(n.identifier,n.manifest.version)))),e.length&&await this.extensionManagementService.deleteExtensions(...e)}addExtensionWithKey(e,t){let n=this.allExtensions.get(e);n||this.allExtensions.set(e,n=new ei(i=>this.uriIdentityService.extUri.getComparisonKey(i))),n.add(t)}removeExtensionWithKey(e,t){let n=this.allExtensions.get(e);n&&n.delete(t),n?.size||this.allExtensions.delete(e)}getKey(e,t){return`${on.toKey(e.id)}@${t}`}fromKey(e){let[t,n]=bb(e);return n?{identifier:{id:t},version:n}:void 0}};var oa=rr,Sh=".vsctmp",ia=class extends Qs{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h,v,y){super(e,t,v,n,m,h,y);this.environmentService=i;this.extensionsScannerService=s;this.extensionsProfileScannerService=a;this.downloadService=l;this.instantiationService=c;this.fileService=d;this.configurationService=u;this.extensionGalleryManifestService=p;this.extractingGalleryExtensions=new Map;this.knownDirectories=new ei;let x=this._register(c.createInstance(na));this.extensionsScanner=this._register(c.createInstance(yc,R=>x.postUninstall(R))),this.manifestCache=this._register(new gp(y,d,v,this,this.logService)),this.extensionsDownloader=this._register(c.createInstance(Jn));let E=this._register(new hp(this,this.extensionsScannerService,y,a,v,d,n));this._register(E.onDidChangeExtensionsByAnotherSource(R=>this.onDidChangeExtensionsFromAnotherSource(R))),this.watchForExtensionsNotInstalledBySystem()}getTargetPlatform(){return this._targetPlatformPromise||(this._targetPlatformPromise=qu(this.fileService,this.logService)),this._targetPlatformPromise}async zip(e){this.logService.trace("ExtensionManagementService#zip",e.identifier.id);let t=await this.collectFiles(e),n=await ox($(this.extensionsDownloader.extensionsDownloadDir,Le()).fsPath,t);return P.file(n)}async getManifest(e){let{location:t,cleanup:n}=await this.downloadVsix(e),i=en(t.fsPath);try{return await mp(i)}finally{await n()}}getInstalled(e,t=this.userDataProfilesService.defaultProfile.extensionsResource,n={version:this.productService.version,date:this.productService.date},i){return this.extensionsScanner.scanExtensions(e??null,t,n,i)}scanAllUserInstalledExtensions(){return this.extensionsScanner.scanAllUserExtensions()}scanInstalledExtensionAtLocation(e){return this.extensionsScanner.scanUserExtensionAtLocation(e)}async install(e,t={}){this.logService.trace("ExtensionManagementService#install",e.toString());let{location:n,cleanup:i}=await this.downloadVsix(e);try{let s=await mp(en(n.fsPath)),a=Er(s.publisher,s.name);if(s.engines&&s.engines.vscode&&!Bs(s.engines.vscode,this.productService.version,this.productService.date))throw new Error(S(2028,null,a,this.productService.version));let l=this.allowedExtensionsService.isAllowed({id:a,version:s.version,publisherDisplayName:void 0});if(l!==!0)throw new Error(S(2030,null,l.value));let d=(await this.installExtensions([{manifest:s,extension:n,options:t}])).find(({identifier:u})=>j(u,{id:a}));if(d?.local)return d.local;throw d?.error?d.error:ct(new Error(`Unknown error while installing extension ${a}`))}finally{await i()}}async installFromLocation(e,t){this.logService.trace("ExtensionManagementService#installFromLocation",e.toString());let n=await this.extensionsScanner.scanUserExtensionAtLocation(e);if(!n||!n.manifest.name||!n.manifest.version)throw new Error(`Cannot find a valid extension from the location ${e.toString()}`);return await this.addExtensionsToProfile([[n,{source:"resource"}]],t),this.logService.info("Successfully installed extension",n.identifier.id,t.toString()),n}async installFromDirectory(e,t={}){this.logService.trace("ExtensionManagementService#installFromDirectory",e.toString());let n=G(e.fsPath,"package.json"),i;try{let d=await yp.promises.readFile(n,"utf8");i=JSON.parse(d)}catch(d){throw new Error(`Cannot read extension manifest from ${n}: ${ee(d)}`)}let s=Er(i.publisher,i.name);if(i.engines&&i.engines.vscode&&!Bs(i.engines.vscode,this.productService.version,this.productService.date))throw new Error(S(2028,null,s,this.productService.version));let a=this.allowedExtensionsService.isAllowed({id:s,version:i.version,publisherDisplayName:void 0});if(a!==!0)throw new Error(S(2030,null,a.value));let c=(await this.installExtensions([{manifest:i,extension:e,options:t}])).find(({identifier:d})=>j(d,{id:s}));if(c?.local)return c.local;throw c?.error?c.error:ct(new Error(`Unknown error while installing extension ${s}`))}async installExtensionsFromProfile(e,t,n){this.logService.trace("ExtensionManagementService#installExtensionsFromProfile",e,t.toString(),n.toString());let i=(await this.getInstalled(1,t)).filter(s=>e.some(a=>j(a,s.identifier)));if(i.length){let s=await Promise.all(i.map(a=>this.extensionsScanner.scanMetadata(a,t)));await this.addExtensionsToProfile(i.map((a,l)=>[a,s[l]]),n),this.logService.info("Successfully installed extensions",i.map(a=>a.identifier.id),n.toString())}return i}async updateMetadata(e,t,n){return this.logService.trace("ExtensionManagementService#updateMetadata",e.identifier.id),t.isPreReleaseVersion&&(t.preRelease=!0,t.hasPreReleaseVersion=!0),t.isMachineScoped===!1&&(t.isMachineScoped=void 0),t.isBuiltin===!1&&(t.isBuiltin=void 0),t.pinned===!1&&(t.pinned=void 0),e=await this.extensionsScanner.updateMetadata(e,t,n),this.manifestCache.invalidate(n),this._onDidUpdateExtensionMetadata.fire({local:e,profileLocation:n}),e}deleteExtension(e){return this.extensionsScanner.deleteExtension(e,"remove")}copyExtension(e,t,n,i){return this.extensionsScanner.copyExtension(e,t,n,i)}moveExtension(e,t,n,i){return this.extensionsScanner.moveExtension(e,t,n,i)}removeExtension(e,t){return this.extensionsScanner.removeExtension(e.identifier,t)}copyExtensions(e,t){return this.extensionsScanner.copyExtensions(e,t,{version:this.productService.version,date:this.productService.date})}deleteExtensions(...e){return this.extensionsScanner.setExtensionsForRemoval(...e)}async cleanUp(){this.logService.trace("ExtensionManagementService#cleanUp");try{await this.extensionsScanner.cleanUp()}catch(e){this.logService.error(e)}}async download(e,t,n){let{location:i}=await this.downloadExtension(e,t,!n);return i}async downloadVsix(e){if(e.scheme===re.file)return{location:e,async cleanup(){}};this.logService.trace("Downloading extension from",e.toString());let t=$(this.extensionsDownloader.extensionsDownloadDir,Le());return await this.downloadService.download(e,t),this.logService.info("Downloaded extension to",t.toString()),{location:t,cleanup:async()=>{try{await this.fileService.del(t)}catch(i){this.logService.error(i)}}}}getCurrentExtensionsManifestLocation(){return this.userDataProfilesService.defaultProfile.extensionsResource}createInstallExtensionTask(e,t,n){let i;if(t instanceof P){let s=lt(t.fsPath),l=Lt.parse(s)?.targetPlatform??"undefined";i=new Lt({id:Er(e.publisher,e.name)},e.version,l)}else i=Lt.create(t);return this.instantiationService.createInstance(Sc,i,e,t,n,(s,a)=>{if(t instanceof P)return this.extractOrCopyFromURI(i,t,n,a);let l=this.extractingGalleryExtensions.get(i.toString());return l||(this.extractingGalleryExtensions.set(i.toString(),l=this.downloadAndExtractGalleryExtension(i,t,s,n,a)),l.finally(()=>this.extractingGalleryExtensions.delete(i.toString()))),l},this.extensionsScanner)}createUninstallExtensionTask(e,t){return new Ih(e,t,this.extensionsProfileScannerService)}async downloadAndExtractGalleryExtension(e,t,n,i,s){let{verificationStatus:a,location:l}=await this.downloadExtension(t,n,!i.donotVerifySignature,i.context?.[VI]);try{if(s.isCancellationRequested)throw new We;let c=await mp(l.fsPath);if(!new Lt(t.identifier,t.version).equals(new Lt({id:Er(c.publisher,c.name)},c.version)))throw new Ge(S(2029,null,t.identifier.id),"Invalid");let d=await this.extensionsScanner.extractUserExtension(e,l.fsPath,!1,s);if(a!=="Success"&&this.environmentService.isBuilt)try{await this.extensionsDownloader.delete(l)}catch(u){this.logService.warn("Error while deleting the downloaded file",l.toString(),ee(u))}return{local:d,verificationStatus:a}}catch(c){try{await this.extensionsDownloader.delete(l)}catch(d){this.logService.warn("Error while deleting the downloaded file",l.toString(),ee(d))}throw ct(c)}}async downloadExtension(e,t,n,i){if(n){let c=this.configurationService.getValue($I);n=Bt(c)?c:!0}n=!1;let{location:s,verificationStatus:a}=await this.extensionsDownloader.download(e,t,n,i),l=qI(e.private,await this.extensionGalleryManifestService.getExtensionGalleryManifest());if(a!=="Success"&&!(a==="NotSigned"&&!l)&&n&&this.environmentService.isBuilt&&await this.getTargetPlatform()!=="linux-armhf"){try{await this.extensionsDownloader.delete(s)}catch(c){this.logService.warn("Error while deleting the downloaded file",s.toString(),ee(c))}if(!a)throw new Ge(S(2033,null),"SignatureVerificationInternal");switch(a){case"PackageIntegrityCheckFailed":case"SignatureIsInvalid":case"SignatureManifestIsInvalid":case"SignatureIntegrityCheckFailed":case"EntryIsMissing":case"EntryIsTampered":case"Untrusted":case"CertificateRevoked":case"SignatureIsNotValid":case"SignatureArchiveHasTooManyEntries":case"NotSigned":throw new Ge(S(2032,null,a),"SignatureVerificationFailed")}throw new Ge(S(2032,null,a),"SignatureVerificationInternal")}return{location:s,verificationStatus:a}}async extractOrCopyFromURI(e,t,n,i){let s=en(t.fsPath);return(await yp.promises.stat(s)).isDirectory()?{local:await this.extensionsScanner.copyUserExtensionFromDirectory(e,t,Bt(n.keepExisting)?!n.keepExisting:!0,i)}:{local:await this.extensionsScanner.extractUserExtension(e,s,Bt(n.keepExisting)?!n.keepExisting:!0,i)}}async collectFiles(e){let t=async i=>{let s=await ce.readdir(i);s=s.map(c=>G(i,c));let a=await Promise.all(s.map(c=>yp.promises.stat(c))),l=Promise.resolve([]);return a.forEach((c,d)=>{let u=s[d];c.isFile()&&(l=l.then(p=>[...p,u])),c.isDirectory()&&(l=l.then(p=>t(u).then(m=>[...p,...m])))}),l};return(await t(e.location.fsPath)).map(i=>({path:`extension/${bd(e.location.fsPath,i)}`,localPath:i}))}async onDidChangeExtensionsFromAnotherSource({added:e,removed:t}){if(t){let n=e&&this.uriIdentityService.extUri.isEqual(t.profileLocation,e.profileLocation)?t.extensions.filter(i=>e.extensions.every(s=>!j(s,i))):t.extensions;for(let i of n)this.logService.info("Extensions removed from another source",i.id,t.profileLocation.toString()),this._onDidUninstallExtension.fire({identifier:i,profileLocation:t.profileLocation})}if(e){let i=(await this.getInstalled(1,e.profileLocation)).filter(s=>e.extensions.some(a=>j(a,s.identifier)));this._onDidInstallExtensions.fire(i.map(s=>(this.logService.info("Extensions added from another source",s.identifier.id,e.profileLocation.toString()),{identifier:s.identifier,local:s,profileLocation:e.profileLocation,operation:1})))}}async watchForExtensionsNotInstalledBySystem(){this._register(this.extensionsScanner.onExtract(t=>this.knownDirectories.add(t)));let e=await this.fileService.resolve(this.extensionsScannerService.userExtensionsLocation);for(let t of e.children??[])t.isDirectory&&this.knownDirectories.add(t.resource);this._register(this.fileService.watch(this.extensionsScannerService.userExtensionsLocation)),this._register(this.fileService.onDidFilesChange(t=>this.onDidFilesChange(t)))}async onDidFilesChange(e){if(!e.affects(this.extensionsScannerService.userExtensionsLocation,1))return;let t=[];for(let n of e.rawAdded){if(this.knownDirectories.has(n)||!this.uriIdentityService.extUri.isEqual(this.uriIdentityService.extUri.dirname(n),this.extensionsScannerService.userExtensionsLocation)||this.uriIdentityService.extUri.isEqual(n,this.uriIdentityService.extUri.joinPath(this.extensionsScannerService.userExtensionsLocation,".obsolete"))||this.uriIdentityService.extUri.basename(n).startsWith(".")||this.uriIdentityService.extUri.basename(n).endsWith(Sh))continue;try{if(!(await this.fileService.stat(n)).isDirectory)continue}catch(s){_e(s)!==1&&this.logService.error(s);continue}let i=await this.extensionsScanner.scanUserExtensionAtLocation(n);i&&i.installedTimestamp===void 0&&(this.knownDirectories.add(n),t.push(i))}t.length&&(await this.addExtensionsToProfile(t.map(n=>[n,void 0]),this.userDataProfilesService.defaultProfile.extensionsResource),this.logService.info("Added extensions to default profile from external source",t.map(n=>n.identifier.id)))}async addExtensionsToProfile(e,t){let n=e.map(i=>i[0]);await this.extensionsScanner.unsetExtensionsForRemoval(...n.map(i=>Lt.create(i))),await this.extensionsProfileScannerService.addExtensionsToProfile(e,t),this._onDidInstallExtensions.fire(n.map(i=>({local:i,identifier:i.identifier,operation:1,profileLocation:t})))}};ia=b([g(0,At),g(1,de),g(2,V),g(3,nt),g(4,ra),g(5,Qr),g(6,Fu),g(7,bt),g(8,W),g(9,Q),g(10,bi),g(11,ne),g(12,sn),g(13,te),g(14,fe)],ia);var yc=class extends T{constructor(e,t,n,i,s,a,l){super();this.beforeRemovingExtension=e;this.fileService=t;this.extensionsScannerService=n;this.extensionsProfileScannerService=i;this.uriIdentityService=s;this.telemetryService=a;this.logService=l;this._onExtract=this._register(new w);this.onExtract=this._onExtract.event;this.scanAllExtensionPromise=new He;this.scanUserExtensionsPromise=new He;this.obsoletedResource=$(this.extensionsScannerService.userExtensionsLocation,".obsolete"),this.obsoleteFileLimiter=new kr}async cleanUp(){await this.removeTemporarilyDeletedFolders(),await this.deleteExtensionsMarkedForRemoval(),await this.initializeExtensionSize()}async scanExtensions(e,t,n,i){try{let s=t.with({query:i}),a={includeInvalid:!0,profileLocation:t,productVersion:n,language:i},l=[];if(e===null||e===0){let c=this.scanAllExtensionPromise.get(s);c||(c=this.extensionsScannerService.scanAllExtensions({language:i},a).finally(()=>this.scanAllExtensionPromise.delete(s)),this.scanAllExtensionPromise.set(s,c)),l.push(...await c)}else if(e===1){let c=this.scanUserExtensionsPromise.get(s);c||(c=this.extensionsScannerService.scanUserExtensions(a).finally(()=>this.scanUserExtensionsPromise.delete(s)),this.scanUserExtensionsPromise.set(s,c)),l.push(...await c)}return l=e!==null?l.filter(c=>c.type===e):l,await Promise.all(l.map(c=>this.toLocalExtension(c)))}catch(s){throw ct(s,"Scanning")}}async scanAllUserExtensions(){try{let e=await this.extensionsScannerService.scanAllUserExtensions();return await Promise.all(e.map(t=>this.toLocalExtension(t)))}catch(e){throw ct(e,"Scanning")}}async scanUserExtensionAtLocation(e){try{let t=await this.extensionsScannerService.scanExistingExtension(e,1,{includeInvalid:!0});if(t)return await this.toLocalExtension(t)}catch(t){this.logService.error(t)}return null}async extractUserExtension(e,t,n,i){return this.installUserExtensionFromSource(e,n,i,async s=>{this.logService.trace(`Started extracting the extension from ${t} to ${s.fsPath}`),await sx(t,s.fsPath,{sourcePath:"extension",overwrite:!0},i),this.logService.info(`Extracted extension to ${s.fsPath}:`,e.id)})}async copyUserExtensionFromDirectory(e,t,n,i){return this.installUserExtensionFromSource(e,n,i,async s=>{this.logService.trace(`Started copying the extension from ${t.fsPath} to ${s.fsPath}`),await ce.copy(t.fsPath,s.fsPath,{preserveSymlinks:!1}),this.logService.info(`Copied extension to ${s.fsPath}:`,e.id)})}async installUserExtensionFromSource(e,t,n,i){let s=e.toString(),a=P.file(G(this.extensionsScannerService.userExtensionsLocation.fsPath,`.${Le()}`)),l=P.file(G(this.extensionsScannerService.userExtensionsLocation.fsPath,s));if(await this.fileService.exists(l)){if(!t)try{return await this.scanLocalExtension(l,1)}catch(c){this.logService.warn(`Error while scanning the existing extension at ${l.path}. Deleting the existing extension and extracting it.`,ee(c))}try{await this.deleteExtensionFromLocation(e.id,l,"removeExisting")}catch{throw new Ge(S(2027,null,l.fsPath,e.id),"Delete")}}try{if(n.isCancellationRequested)throw new We;try{await i(a)}catch(d){throw vc(d)}let c={installedTimestamp:Date.now(),targetPlatform:e.targetPlatform};try{c.size=await hu(a,this.fileService)}catch(d){this.logService.warn(`Error while getting the size of the extracted extension : ${a.fsPath}`,ee(d))}try{await this.extensionsScannerService.updateManifestMetadata(a,c)}catch(d){throw this.telemetryService.publicLog2("extension:extract",{extensionId:e.id,code:`${_e(d)}`}),ct(d,"UpdateMetadata")}if(n.isCancellationRequested)throw new We;try{this.logService.trace(`Started renaming the extension from ${a.fsPath} to ${l.fsPath}`),await this.rename(a.fsPath,l.fsPath),this.logService.info("Renamed to",l.fsPath)}catch(d){if(d.code==="ENOTEMPTY"){this.logService.info("Rename failed because extension was installed by another source. So ignoring renaming.",e.id);try{await this.fileService.del(a,{recursive:!0})}catch{}}else throw this.logService.info(`Rename failed because of ${ee(d)}. Deleted from extracted location`,a),d}this._onExtract.fire(l)}catch(c){try{await this.fileService.del(a,{recursive:!0})}catch{}throw c}return this.scanLocalExtension(l,1)}async scanMetadata(e,t){return(await this.getScannedExtension(e,t))?.metadata}async getScannedExtension(e,t){return(await this.extensionsProfileScannerService.scanProfileExtensions(t)).find(i=>j(i.identifier,e.identifier))}async updateMetadata(e,t,n){try{await this.extensionsProfileScannerService.updateMetadata([[e,t]],n)}catch(i){throw this.telemetryService.publicLog2("extension:extract",{extensionId:e.identifier.id,code:`${_e(i)}`,isProfile:!!n}),ct(i,"UpdateMetadata")}return this.scanLocalExtension(e.location,e.type,n)}async setExtensionsForRemoval(...e){let t=[];for(let i of e)await this.fileService.exists(i.location)&&t.push(i);let n=t.map(i=>Lt.create(i));await this.withRemovedExtensions(i=>n.forEach(s=>{i[s.toString()]=!0,this.logService.info("Marked extension as removed",s.toString())}))}async unsetExtensionsForRemoval(...e){try{let t=[];return await this.withRemovedExtensions(n=>e.forEach(i=>{n[i.toString()]?(t.push(!0),delete n[i.toString()]):t.push(!1)})),t}catch(t){throw ct(t,"UnsetRemoved")}}async deleteExtension(e,t){this.uriIdentityService.extUri.isEqualOrParent(e.location,this.extensionsScannerService.userExtensionsLocation)&&(await this.deleteExtensionFromLocation(e.identifier.id,e.location,t),await this.unsetExtensionsForRemoval(Lt.create(e)))}async copyExtension(e,t,n,i){let s=await this.getScannedExtension(e,t),a=await this.getScannedExtension(e,n);if(i={...s?.metadata,...i},a)if(this.uriIdentityService.extUri.isEqual(a.location,e.location))await this.extensionsProfileScannerService.updateMetadata([[e,{...a.metadata,...i}]],n);else{let l=await this.scanLocalExtension(a.location,e.type,n);await this.extensionsProfileScannerService.removeExtensionsFromProfile([l.identifier],n),await this.extensionsProfileScannerService.addExtensionsToProfile([[e,{...a.metadata,...i}]],n)}else await this.extensionsProfileScannerService.addExtensionsToProfile([[e,i]],n);return this.scanLocalExtension(e.location,e.type,n)}async moveExtension(e,t,n,i){let s=await this.getScannedExtension(e,t),a=await this.getScannedExtension(e,n);if(i={...s?.metadata,...i},a)if(this.uriIdentityService.extUri.isEqual(a.location,e.location))await this.extensionsProfileScannerService.updateMetadata([[e,{...a.metadata,...i}]],n);else{let l=await this.scanLocalExtension(a.location,e.type,n);await this.removeExtension(l.identifier,n),await this.extensionsProfileScannerService.addExtensionsToProfile([[e,{...a.metadata,...i}]],n)}else await this.extensionsProfileScannerService.addExtensionsToProfile([[e,i]],n),s&&await this.removeExtension(s.identifier,t);return this.scanLocalExtension(e.location,e.type,n)}async removeExtension(e,t){await this.extensionsProfileScannerService.removeExtensionsFromProfile([e],t)}async copyExtensions(e,t,n){let i=await this.scanExtensions(1,e,n),s=await Promise.all(i.filter(a=>!a.isApplicationScoped).map(async a=>[a,await this.scanMetadata(a,e)]));await this.extensionsProfileScannerService.addExtensionsToProfile(s,t)}async deleteExtensionFromLocation(e,t,n){this.logService.trace(`Deleting ${n} extension from disk`,e,t.fsPath);let i=this.uriIdentityService.extUri.joinPath(this.uriIdentityService.extUri.dirname(t),`${this.uriIdentityService.extUri.basename(t)}.${rn(Le()).toString(16)}${Sh}`);await this.rename(t.fsPath,i.fsPath),await this.fileService.del(i,{recursive:!0}),this.logService.info(`Deleted ${n} extension from disk`,e,t.fsPath)}withRemovedExtensions(e){return this.obsoleteFileLimiter.queue(async()=>{let t;try{t=(await this.fileService.readFile(this.obsoletedResource,"utf8")).value.toString()}catch(i){if(_e(i)!==1)throw i}let n={};if(t)try{n=JSON.parse(t)}catch{}if(e)if(e(n),Object.keys(n).length)await this.fileService.writeFile(this.obsoletedResource,U.fromString(JSON.stringify(n)));else try{await this.fileService.del(this.obsoletedResource)}catch(i){if(_e(i)!==1)throw i}return n})}async rename(e,t){try{await ce.rename(e,t,120*1e3)}catch(n){throw ct(n,"Rename")}}async scanLocalExtension(e,t,n){try{if(n){let s=(await this.extensionsScannerService.scanUserExtensions({profileLocation:n})).find(a=>this.uriIdentityService.extUri.isEqual(a.location,e));if(s)return await this.toLocalExtension(s)}else{let i=await this.extensionsScannerService.scanExistingExtension(e,t,{includeInvalid:!0});if(i)return await this.toLocalExtension(i)}throw new Ge(S(2026,null,e.path),"ScanningExtension")}catch(i){throw ct(i,"ScanningExtension")}}async toLocalExtension(e){let t;try{t=await this.fileService.resolve(e.location)}catch{}let n,i;return t?.children&&(n=t.children.find(({name:s})=>/^readme(\.txt|\.md|)$/i.test(s))?.resource,i=t.children.find(({name:s})=>/^changelog(\.txt|\.md|)$/i.test(s))?.resource),{identifier:e.identifier,type:e.type,isBuiltin:e.isBuiltin||!!e.metadata?.isBuiltin,location:e.location,manifest:e.manifest,targetPlatform:e.targetPlatform,validations:e.validations,isValid:e.isValid,readmeUrl:n,changelogUrl:i,publisherDisplayName:e.metadata?.publisherDisplayName,publisherId:e.metadata?.publisherId||null,isApplicationScoped:!!e.metadata?.isApplicationScoped,isMachineScoped:!!e.metadata?.isMachineScoped,isPreReleaseVersion:!!e.metadata?.isPreReleaseVersion,hasPreReleaseVersion:!!e.metadata?.hasPreReleaseVersion,preRelease:e.preRelease,installedTimestamp:e.metadata?.installedTimestamp,updated:!!e.metadata?.updated,pinned:!!e.metadata?.pinned,private:!!e.metadata?.private,isWorkspaceScoped:!1,source:e.metadata?.source??(e.identifier.uuid?"gallery":"vsix"),size:e.metadata?.size??0}}async initializeExtensionSize(){let e=await this.extensionsScannerService.scanAllUserExtensions();await Promise.all(e.map(async t=>{if(rd(t.metadata?.installedTimestamp)&&st(t.metadata?.size)){let n=await hu(t.location,this.fileService);await this.extensionsScannerService.updateManifestMetadata(t.location,{size:n})}}))}async deleteExtensionsMarkedForRemoval(){let e;try{e=await this.withRemovedExtensions()}catch(s){throw ct(s,"ReadRemoved")}if(Object.keys(e).length===0){this.logService.debug("No extensions are marked as removed.");return}this.logService.debug("Deleting extensions marked as removed:",Object.keys(e));let t=await this.scanAllUserExtensions(),n=new Set;for(let s of t)e[Lt.create(s).toString()]||n.add(s.identifier.id.toLowerCase());try{let s=Gu(t,a=>a.identifier);await Ke.settled(s.map(async a=>{let l=a.sort((c,d)=>Xu(c.manifest.version,d.manifest.version))[0];n.has(l.identifier.id.toLowerCase())||await this.beforeRemovingExtension(l)}))}catch(s){this.logService.error(s)}let i=t.filter(s=>s.installedTimestamp&&e[Lt.create(s).toString()]);await Promise.allSettled(i.map(s=>this.deleteExtension(s,"marked for removal")))}async removeTemporarilyDeletedFolders(){this.logService.trace("ExtensionManagementService#removeTempDeleteFolders");let e;try{e=await this.fileService.resolve(this.extensionsScannerService.userExtensionsLocation)}catch(t){_e(t)!==1&&this.logService.error(t);return}if(e?.children)try{await Promise.allSettled(e.children.map(async t=>{if(!(!t.isDirectory||!t.name.endsWith(Sh))){this.logService.trace("Deleting the temporarily deleted folder",t.resource.toString());try{await this.fileService.del(t.resource,{recursive:!0}),this.logService.trace("Deleted the temporarily deleted folder",t.resource.toString())}catch(n){_e(n)!==1&&this.logService.error(n)}}}))}catch{}}};yc=b([g(1,W),g(2,ra),g(3,Qr),g(4,te),g(5,de),g(6,V)],yc);var Sc=class extends fc{constructor(e,t,n,i,s,a,l,c,d,u,p,m){super();this.extensionKey=e;this.manifest=t;this.source=n;this.options=i;this.extractExtensionFn=s;this.extensionsScanner=a;this.uriIdentityService=l;this.galleryService=c;this.userDataProfilesService=d;this.extensionsScannerService=u;this.extensionsProfileScannerService=p;this.logService=m;this._operation=2;this.identifier=this.extensionKey.identifier}get operation(){return this.options.operation??this._operation}get verificationStatus(){return this._verificationStatus}async doRun(e){let n=(await this.extensionsScanner.scanExtensions(1,this.options.profileLocation,this.options.productVersion)).find(l=>j(l.identifier,this.identifier));n&&(this._operation=3);let i={isApplicationScoped:this.options.isApplicationScoped||n?.isApplicationScoped,isMachineScoped:this.options.isMachineScoped||n?.isMachineScoped,isBuiltin:this.options.isBuiltin||n?.isBuiltin,isSystem:n?.type===0?!0:void 0,installedTimestamp:Date.now(),pinned:this.options.installGivenVersion?!0:this.options.pinned??n?.pinned,source:this.source instanceof P?"vsix":"gallery"},s;if(this.source instanceof P){if(n&&this.extensionKey.equals(new Lt(n.identifier,n.manifest.version)))try{await this.extensionsScanner.deleteExtension(n,"existing")}catch{throw new Error(S(2031,null,this.manifest.displayName||this.manifest.name))}let l=await this.unsetIfRemoved(this.extensionKey);if(l)try{await this.extensionsScanner.deleteExtension(l,"existing")}catch{throw new Error(S(2031,null,this.manifest.displayName||this.manifest.name))}}else{if(i.id=this.source.identifier.uuid,i.publisherId=this.source.publisherId,i.publisherDisplayName=this.source.publisherDisplayName,i.targetPlatform=this.source.properties.targetPlatform,i.updated=!!n,i.private=this.source.private,i.isPreReleaseVersion=this.source.properties.isPreReleaseVersion,i.hasPreReleaseVersion=n?.hasPreReleaseVersion||this.source.properties.isPreReleaseVersion,i.preRelease=Bt(this.options.preRelease)?this.options.preRelease:this.options.installPreReleaseVersion||this.source.properties.isPreReleaseVersion||n?.preRelease,n&&n.type!==0&&n.manifest.version===this.source.version)return this.extensionsScanner.updateMetadata(n,i,this.options.profileLocation);s=await this.unsetIfRemoved(this.extensionKey)}if(e.isCancellationRequested)throw ct(new We);if(!s){let l=await this.extractExtensionFn(this.operation,e);s=l.local,this._verificationStatus=l.verificationStatus}if(this.uriIdentityService.extUri.isEqual(this.userDataProfilesService.defaultProfile.extensionsResource,this.options.profileLocation))try{await this.extensionsScannerService.initializeDefaultProfileExtensions()}catch(l){throw ct(l,"IntializeDefaultProfile")}if(e.isCancellationRequested)throw ct(new We);try{await this.extensionsProfileScannerService.addExtensionsToProfile([[s,i]],this.options.profileLocation,!s.isValid)}catch(l){throw ct(l,"AddToProfile")}let a=await this.extensionsScanner.scanLocalExtension(s.location,1,this.options.profileLocation);if(!a)throw new Ge("Cannot find the installed extension","InstalledExtensionNotFound");return this.source instanceof P&&this.updateMetadata(s,e),a}async unsetIfRemoved(e){let[t]=await this.extensionsScanner.unsetExtensionsForRemoval(e);if(t)return this.logService.info("Removed the extension from removed list:",e.id),(await this.extensionsScanner.scanAllUserExtensions()).find(i=>Lt.create(i).equals(e))}async updateMetadata(e,t){try{let[n]=await this.galleryService.getExtensions([{id:e.identifier.id,version:e.manifest.version}],t);if(n||([n]=await this.galleryService.getExtensions([{id:e.identifier.id}],t)),n){let i={id:n.identifier.uuid,publisherDisplayName:n.publisherDisplayName,publisherId:n.publisherId,isPreReleaseVersion:n.properties.isPreReleaseVersion,hasPreReleaseVersion:e.hasPreReleaseVersion||n.properties.isPreReleaseVersion,preRelease:n.properties.isPreReleaseVersion||this.options.installPreReleaseVersion};await this.extensionsScanner.updateMetadata(e,i,this.options.profileLocation)}}catch{}}};Sc=b([g(6,te),g(7,At),g(8,fe),g(9,ra),g(10,Qr),g(11,V)],Sc);var Ih=class extends fc{constructor(e,t,n){super();this.extension=e;this.options=t;this.extensionsProfileScannerService=n}doRun(e){return this.extensionsProfileScannerService.removeExtensionsFromProfile([this.extension.identifier],this.options.profileLocation)}};var Sp=L("IExtensionRecommendationNotificationService");async function Ip(o,r,e,t,n,i){let s;try{await C0(o,r,e,t,n,i)}catch(a){s=a}finally{s&&n.errorTransformer&&(s=n.errorTransformer(s)),typeof s<"u"&&e.error(s),e.end()}}async function C0(o,r,e,t,n,i){bh(i);let s=await o.open(r,{create:!1});try{bh(i);let a=0,l=0,c=n&&typeof n.length=="number"?n.length:void 0,d=U.alloc(Math.min(n.bufferSize,typeof c=="number"?c:n.bufferSize)),u=n&&typeof n.position=="number"?n.position:0,p=0;do l=await o.read(s,u,d.buffer,p,d.byteLength-p),u+=l,p+=l,a+=l,typeof c=="number"&&(c-=l),p===d.byteLength&&(await e.write(t(d)),d=U.alloc(Math.min(n.bufferSize,typeof c=="number"?c:n.bufferSize)),p=0);while(l>0&&(typeof c!="number"||c>0)&&bh(i)&&D0(a,n));if(p>0){let m=p;typeof c=="number"&&(m=Math.min(p,c)),e.write(t(d.slice(0,m)))}}catch(a){throw qn(a)}finally{await o.close(s)}}function bh(o){if(o.isCancellationRequested)throw Yn();return!0}function D0(o,r){if(typeof r?.limits?.size=="number"&&o>r.limits.size)throw Fr(S(2096,null),"EntryTooLarge");return!0}var xi=class extends T{constructor(e){super();this.logService=e;this.BUFFER_SIZE=256*1024;this._onDidChangeFileSystemProviderRegistrations=this._register(new w);this.onDidChangeFileSystemProviderRegistrations=this._onDidChangeFileSystemProviderRegistrations.event;this._onWillActivateFileSystemProvider=this._register(new w);this.onWillActivateFileSystemProvider=this._onWillActivateFileSystemProvider.event;this._onDidChangeFileSystemProviderCapabilities=this._register(new w);this.onDidChangeFileSystemProviderCapabilities=this._onDidChangeFileSystemProviderCapabilities.event;this.provider=new Map;this._onDidRunOperation=this._register(new w);this.onDidRunOperation=this._onDidRunOperation.event;this.internalOnDidFilesChange=this._register(new w);this._onDidUncorrelatedFilesChange=this._register(new w);this.onDidFilesChange=this._onDidUncorrelatedFilesChange.event;this._onDidWatchError=this._register(new w);this.onDidWatchError=this._onDidWatchError.event;this.activeWatchers=new Map;this.writeQueue=this._register(new ts)}registerProvider(e,t){if(this.provider.has(e))throw new Error(`A filesystem provider for the scheme '${e}' is already registered.`);Tn(`code/registerFilesystem/${e}`);let n=new se;return this.provider.set(e,t),this._onDidChangeFileSystemProviderRegistrations.fire({added:!0,scheme:e,provider:t}),n.add(t.onDidChangeFile(i=>{let s=new lu(i,!this.isPathCaseSensitive(t));this.internalOnDidFilesChange.fire(s),s.hasCorrelation()||this._onDidUncorrelatedFilesChange.fire(s)})),typeof t.onDidWatchError=="function"&&n.add(t.onDidWatchError(i=>this._onDidWatchError.fire(new Error(i)))),n.add(t.onDidChangeCapabilities(()=>this._onDidChangeFileSystemProviderCapabilities.fire({provider:t,scheme:e}))),oe(()=>{this._onDidChangeFileSystemProviderRegistrations.fire({added:!1,scheme:e,provider:t}),this.provider.delete(e),$t(n)})}getProvider(e){return this.provider.get(e)}async activateProvider(e){let t=[];this._onWillActivateFileSystemProvider.fire({scheme:e,join(n){t.push(n)}}),!this.provider.has(e)&&await Ke.settled(t)}async canHandleResource(e){return await this.activateProvider(e.scheme),this.hasProvider(e)}hasProvider(e){return this.provider.has(e.scheme)}hasCapability(e,t){let n=this.provider.get(e.scheme);return!!(n&&n.capabilities&t)}listCapabilities(){return ti.map(this.provider,([e,t])=>({scheme:e,capabilities:t.capabilities}))}async withProvider(e){if(!kS(e))throw new et(S(2085,null,this.resourceForError(e)),8);await this.activateProvider(e.scheme);let t=this.provider.get(e.scheme);if(!t){let n=new $r;throw n.message=S(2087,null,e.toString()),n}return t}async withReadProvider(e){let t=await this.withProvider(e);if(Gn(t)||Ar(t)||du(t))return t;throw new Error(`Filesystem provider for scheme '${e.scheme}' neither has FileReadWrite, FileReadStream nor FileOpenReadWriteClose capability which is needed for the read operation.`)}async withWriteProvider(e){let t=await this.withProvider(e);if(Gn(t)||Ar(t))return t;throw new Error(`Filesystem provider for scheme '${e.scheme}' neither has FileReadWrite nor FileOpenReadWriteClose capability which is needed for the write operation.`)}async resolve(e,t){try{return await this.doResolveFile(e,t)}catch(n){throw Yl(n)==="EntryNotFound"?new et(S(2082,null,this.resourceForError(e)),1):qn(n)}}async doResolveFile(e,t){let n=await this.withProvider(e),i=this.isPathCaseSensitive(n),s=t?.resolveTo,a=t?.resolveSingleChildDescendants,l=t?.resolveMetadata,c=await n.stat(e),d;return this.toFileStat(n,e,c,void 0,!!l,(u,p)=>(d||(d=Mr.forUris(()=>!i),d.set(e,!0),s&&d.fill(!0,s)),d.get(u.resource)||d.findSuperstr(u.resource.with({query:null,fragment:null}))?!0:u.isDirectory&&a?p===1:!1))}async toFileStat(e,t,n,i,s,a){let{providerExtUri:l}=this.getExtUri(e),c={resource:t,name:l.basename(t),isFile:(n.type&1)!==0,isDirectory:(n.type&2)!==0,isSymbolicLink:(n.type&64)!==0,mtime:n.mtime,ctime:n.ctime,size:n.size,readonly:!!((n.permissions??0)&1)||!!(e.capabilities&2048),locked:!!((n.permissions??0)&2),executable:!!((n.permissions??0)&4),etag:Ig({mtime:n.mtime,size:n.size}),children:void 0};if(c.isDirectory&&a(c,i)){try{let d=await e.readdir(t),u=await Ke.settled(d.map(async([p,m])=>{try{let h=l.joinPath(t,p),v=s?await e.stat(h):{type:m};return await this.toFileStat(e,h,v,d.length,s,a)}catch(h){return this.logService.trace(h),null}}));c.children=hn(u)}catch(d){this.logService.trace(d),c.children=[]}return c}return c}async resolveAll(e){return Ke.settled(e.map(async t=>{try{return{stat:await this.doResolveFile(t.resource,t.options),success:!0}}catch(n){return this.logService.trace(n),{stat:void 0,success:!1}}}))}async stat(e){let t=await this.withProvider(e),n=await t.stat(e);return this.toFileStat(t,e,n,void 0,!0,()=>!1)}async realpath(e){let t=await this.withProvider(e);if(LI(t)){let n=await t.realpath(e);return e.with({path:n})}}async exists(e){let t=await this.withProvider(e);try{return!!await t.stat(e)}catch{return!1}}async canCreateFile(e,t){try{await this.doValidateCreateFile(e,t)}catch(n){return n}return!0}async doValidateCreateFile(e,t){if(!t?.overwrite&&await this.exists(e))throw new et(S(2078,null,this.resourceForError(e)),3,t)}async createFile(e,t=U.fromString(""),n){await this.doValidateCreateFile(e,n);let i=await this.writeFile(e,t);return this._onDidRunOperation.fire(new $n(e,0,i)),i}async writeFile(e,t,n){let i=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),{providerExtUri:s}=this.getExtUri(i),a=n;if(Sg(i)&&!a?.atomic){let l=i.enforceAtomicWriteFile?.(e);l&&(a={...n,atomic:l})}try{let{stat:l,buffer:c}=await this.validateWriteFile(i,e,t,a);l||await this.mkdirp(i,s.dirname(e)),c||(c=await this.peekBufferForWriting(i,t)),!Gn(i)||Ar(i)&&c instanceof U||Ar(i)&&Sg(i)&&a?.atomic?await this.doWriteUnbuffered(i,e,a,c):await this.doWriteBuffered(i,e,a,c instanceof U?qS(c):c),this._onDidRunOperation.fire(new $n(e,4))}catch(l){throw new et(S(2077,null,this.resourceForError(e),qn(l).toString()),_e(l),a)}return this.resolve(e,{resolveMetadata:!0})}async peekBufferForWriting(e,t){let n;if(Ar(e)&&!(t instanceof U))if(Dl(t)){let i=await WS(t,3);i.ended?n=U.concat(i.buffer):n=i}else n=VS(t,i=>U.concat(i),3);else n=t;return n}async validateWriteFile(e,t,n,i){let s=!!i?.unlock;if(s&&!(e.capabilities&8192))throw new Error(S(2095,null,this.resourceForError(t)));if(i?.append&&!UI(e))throw new et(S(2074,null,this.resourceForError(t)),6);if(!!i?.atomic){if(!(e.capabilities&32768))throw new Error(S(2093,null,this.resourceForError(t)));if(!(e.capabilities&2))throw new Error(S(2094,null,this.resourceForError(t)));if(s)throw new Error(S(2092,null,this.resourceForError(t)))}let l;try{l=await e.stat(t)}catch{return Object.create(null)}if((l.type&2)!==0)throw new et(S(2080,null,this.resourceForError(t)),0,i);this.throwIfFileIsReadonly(t,l);let c;if(typeof i?.mtime=="number"&&typeof i.etag=="string"&&i.etag!==pu&&typeof l.mtime=="number"&&typeof l.size=="number"&&i.mtime<l.mtime&&i.etag!==Ig({mtime:i.mtime,size:l.size})){if(c=await this.peekBufferForWriting(e,n),c instanceof U&&c.byteLength===l.size)try{let{value:d}=await this.readFile(t,{limits:{size:l.size}});if(c.equals(d))return{stat:l,buffer:c}}catch{}throw new et(S(2081,null),3,i)}return{stat:l,buffer:c}}async readFile(e,t,n){let i=await this.withReadProvider(e);return t?.atomic?this.doReadFileAtomic(i,e,t,n):this.doReadFile(i,e,t,n)}async doReadFileAtomic(e,t,n,i){return new Promise((s,a)=>{this.writeQueue.queueFor(t,async()=>{try{let l=await this.doReadFile(e,t,n,i);s(l)}catch(l){a(l)}},this.getExtUri(e).providerExtUri)})}async doReadFile(e,t,n,i){let s=await this.doReadFileStream(e,t,{...n,preferUnbuffered:!0},i);return{...s,value:await En(s.value)}}async readFileStream(e,t,n){let i=await this.withReadProvider(e);return this.doReadFileStream(i,e,t,n)}async doReadFileStream(e,t,n,i){let s=new mt(i),a=n;uu(e)&&e.enforceAtomicReadFile?.(t)&&(a={...n,atomic:!0});let l=this.validateReadFile(t,a).then(d=>d,d=>{throw s.dispose(!0),d}),c;try{return typeof a?.etag=="string"&&a.etag!==pu&&await l,a?.atomic&&uu(e)||!(Gn(e)||du(e))||Ar(e)&&a?.preferUnbuffered?c=this.readFileUnbuffered(e,t,a):du(e)?c=this.readFileStreamed(e,t,s.token,a):c=this.readFileBuffered(e,t,s.token,a),c.on("end",()=>s.dispose()),c.on("error",()=>s.dispose()),{...await l,value:c}}catch(d){throw c&&await kd(c),this.restoreReadError(d,t,a)}}restoreReadError(e,t,n){let i=S(2075,null,this.resourceForError(t),qn(e).toString());return e instanceof Ss?new Ss(i,e.stat,n):e instanceof ys?new ys(i,e.fileOperationResult,e.size,e.options):new et(i,_e(e),n)}readFileStreamed(e,t,n,i=Object.create(null)){let s=e.readFileStream(t,i,n);return Ud(s,{data:a=>a instanceof U?a:U.wrap(a),error:a=>this.restoreReadError(a,t,i)},a=>U.concat(a))}readFileBuffered(e,t,n,i=Object.create(null)){let s=jS();return Ip(e,t,s,a=>a,{...i,bufferSize:this.BUFFER_SIZE,errorTransformer:a=>this.restoreReadError(a,t,i)},n),s}readFileUnbuffered(e,t,n){let i=Vn(s=>U.concat(s));return(async()=>{try{let s;n?.atomic&&uu(e)?s=await e.readFile(t,{atomic:!0}):s=await e.readFile(t),typeof n?.position=="number"&&(s=s.slice(n.position)),typeof n?.length=="number"&&(s=s.slice(0,n.length)),this.validateReadFileLimits(t,s.byteLength,n),i.end(U.wrap(s))}catch(s){i.error(s),i.end()}})(),i}async validateReadFile(e,t){let n=await this.resolve(e,{resolveMetadata:!0});if(n.isDirectory)throw new et(S(2079,null,this.resourceForError(e)),0,t);if(typeof t?.etag=="string"&&t.etag!==pu&&t.etag===n.etag)throw new Ss(S(2083,null),n,t);return this.validateReadFileLimits(e,n.size,t),n}validateReadFileLimits(e,t,n){if(typeof n?.limits?.size=="number"&&t>n.limits.size)throw new ys(S(2084,null,this.resourceForError(e)),7,t,n)}async canMove(e,t,n){return this.doCanMoveCopy(e,t,"move",n)}async canCopy(e,t,n){return this.doCanMoveCopy(e,t,"copy",n)}async doCanMoveCopy(e,t,n,i){if(e.toString()!==t.toString())try{let s=n==="move"?this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e):await this.withReadProvider(e),a=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t);await this.doValidateMoveCopy(s,e,a,t,n,i)}catch(s){return s}return!0}async move(e,t,n){let i=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t),a=await this.doMoveCopy(i,e,s,t,"move",!!n),l=await this.resolve(t,{resolveMetadata:!0});return this._onDidRunOperation.fire(new $n(e,a==="move"?2:3,l)),l}async copy(e,t,n){let i=await this.withReadProvider(e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t),a=await this.doMoveCopy(i,e,s,t,"copy",!!n),l=await this.resolve(t,{resolveMetadata:!0});return this._onDidRunOperation.fire(new $n(e,a==="copy"?3:2,l)),l}async doMoveCopy(e,t,n,i,s,a){if(t.toString()===i.toString())return s;let{exists:l,isSameResourceWithDifferentPathCase:c}=await this.doValidateMoveCopy(e,t,n,i,s,a);if(l&&!c&&a&&await this.del(i,{recursive:!0}),await this.mkdirp(n,this.getExtUri(n).providerExtUri.dirname(i)),s==="copy"){if(e===n&&Xl(e))await e.copy(t,i,{overwrite:a});else{let d=await this.resolve(t);d.isDirectory?await this.doCopyFolder(e,d,n,i):await this.doCopyFile(e,t,n,i)}return s}else return e===n?(await e.rename(t,i,{overwrite:a}),s):(await this.doMoveCopy(e,t,n,i,"copy",a),await this.del(t,{recursive:!0}),"copy")}async doCopyFile(e,t,n,i){if(Gn(e)&&Gn(n))return this.doPipeBuffered(e,t,n,i);if(Gn(e)&&Ar(n))return this.doPipeBufferedToUnbuffered(e,t,n,i);if(Ar(e)&&Gn(n))return this.doPipeUnbufferedToBuffered(e,t,n,i);if(Ar(e)&&Ar(n))return this.doPipeUnbuffered(e,t,n,i)}async doCopyFolder(e,t,n,i){await n.mkdir(i),Array.isArray(t.children)&&await Ke.settled(t.children.map(async s=>{let a=this.getExtUri(n).providerExtUri.joinPath(i,s.name);return s.isDirectory?this.doCopyFolder(e,await this.resolve(s.resource),n,a):this.doCopyFile(e,s.resource,n,a)}))}async doValidateMoveCopy(e,t,n,i,s,a){let l=!1;if(e===n){let{providerExtUri:d,isPathCaseSensitive:u}=this.getExtUri(e);if(u||(l=d.isEqual(t,i)),l&&s==="copy")throw new Error(S(2088,null,this.resourceForError(t),this.resourceForError(i)));if(!l&&d.isEqualOrParent(i,t))throw new Error(S(2089,null,this.resourceForError(t),this.resourceForError(i)))}let c=await this.exists(i);if(c&&!l){if(!a)throw new et(S(2090,null,this.resourceForError(t),this.resourceForError(i)),4);if(e===n){let{providerExtUri:d}=this.getExtUri(e);if(d.isEqualOrParent(t,i))throw new Error(S(2091,null,this.resourceForError(t),this.resourceForError(i)))}}return{exists:c,isSameResourceWithDifferentPathCase:l}}getExtUri(e){let t=this.isPathCaseSensitive(e);return{providerExtUri:t?De:CS,isPathCaseSensitive:t}}isPathCaseSensitive(e){return!!(e.capabilities&1024)}async createFolder(e){let t=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e);await this.mkdirp(t,e);let n=await this.resolve(e,{resolveMetadata:!0});return this._onDidRunOperation.fire(new $n(e,0,n)),n}async mkdirp(e,t){let n=[],{providerExtUri:i}=this.getExtUri(e);for(;!i.isEqual(t,i.dirname(t));)try{if(((await e.stat(t)).type&2)===0)throw new Error(S(2086,null,this.resourceForError(t)));break}catch(s){if(Yl(s)!=="EntryNotFound")throw s;n.push(i.basename(t)),t=i.dirname(t)}for(let s=n.length-1;s>=0;s--){t=i.joinPath(t,n[s]);try{await e.mkdir(t)}catch(a){if(Yl(a)!=="EntryExists")throw a}}}async canDelete(e,t){try{await this.doValidateDelete(e,t)}catch(n){return n}return!0}async doValidateDelete(e,t){let n=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e),i=!!t?.useTrash;if(i&&!(n.capabilities&4096))throw new Error(S(2073,null,this.resourceForError(e)));let s=t?.atomic;if(s&&!(n.capabilities&65536))throw new Error(S(2069,null,this.resourceForError(e)));if(i&&s)throw new Error(S(2072,null,this.resourceForError(e)));let a;try{a=await n.stat(e)}catch{}if(a)this.throwIfFileIsReadonly(e,a);else throw new et(S(2071,null,this.resourceForError(e)),1);if(!!!t?.recursive){let c=await this.resolve(e);if(c.isDirectory&&Array.isArray(c.children)&&c.children.length>0)throw new Error(S(2070,null,this.resourceForError(e)))}return n}async del(e,t){let n=await this.doValidateDelete(e,t),i=t;if(MI(n)&&!i?.atomic){let c=n.enforceAtomicDelete?.(e);c&&(i={...t,atomic:c})}let s=!!i?.useTrash,a=!!i?.recursive,l=i?.atomic??!1;await n.delete(e,{recursive:a,useTrash:s,atomic:l}),this._onDidRunOperation.fire(new $n(e,1))}async cloneFile(e,t){let n=await this.withProvider(e),i=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t);if(!(n===i&&this.getExtUri(n).providerExtUri.isEqual(e,t)))return n===i&&cu(n)?n.cloneFile(e,t):(await this.mkdirp(i,this.getExtUri(i).providerExtUri.dirname(t)),n===i&&Xl(n)?this.writeQueue.queueFor(e,()=>n.copy(e,t,{overwrite:!0}),this.getExtUri(n).providerExtUri):this.writeQueue.queueFor(e,()=>this.doCopyFile(n,e,i,t),this.getExtUri(n).providerExtUri))}static{this.WATCHER_CORRELATION_IDS=0}createWatcher(e,t){return this.watch(e,{...t,correlationId:xi.WATCHER_CORRELATION_IDS++})}watch(e,t={recursive:!1,excludes:[]}){let n=new se,i=!1,s=()=>{i=!0};n.add(oe(()=>s())),(async()=>{try{let l=await this.doWatch(e,t);i?$t(l):s=()=>$t(l)}catch(l){this.logService.error(l)}})();let a=t.correlationId;if(typeof a=="number"){let l=n.add(new w);return n.add(this.internalOnDidFilesChange.event(d=>{d.correlates(a)&&l.fire(d)})),{onDidChange:l.event,dispose:()=>n.dispose()}}return n}async doWatch(e,t){let n=await this.withProvider(e),i=rn([this.getExtUri(n).providerExtUri.getComparisonKey(e),t]),s=this.activeWatchers.get(i);return s||(s={count:0,disposable:n.watch(e,t)},this.activeWatchers.set(i,s)),s.count+=1,oe(()=>{s&&(s.count--,s.count===0&&($t(s.disposable),this.activeWatchers.delete(i)))})}dispose(){super.dispose();for(let[,e]of this.activeWatchers)$t(e.disposable);this.activeWatchers.clear()}async doWriteBuffered(e,t,n,i){return this.writeQueue.queueFor(t,async()=>{let s=await e.open(t,{create:!0,unlock:n?.unlock??!1,append:n?.append??!1});try{Dl(i)||_d(i)?await this.doWriteStreamBufferedQueued(e,s,i):await this.doWriteReadableBufferedQueued(e,s,i)}catch(a){throw qn(a)}finally{await e.close(s)}},this.getExtUri(e).providerExtUri)}async doWriteStreamBufferedQueued(e,t,n){let i=0,s;if(_d(n)){if(n.buffer.length>0){let a=U.concat(n.buffer);await this.doWriteBuffer(e,t,a,a.byteLength,i,0),i+=a.byteLength}if(n.ended)return;s=n.stream}else s=n;return new Promise((a,l)=>{ns(s,{onData:async c=>{s.pause();try{await this.doWriteBuffer(e,t,c,c.byteLength,i,0)}catch(d){return l(d)}i+=c.byteLength,setTimeout(()=>s.resume())},onError:c=>l(c),onEnd:()=>a()})})}async doWriteReadableBufferedQueued(e,t,n){let i=0,s;for(;(s=n.read())!==null;)await this.doWriteBuffer(e,t,s,s.byteLength,i,0),i+=s.byteLength}async doWriteBuffer(e,t,n,i,s,a){let l=0;for(;l<i;){let c=await e.write(t,s+l,n.buffer,a+l,i-l);l+=c}}async doWriteUnbuffered(e,t,n,i){return this.writeQueue.queueFor(t,()=>this.doWriteUnbufferedQueued(e,t,n,i),this.getExtUri(e).providerExtUri)}async doWriteUnbufferedQueued(e,t,n,i){let s;i instanceof U?s=i:Dl(i)?s=await En(i):_d(i)?s=await zS(i):s=GS(i),await e.writeFile(t,s.buffer,{create:!0,overwrite:!0,unlock:n?.unlock??!1,atomic:n?.atomic??!1,append:n?.append??!1})}async doPipeBuffered(e,t,n,i){return this.writeQueue.queueFor(i,()=>this.doPipeBufferedQueued(e,t,n,i),this.getExtUri(n).providerExtUri)}async doPipeBufferedQueued(e,t,n,i){let s,a;try{s=await e.open(t,{create:!1}),a=await n.open(i,{create:!0,unlock:!1});let l=U.alloc(this.BUFFER_SIZE),c=0,d=0,u=0;do u=await e.read(s,c,l.buffer,d,l.byteLength-d),await this.doWriteBuffer(n,a,l,u,c,d),c+=u,d+=u,d===l.byteLength&&(d=0);while(u>0)}catch(l){throw qn(l)}finally{await Ke.settled([typeof s=="number"?e.close(s):Promise.resolve(),typeof a=="number"?n.close(a):Promise.resolve()])}}async doPipeUnbuffered(e,t,n,i){return this.writeQueue.queueFor(i,()=>this.doPipeUnbufferedQueued(e,t,n,i),this.getExtUri(n).providerExtUri)}async doPipeUnbufferedQueued(e,t,n,i){return n.writeFile(i,await e.readFile(t),{create:!0,overwrite:!0,unlock:!1,atomic:!1})}async doPipeUnbufferedToBuffered(e,t,n,i){return this.writeQueue.queueFor(i,()=>this.doPipeUnbufferedToBufferedQueued(e,t,n,i),this.getExtUri(n).providerExtUri)}async doPipeUnbufferedToBufferedQueued(e,t,n,i){let s=await n.open(i,{create:!0,unlock:!1});try{let a=await e.readFile(t);await this.doWriteBuffer(n,s,U.wrap(a),a.byteLength,0,0)}catch(a){throw qn(a)}finally{await n.close(s)}}async doPipeBufferedToUnbuffered(e,t,n,i){let s=await En(this.readFileBuffered(e,t,Y.None));await this.doWriteUnbuffered(n,i,void 0,s)}throwIfFileSystemIsReadonly(e,t){if(e.capabilities&2048)throw new et(S(2076,null,this.resourceForError(t)),6);return e}throwIfFileIsReadonly(e,t){if((t.permissions??0)&1)throw new et(S(2076,null,this.resourceForError(e)),6)}resourceForError(e){return e.scheme===re.file?e.fsPath:e.toString(!0)}};xi=b([g(0,V)],xi);import{constants as Dh,promises as go}from"fs";var sa="**",dx="/",bp="[/\\\\]",xp="[^/\\\\]",U0=/\//g;function ux(o,r){switch(o){case 0:return"";case 1:return`${xp}*?`;default:return`(?:${bp}|${xp}+${bp}${r?`|${bp}${xp}+`:""})*?`}}function px(o,r){if(!o)return[];let e=[],t=!1,n=!1,i="";for(let s of o){switch(s){case r:if(!t&&!n){e.push(i),i="";continue}break;case"{":t=!0;break;case"}":t=!1;break;case"[":n=!0;break;case"]":n=!1;break}i+=s}return i&&e.push(i),e}function vx(o){if(!o)return"";let r="",e=px(o,dx);if(e.every(t=>t===sa))r=".*";else{let t=!1;e.forEach((n,i)=>{if(n===sa){if(t)return;r+=ux(2,i===e.length-1)}else{let s=!1,a="",l=!1,c="";for(let d of n){if(d!=="}"&&s){a+=d;continue}if(l&&(d!=="]"||!c)){let u;d==="-"?u=d:(d==="^"||d==="!")&&!c?u="^":d===dx?u="":u=zr(d),c+=u;continue}switch(d){case"{":s=!0;continue;case"[":l=!0;continue;case"}":{let p=`(?:${px(a,",").map(m=>vx(m)).join("|")})`;r+=p,s=!1,a="";break}case"]":{r+="["+c+"]",l=!1,c="";break}case"?":r+=xp;continue;case"*":r+=ux(1);continue;default:r+=zr(d)}}i<e.length-1&&(e[i+1]!==sa||i+2<e.length)&&(r+=bp)}t=n===sa})}return r}var L0=/^\*\*\/\*\.[\w\.-]+$/,M0=/^\*\*\/([\w\.-]+)\/?$/,A0=/^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/,F0=/^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/,O0=/^\*\*((\/[\w\.-]+)+)\/?$/,N0=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,fx=new yn(1e4),mx=function(){return!1},Cn=function(){return null};function Ph(o,r){if(!o)return Cn;let e;typeof o!="string"?e=o.pattern:e=o,e=e.trim();let t=r.ignoreCase??!1,n={...r,equals:t?yr:(l,c)=>l===c,endsWith:t?cS:(l,c)=>l.endsWith(c),isEqualOrParent:(l,c)=>On(l,c,!Be||t)},i=`${t?e.toLowerCase():e}_${!!r.trimForExclusions}_${t}`,s=fx.get(i);if(s)return gx(s,o,n);let a;return L0.test(e)?s=V0(e.substring(4),e,n):(a=M0.exec(wh(e,n)))?s=W0(a[1],e,n):(r.trimForExclusions?F0:A0).test(e)?s=B0(e,n):(a=O0.exec(wh(e,n)))?s=hx(a[1].substring(1),e,!0,n):(a=N0.exec(wh(e,n)))?s=hx(a[1],e,!1,n):s=$0(e,n),fx.set(i,s),gx(s,o,n)}function gx(o,r,e){if(typeof r=="string")return o;let t=function(n,i){return e.isEqualOrParent(n,r.base)?o(gd(n.substring(r.base.length),Ut),i):null};return t.allBasenames=o.allBasenames,t.allPaths=o.allPaths,t.basenames=o.basenames,t.patterns=o.patterns,t}function wh(o,r){return r.trimForExclusions&&o.endsWith("/**")?o.substring(0,o.length-2):o}function V0(o,r,e){return function(t,n){return typeof t=="string"&&e.endsWith(t,o)?r:null}}function W0(o,r,e){let t=`/${o}`,n=`\\${o}`,i=function(a,l){return typeof a!="string"?null:l?e.equals(l,o)?r:null:e.equals(a,o)||e.endsWith(a,t)||e.endsWith(a,n)?r:null},s=[o];return i.basenames=s,i.patterns=[r],i.allBasenames=s,i}function B0(o,r){let e=Sx(o.slice(1,-1).split(",").map(a=>Ph(a,r)).filter(a=>a!==Cn),o),t=e.length;if(!t)return Cn;if(t===1)return e[0];let n=function(a,l){for(let c=0,d=e.length;c<d;c++)if(e[c](a,l))return o;return null},i=e.find(a=>!!a.allBasenames);i&&(n.allBasenames=i.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(n.allPaths=s),n}function hx(o,r,e,t){let n=Ut===Te.sep,i=n?o:o.replace(U0,Ut),s=Ut+i,a=Te.sep+o,l;return e?l=function(c,d){return typeof c=="string"&&(t.equals(c,i)||t.endsWith(c,s)||!n&&(t.equals(c,o)||t.endsWith(c,a)))?r:null}:l=function(c,d){return typeof c=="string"&&(t.equals(c,i)||!n&&t.equals(c,o))?r:null},l.allPaths=[(e?"*/":"./")+o],l}function $0(o,r){try{let e=new RegExp(`^${vx(o)}$`,r.ignoreCase?"i":void 0);return function(t){return e.lastIndex=0,typeof t=="string"&&e.test(t)?o:null}}catch{return Cn}}function yx(o,r={}){if(!o)return mx;if(typeof o=="string"||G0(o)){let e=Ph(o,r);if(e===Cn)return mx;let t=function(n,i){return!!e(n,i)};return e.allBasenames&&(t.allBasenames=e.allBasenames),e.allPaths&&(t.allPaths=e.allPaths),t}return q0(o,r)}function G0(o){let r=o;return r?typeof r.base=="string"&&typeof r.pattern=="string":!1}function q0(o,r){let e=Sx(Object.getOwnPropertyNames(o).map(a=>z0(a,o[a],r)).filter(a=>a!==Cn)),t=e.length;if(!t)return Cn;if(!e.some(a=>!!a.requiresSiblings)){if(t===1)return e[0];let a=function(d,u){let p;for(let m=0,h=e.length;m<h;m++){let v=e[m](d,u);if(typeof v=="string")return v;Dd(v)&&(p||(p=[]),p.push(v))}return p?(async()=>{for(let m of p){let h=await m;if(typeof h=="string")return h}return null})():null},l=e.find(d=>!!d.allBasenames);l&&(a.allBasenames=l.allBasenames);let c=e.reduce((d,u)=>u.allPaths?d.concat(u.allPaths):d,[]);return c.length&&(a.allPaths=c),a}let n=function(a,l,c){let d,u;for(let p=0,m=e.length;p<m;p++){let h=e[p];h.requiresSiblings&&c&&(l||(l=lt(a)),d||(d=l.substring(0,l.length-xd(a).length)));let v=h(a,l,d,c);if(typeof v=="string")return v;Dd(v)&&(u||(u=[]),u.push(v))}return u?(async()=>{for(let p of u){let m=await p;if(typeof m=="string")return m}return null})():null},i=e.find(a=>!!a.allBasenames);i&&(n.allBasenames=i.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(n.allPaths=s),n}function z0(o,r,e){if(r===!1)return Cn;let t=Ph(o,e);if(t===Cn)return Cn;if(typeof r=="boolean")return t;if(r){let n=r.when;if(typeof n=="string"){let i=(s,a,l,c)=>{if(!c||!t(s,a))return null;let d=n.replace("$(basename)",()=>l),u=c(d);return Dd(u)?u.then(p=>p?o:null):u?o:null};return i.requiresSiblings=!0,i}}return t}function Sx(o,r){let e=o.filter(a=>!!a.basenames);if(e.length<2)return o;let t=e.reduce((a,l)=>{let c=l.basenames;return c?a.concat(c):a},[]),n;if(r){n=[];for(let a=0,l=t.length;a<l;a++)n.push(r)}else n=e.reduce((a,l)=>{let c=l.patterns;return c?a.concat(c):a},[]);let i=function(a,l){if(typeof a!="string")return null;if(!l){let d;for(d=a.length;d>0;d--){let u=a.charCodeAt(d-1);if(u===47||u===92)break}l=a.substring(d)}let c=t.indexOf(l);return c!==-1?n[c]:null};i.basenames=t,i.patterns=n,i.allBasenames=t;let s=o.filter(a=>!a.basenames);return s.push(i),s}function Rh(o,r){return Pt(o,r,(e,t)=>typeof e=="string"&&typeof t=="string"?e===t:typeof e!="string"&&typeof t!="string"?e.base===t.base&&e.pattern===t.pattern:!1)}function Rp(o){return typeof o.correlationId=="number"}function Ix(o){return o.recursive===!0}var Ep=class o extends T{constructor(e,t,n,i){super();this.onFileChanges=e;this.onLogMessage=t;this.verboseLogging=n;this.options=i;this.watcherDisposables=this._register(new kt);this.requests=void 0;this.restartCounter=0}static{this.MAX_RESTARTS=5}init(){let e=new se;this.watcherDisposables.value=e,this.watcher=this.createWatcher(e),this.watcher.setVerboseLogging(this.verboseLogging),e.add(this.watcher.onDidChangeFile(t=>this.onFileChanges(t))),e.add(this.watcher.onDidLogMessage(t=>this.onLogMessage(t))),e.add(this.watcher.onDidError(t=>this.onError(t.error,t.request)))}onError(e,t){this.canRestart(e,t)?this.restartCounter<o.MAX_RESTARTS&&this.requests?(this.error(`restarting watcher after unexpected error: ${e}`),this.restart(this.requests)):this.error(`gave up attempting to restart watcher after unexpected error: ${e}`):this.error(e)}canRestart(e,t){return!(!this.options.restartOnError||t||e.indexOf("No space left on device")!==-1||e.indexOf("EMFILE")!==-1)}restart(e){this.restartCounter++,this.init(),this.watch(e)}async watch(e){this.requests=e,await this.watcher?.watch(e)}async setVerboseLogging(e){this.verboseLogging=e,await this.watcher?.setVerboseLogging(e)}error(e){this.onLogMessage({type:"error",message:`[File Watcher (${this.options.type})] ${e}`})}trace(e){this.onLogMessage({type:"trace",message:`[File Watcher (${this.options.type})] ${e}`})}dispose(){return this.watcher=void 0,super.dispose()}},wp=class extends Ep{constructor(r,e,t){super(r,e,t,{type:"node.js",restartOnError:!1})}},Pp=class extends Ep{constructor(r,e,t){super(r,e,t,{type:"universal",restartOnError:!0})}};function Ic(o){return o.map(r=>({type:r.type,resource:P.revive(r.resource),cId:r.cId}))}function bx(o){let r=new Th;for(let e of o)r.processEvent(e);return r.coalesce()}function K0(o,r){return typeof r=="string"&&!r.startsWith(sa)&&!Zo(r)?{base:o,pattern:r}:r}function Ch(o,r,e){let t=[];for(let n of r)t.push(yx(K0(o,n),{ignoreCase:e}));return t}var Th=class{constructor(){this.coalesced=new Set;this.mapPathToChange=new Map}toKey(r){return Be?r.resource.fsPath:r.resource.fsPath.toLowerCase()}processEvent(r){let e=this.mapPathToChange.get(this.toKey(r)),t=!1;if(e){let n=e.type,i=r.type;e.resource.fsPath!==r.resource.fsPath&&(r.type===2||r.type===1)?t=!0:n===1&&i===2?(this.mapPathToChange.delete(this.toKey(r)),this.coalesced.delete(e)):n===2&&i===1?e.type=0:n===1&&i===0||(e.type=i)}else t=!0;t&&(this.coalesced.add(r),this.mapPathToChange.set(this.toKey(r),r))}coalesce(){let r=[],e=[];return Array.from(this.coalesced).filter(t=>t.type!==2?(r.push(t),!1):!0).sort((t,n)=>t.resource.fsPath.length-n.resource.fsPath.length).filter(t=>e.some(n=>AI(t.resource.fsPath,n,!Be))?!1:(e.push(t.resource.fsPath),!0)).concat(r)}};function xx(o,r){if(typeof r=="number")switch(o.type){case 1:return(r&4)===0;case 2:return(r&8)===0;case 0:return(r&2)===0}return!1}function Ex(o){if(typeof o=="number"){let r=[];return o&4&&r.push("Added"),o&8&&r.push("Deleted"),o&2&&r.push("Updated"),r.length===0?"<all>":`[${r.join(", ")}]`}return"<none>"}var Tp=class extends T{constructor(e,t){super();this.logService=e;this.options=t;this._onDidChangeFile=this._register(new w);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new w);this.onDidWatchError=this._onDidWatchError.event;this.universalWatchRequests=[];this.universalWatchRequestDelayer=this._register(new ur(this.getRefreshWatchersDelay(this.universalWatchRequests.length)));this.nonRecursiveWatchRequests=[];this.nonRecursiveWatchRequestDelayer=this._register(new ur(this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)))}watch(e,t){return t.recursive||this.options?.watcher?.forceUniversal?this.watchUniversal(e,t):this.watchNonRecursive(e,t)}getRefreshWatchersDelay(e){return e>200?500:0}watchUniversal(e,t){let n=this.toWatchRequest(e,t),i=gm(this.universalWatchRequests,n);return this.refreshUniversalWatchers(),oe(()=>{i(),this.refreshUniversalWatchers()})}toWatchRequest(e,t){let n={path:this.toWatchPath(e),excludes:t.excludes,includes:t.includes,recursive:t.recursive,filter:t.filter,correlationId:t.correlationId};if(Ix(n)){let i=this.options?.watcher?.recursive?.usePolling;i===!0?n.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3:Array.isArray(i)&&i.includes(n.path)&&(n.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3)}return n}refreshUniversalWatchers(){this.universalWatchRequestDelayer.trigger(()=>this.doRefreshUniversalWatchers(),this.getRefreshWatchersDelay(this.universalWatchRequests.length)).catch(e=>Me(e))}doRefreshUniversalWatchers(){return this.universalWatcher||(this.universalWatcher=this._register(this.createUniversalWatcher(e=>this._onDidChangeFile.fire(Ic(e)),e=>this.onWatcherLogMessage(e),this.logService.getLevel()===1)),this._register(this.logService.onDidChangeLogLevel(()=>{this.universalWatcher?.setVerboseLogging(this.logService.getLevel()===1)}))),this.universalWatcher.watch(this.universalWatchRequests)}watchNonRecursive(e,t){let n={path:this.toWatchPath(e),excludes:t.excludes,includes:t.includes,recursive:!1,filter:t.filter,correlationId:t.correlationId},i=gm(this.nonRecursiveWatchRequests,n);return this.refreshNonRecursiveWatchers(),oe(()=>{i(),this.refreshNonRecursiveWatchers()})}refreshNonRecursiveWatchers(){this.nonRecursiveWatchRequestDelayer.trigger(()=>this.doRefreshNonRecursiveWatchers(),this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)).catch(e=>Me(e))}doRefreshNonRecursiveWatchers(){return this.nonRecursiveWatcher||(this.nonRecursiveWatcher=this._register(this.createNonRecursiveWatcher(e=>this._onDidChangeFile.fire(Ic(e)),e=>this.onWatcherLogMessage(e),this.logService.getLevel()===1)),this._register(this.logService.onDidChangeLogLevel(()=>{this.nonRecursiveWatcher?.setVerboseLogging(this.logService.getLevel()===1)}))),this.nonRecursiveWatcher.watch(this.nonRecursiveWatchRequests)}onWatcherLogMessage(e){e.type==="error"&&this._onDidWatchError.fire(e.message),this.logWatcherMessage(e)}logWatcherMessage(e){this.logService[e.type](e.message)}toFilePath(e){return br(e.fsPath)}toWatchPath(e){let t=this.toFilePath(e);return wS(t)}};import{fork as X0}from"child_process";function wx(o){let r=o;return r&&typeof r.type=="string"&&typeof r.severity=="string"}function j0(o){let r=[],e;try{let t=JSON.parse(o.arguments),n=t[t.length-1];n&&n.__$stack&&(t.pop(),e=n.__$stack),r.push(...t)}catch{r.push("Unable to log remote console arguments",o.arguments)}return{args:r,stack:e}}function H0(o){if(!o)return o;let r=o.indexOf(`
`);return r===-1?o:o.substring(0,r)}function Px(o,r){let{args:e,stack:t}=j0(o),n=typeof e[0]=="string"&&e.length===1,i=H0(t);i&&(i=`(${i.trim()})`);let s=[];if(typeof e[0]=="string"?i&&n?s=[`%c[${r}] %c${e[0]} %c${i}`,aa("blue"),aa(""),aa("grey")]:s=[`%c[${r}] %c${e[0]}`,aa("blue"),aa(""),...e.slice(1)]:s=[`%c[${r}]%`,aa("blue"),...e],i&&!n&&s.push(i),typeof console[o.severity]!="function")throw new Error("Unknown console method");console[o.severity].apply(console,s)}function aa(o){return`color: ${o}`}import*as J0 from"child_process";import{promises as xB}from"fs";function Rx(o){o&&(delete o.DEBUG,Be&&delete o.LD_PRELOAD)}function Tx(o=Fe){return o.comspec||"cmd.exe"}function Cx(o){let r=[],e=!1,t=function(n){if(e){r.push(n);return}(!o.send(n,s=>{if(s&&console.error(s),e=!1,r.length>0){let a=r.slice(0);r=[],a.forEach(l=>t(l))}})||he)&&(e=!0)};return{send:t}}var la=class{constructor(r,e){this.modulePath=r;this.options=e;this.activeRequests=new Set;this.channels=new Map;this._onDidProcessExit=new w;this.onDidProcessExit=this._onDidProcessExit.event;let t=e.timeout||6e4;this.disposeDelayer=new Yi(t),this.child=null,this._client=null}getChannel(r){let e=this;return{call(t,n,i){return e.requestPromise(r,t,n,i)},listen(t,n){return e.requestEvent(r,t,n)}}}requestPromise(r,e,t,n=Y.None){if(!this.disposeDelayer)return Promise.reject(new Error("disposed"));if(n.isCancellationRequested)return Promise.reject(Yn());this.disposeDelayer.cancel();let i=this.getCachedChannel(r),s=Je(c=>i.call(e,t,c)),a=n.onCancellationRequested(()=>s.cancel()),l=oe(()=>s.cancel());return this.activeRequests.add(l),s.finally(()=>{a.dispose(),this.activeRequests.delete(l),this.activeRequests.size===0&&this.disposeDelayer&&this.disposeDelayer.trigger(()=>this.disposeClient())}),s}requestEvent(r,e,t){if(!this.disposeDelayer)return k.None;this.disposeDelayer.cancel();let n,i=new w({onWillAddFirstListener:()=>{n=this.getCachedChannel(r).listen(e,t)(i.fire,i),this.activeRequests.add(n)},onDidRemoveLastListener:()=>{this.activeRequests.delete(n),n.dispose(),this.activeRequests.size===0&&this.disposeDelayer&&this.disposeDelayer.trigger(()=>this.disposeClient())}});return i.event}get client(){if(!this._client){let r=this.options.args||[],e=Object.create(null);e.env={...Ct(process.env),VSCODE_PARENT_PID:String(process.pid)},this.options.env&&(e.env={...e.env,...this.options.env}),this.options.freshExecArgv&&(e.execArgv=[]),typeof this.options.debug=="number"&&(e.execArgv=["--nolazy","--inspect="+this.options.debug]),typeof this.options.debugBrk=="number"&&(e.execArgv=["--nolazy","--inspect-brk="+this.options.debugBrk]),e.execArgv===void 0&&(e.execArgv=process.execArgv.filter(u=>!/^--inspect(-brk)?=/.test(u)).filter(u=>!u.startsWith("--vscode-"))),Rx(e.env),this.child=X0(this.modulePath,r,e);let t=new w,i=k.fromNodeEventEmitter(this.child,"message",u=>u)(u=>{if(wx(u)){Px(u,`IPC Library: ${this.options.serverName}`);return}t.fire(U.wrap(Buffer.from(u,"base64")))}),s=this.options.useQueue?Cx(this.child):this.child,a=u=>this.child?.connected&&s.send(u.buffer.toString("base64")),l=t.event,c={send:a,onMessage:l};this._client=new as(c);let d=()=>this.disposeClient();process.once("exit",d),this.child.on("error",u=>console.warn('IPC "'+this.options.serverName+'" errored with '+u)),this.child.on("exit",(u,p)=>{process.removeListener("exit",d),i.dispose(),this.activeRequests.forEach(m=>$t(m)),this.activeRequests.clear(),u!==0&&p!=="SIGTERM"&&console.warn('IPC "'+this.options.serverName+'" crashed with exit code '+u+" and signal "+p),this.disposeDelayer?.cancel(),this.disposeClient(),this._onDidProcessExit.fire({code:u,signal:p})})}return this._client}getCachedChannel(r){let e=this.channels.get(r);return e||(e=this.client.getChannel(r),this.channels.set(r,e)),e}disposeClient(){this._client&&(this.child&&(this.child.kill(),this.child=null),this._client=null,this.channels.clear())}dispose(){this._onDidProcessExit.dispose(),this.disposeDelayer?.cancel(),this.disposeDelayer=void 0,this.disposeClient(),this.activeRequests.clear()}};var Cp=class extends Pp{constructor(r,e,t){super(r,e,t),this.init()}createWatcher(r){let e=r.add(new la(dr.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"}}));return r.add(e.onDidProcessExit(({code:t,signal:n})=>this.onError(`terminated by itself with code ${t}, signal: ${n} (ETERM)`))),Rt.toService(ZS(e.getChannel("watcher")))}};import{watchFile as Y0,unwatchFile as Z0}from"fs";var Dp=class extends T{constructor(){super();this._onDidChangeFile=this._register(new w);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidLogMessage=this._register(new w);this.onDidLogMessage=this._onDidLogMessage.event;this._onDidWatchFail=this._register(new w);this.onDidWatchFail=this._onDidWatchFail.event;this.correlatedWatchRequests=new Map;this.nonCorrelatedWatchRequests=new Map;this.suspendedWatchRequests=this._register(new Gr);this.suspendedWatchRequestsWithPolling=new Set;this.updateWatchersDelayer=this._register(new ur(this.getUpdateWatchersDelay()));this.suspendedWatchRequestPollingInterval=5007;this.joinWatch=new Ur;this.verboseLogging=!1;this._register(this.onDidWatchFail(e=>this.suspendWatchRequest({id:this.computeId(e),correlationId:this.isCorrelated(e)?e.correlationId:void 0,path:e.path})))}isCorrelated(e){return Rp(e)}computeId(e){return this.isCorrelated(e)?e.correlationId:rn(e)}async watch(e){this.joinWatch.isSettled||this.joinWatch.complete(),this.joinWatch=new Ur;try{this.correlatedWatchRequests.clear(),this.nonCorrelatedWatchRequests.clear();for(let t of e)this.isCorrelated(t)?this.correlatedWatchRequests.set(t.correlationId,t):this.nonCorrelatedWatchRequests.set(this.computeId(t),t);for(let[t]of this.suspendedWatchRequests)!this.nonCorrelatedWatchRequests.has(t)&&!this.correlatedWatchRequests.has(t)&&(this.suspendedWatchRequests.deleteAndDispose(t),this.suspendedWatchRequestsWithPolling.delete(t));return await this.updateWatchers(!1)}finally{this.joinWatch.complete()}}updateWatchers(e){let t=[];for(let[n,i]of[...this.nonCorrelatedWatchRequests,...this.correlatedWatchRequests])this.suspendedWatchRequests.has(n)||t.push(i);return this.updateWatchersDelayer.trigger(()=>this.doWatch(t),e?this.getUpdateWatchersDelay():0).catch(n=>Me(n))}getUpdateWatchersDelay(){return 800}isSuspended(e){let t=this.computeId(e);return this.suspendedWatchRequestsWithPolling.has(t)?"polling":this.suspendedWatchRequests.has(t)}async suspendWatchRequest(e){if(this.suspendedWatchRequests.has(e.id))return;let t=new se;this.suspendedWatchRequests.set(e.id,t),await this.joinWatch.p,!t.isDisposed&&(this.monitorSuspendedWatchRequest(e,t),this.updateWatchers(!0))}resumeWatchRequest(e){this.suspendedWatchRequests.deleteAndDispose(e.id),this.suspendedWatchRequestsWithPolling.delete(e.id),this.updateWatchers(!1)}monitorSuspendedWatchRequest(e,t){this.doMonitorWithExistingWatcher(e,t)?(this.trace(`reusing an existing recursive watcher to monitor ${e.path}`),this.suspendedWatchRequestsWithPolling.delete(e.id)):(this.doMonitorWithNodeJS(e,t),this.suspendedWatchRequestsWithPolling.add(e.id))}doMonitorWithExistingWatcher(e,t){let n=this.recursiveWatcher?.subscribe(e.path,(i,s)=>{t.isDisposed||(i?this.monitorSuspendedWatchRequest(e,t):s?.type===1&&this.onMonitoredPathAdded(e))});return n?(t.add(n),!0):!1}doMonitorWithNodeJS(e,t){let n=!1,i=(s,a)=>{if(t.isDisposed)return;let l=this.isPathNotFound(s),c=this.isPathNotFound(a),d=n;n=l,!l&&(c||d)&&this.onMonitoredPathAdded(e)};this.trace(`starting fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{Y0(e.path,{persistent:!1,interval:this.suspendedWatchRequestPollingInterval},i)}catch(s){this.warn(`fs.watchFile() failed with error ${s} on path ${e.path} (correlationId: ${e.correlationId})`)}t.add(oe(()=>{this.trace(`stopping fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{Z0(e.path,i)}catch(s){this.warn(`fs.unwatchFile() failed with error ${s} on path ${e.path} (correlationId: ${e.correlationId})`)}}))}onMonitoredPathAdded(e){this.trace(`detected ${e.path} exists again, resuming watcher (correlationId: ${e.correlationId})`);let t={resource:P.file(e.path),type:1,cId:e.correlationId};this._onDidChangeFile.fire([t]),this.traceEvent(t,e),this.resumeWatchRequest(e)}isPathNotFound(e){return e.ctimeMs===0&&e.ino===0}async stop(){this.suspendedWatchRequests.clearAndDisposeAll(),this.suspendedWatchRequestsWithPolling.clear()}traceEvent(e,t){if(this.verboseLogging){let n=` >> normalized ${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`;this.traceWithCorrelation(n,t)}}traceWithCorrelation(e,t){this.verboseLogging&&this.trace(`${e}${typeof t.correlationId=="number"?` <${t.correlationId}> `:""}`)}requestToString(e){return`${e.path} (excludes: ${e.excludes.length>0?e.excludes:"<none>"}, includes: ${e.includes&&e.includes.length>0?JSON.stringify(e.includes):"<all>"}, filter: ${Ex(e.filter)}, correlationId: ${typeof e.correlationId=="number"?e.correlationId:"<none>"})`}async setVerboseLogging(e){this.verboseLogging=e}};import{watch as eR,promises as tR}from"fs";var _p=class o extends T{constructor(e,t,n,i,s,a){super();this.request=e;this.recursiveWatcher=t;this.onDidFilesChange=n;this.onDidWatchFail=i;this.onLogMessage=s;this.verboseLogging=a;this.throttledFileChangesEmitter=this._register(new rs({maxWorkChunkSize:100,throttleDelay:200,maxBufferedWork:1e4},e=>this.onDidFilesChange(e)));this.fileChangesAggregator=this._register(new Td(e=>this.handleFileChanges(e),o.FILE_CHANGES_HANDLER_DELAY));this.cts=new mt;this.realPath=new cr(async()=>{let e=this.request.path;try{e=await ce.realpath(this.request.path),this.request.path!==e&&this.trace(`correcting a path to watch that seems to be a symbolic link (original: ${this.request.path}, real: ${e})`)}catch{}return e});this._isReusingRecursiveWatcher=!1;this.didFail=!1;let l=!Be;this.excludes=Ch(this.request.path,this.request.excludes,l),this.includes=this.request.includes?Ch(this.request.path,this.request.includes,l):void 0,this.filter=Rp(this.request)?this.request.filter:void 0,this.ready=this.watch()}static{this.FILE_DELETE_HANDLER_DELAY=100}static{this.FILE_CHANGES_HANDLER_DELAY=75}get isReusingRecursiveWatcher(){return this._isReusingRecursiveWatcher}get failed(){return this.didFail}async watch(){try{let e=await tR.stat(this.request.path);if(this.cts.token.isCancellationRequested)return;this._register(await this.doWatch(e.isDirectory()))}catch(e){e.code!=="ENOENT"?this.error(e):this.trace(`ignoring a path for watching who's stat info failed to resolve: ${this.request.path} (error: ${e})`),this.notifyWatchFailed()}}notifyWatchFailed(){this.didFail=!0,this.onDidWatchFail?.()}async doWatch(e){let t=new se;return this.doWatchWithExistingWatcher(e,t)?(this.trace(`reusing an existing recursive watcher for ${this.request.path}`),this._isReusingRecursiveWatcher=!0):(this._isReusingRecursiveWatcher=!1,await this.doWatchWithNodeJS(e,t)),t}doWatchWithExistingWatcher(e,t){if(e)return!1;let n=P.file(this.request.path),i=this.recursiveWatcher?.subscribe(this.request.path,async(s,a)=>{t.isDisposed||(s?await By(this.doWatch(e),t):a&&(typeof a.cId=="number"||typeof this.request.correlationId=="number")&&this.onFileChange({resource:n,type:a.type,cId:this.request.correlationId},!0))});return i?(t.add(i),!0):!1}async doWatchWithNodeJS(e,t){let n=await this.realPath.value;if(this.cts.token.isCancellationRequested)return;if(Gt&&On(n,"/Volumes/",!0)){this.error(`Refusing to watch ${n} for changes using fs.watch() for possibly being a network share where watching is unreliable and unstable.`);return}let i=new mt(this.cts.token);t.add(oe(()=>i.dispose(!0)));let s=new se;t.add(s);try{let a=P.file(this.request.path),l=lt(n),c=eR(n);s.add(oe(()=>{c.removeAllListeners(),c.close()})),this.trace(`Started watching: '${n}'`);let d=new Set;if(e)try{for(let p of await ce.readdir(n))d.add(p)}catch(p){this.error(p)}if(i.token.isCancellationRequested)return;let u=new Map;s.add(oe(()=>{for(let[,p]of u)p.dispose();u.clear()})),c.on("error",(p,m)=>{i.token.isCancellationRequested||(this.error(`Failed to watch ${n} for changes using fs.watch() (${p}, ${m})`),this.notifyWatchFailed())}),c.on("change",(p,m)=>{if(i.token.isCancellationRequested)return;this.verboseLogging&&this.traceWithCorrelation(`[raw] ["${p}"] ${m}`);let h="";if(m&&(h=m.toString(),Gt&&(h=Al(h))),!(!h||p!=="change"&&p!=="rename"))if(e)if(p==="rename"){u.get(h)?.dispose();let v=setTimeout(async()=>{if(u.delete(h),es(h,l,!Be)&&!await ce.exists(n)){this.onWatchedPathDeleted(a);return}if(i.token.isCancellationRequested)return;let y=await this.existsChildStrictCase(G(n,h));if(i.token.isCancellationRequested)return;let x;y?d.has(h)?x=0:(x=1,d.add(h)):(d.delete(h),x=2),this.onFileChange({resource:$(a,h),type:x,cId:this.request.correlationId})},o.FILE_DELETE_HANDLER_DELAY);u.set(h,oe(()=>clearTimeout(v)))}else{let v;d.has(h)?v=0:(v=1,d.add(h)),this.onFileChange({resource:$(a,h),type:v,cId:this.request.correlationId})}else if(p==="rename"||!es(h,l,!Be)){let v=setTimeout(async()=>{let y=await ce.exists(n);i.token.isCancellationRequested||(y?(this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0),s.add(await this.doWatch(!1))):this.onWatchedPathDeleted(a))},o.FILE_DELETE_HANDLER_DELAY);s.clear(),s.add(oe(()=>clearTimeout(v)))}else this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0)})}catch(a){if(i.token.isCancellationRequested)return;this.error(`Failed to watch ${n} for changes using fs.watch() (${a.toString()})`),this.notifyWatchFailed()}}onWatchedPathDeleted(e){this.warn("Watcher shutdown because watched path got deleted"),this.onFileChange({resource:e,type:2,cId:this.request.correlationId},!0),this.fileChangesAggregator.flush(),this.notifyWatchFailed()}onFileChange(e,t=!1){this.cts.token.isCancellationRequested||(this.verboseLogging&&this.traceWithCorrelation(`${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`),!t&&this.excludes.some(n=>n(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (excluded) ${e.resource.fsPath}`):!t&&this.includes&&this.includes.length>0&&!this.includes.some(n=>n(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (not included) ${e.resource.fsPath}`):this.fileChangesAggregator.work(e))}handleFileChanges(e){let t=bx(e),n=[];for(let s of t){if(xx(s,this.filter)){this.verboseLogging&&this.traceWithCorrelation(` >> ignored (filtered) ${s.resource.fsPath}`);continue}n.push(s)}if(n.length===0)return;if(this.verboseLogging)for(let s of n)this.traceWithCorrelation(` >> normalized ${s.type===1?"[ADDED]":s.type===2?"[DELETED]":"[CHANGED]"} ${s.resource.fsPath}`);this.throttledFileChangesEmitter.work(n)?this.throttledFileChangesEmitter.pending>0&&this.trace(`started throttling events due to large amount of file change events at once (pending: ${this.throttledFileChangesEmitter.pending}, most recent change: ${n[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`):this.warn(`started ignoring events due to too many file change events at once (incoming: ${n.length}, most recent change: ${n[0].resource.fsPath}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`)}async existsChildStrictCase(e){if(Be)return ce.exists(e);try{let t=lt(e);return(await ce.readdir($e(e))).some(i=>i===t)}catch(t){return this.trace(t),!1}}setVerboseLogging(e){this.verboseLogging=e}error(e){this.cts.token.isCancellationRequested||this.onLogMessage?.({type:"error",message:`[File Watcher (node.js)] ${e}`})}warn(e){this.cts.token.isCancellationRequested||this.onLogMessage?.({type:"warn",message:`[File Watcher (node.js)] ${e}`})}trace(e){!this.cts.token.isCancellationRequested&&this.verboseLogging&&this.onLogMessage?.({type:"trace",message:`[File Watcher (node.js)] ${e}`})}traceWithCorrelation(e){!this.cts.token.isCancellationRequested&&this.verboseLogging&&this.trace(`${e}${typeof this.request.correlationId=="number"?` <${this.request.correlationId}> `:""}`)}dispose(){this.cts.dispose(!0),super.dispose()}};var kp=class extends Dp{constructor(e){super();this.recursiveWatcher=e;this.onDidError=k.None;this._watchers=new Map;this.worker=this._register(new kt)}get watchers(){return this._watchers.values()}async doWatch(e){e=this.removeDuplicateRequests(e);let t=[],n=new Set(Array.from(this.watchers));for(let i of e){let s=this._watchers.get(this.requestToWatcherKey(i));s&&Rh(s.request.excludes,i.excludes)&&Rh(s.request.includes,i.includes)?n.delete(s):t.push(i)}t.length&&this.trace(`Request to start watching: ${t.map(i=>this.requestToString(i)).join(",")}`),n.size&&this.trace(`Request to stop watching: ${Array.from(n).map(i=>this.requestToString(i.request)).join(",")}`),this.worker.clear();for(let i of n)this.stopWatching(i);this.createWatchWorker().work(t)}createWatchWorker(){return this.worker.value=new rs({maxWorkChunkSize:100,throttleDelay:100,maxBufferedWork:Number.MAX_VALUE},e=>{for(let t of e)this.startWatching(t)}),this.worker.value}requestToWatcherKey(e){return typeof e.correlationId=="number"?e.correlationId:this.pathToWatcherKey(e.path)}pathToWatcherKey(e){return Be?e:e.toLowerCase()}startWatching(e){let t=new _p(e,this.recursiveWatcher,i=>this._onDidChangeFile.fire(i),()=>this._onDidWatchFail.fire(e),i=>this._onDidLogMessage.fire(i),this.verboseLogging),n={request:e,instance:t};this._watchers.set(this.requestToWatcherKey(e),n)}async stop(){await super.stop();for(let e of this.watchers)this.stopWatching(e)}stopWatching(e){this.trace("stopping file watcher",e),this._watchers.delete(this.requestToWatcherKey(e.request)),e.instance.dispose()}removeDuplicateRequests(e){let t=new Map;for(let n of e){let i=t.get(n.correlationId);i||(i=new Map,t.set(n.correlationId,i));let s=this.pathToWatcherKey(n.path);i.has(s)&&this.trace(`ignoring a request for watching who's path is already watched: ${this.requestToString(n)}`),i.set(s,n)}return Array.from(t.values()).flatMap(n=>Array.from(n.values()))}async setVerboseLogging(e){super.setVerboseLogging(e);for(let t of this.watchers)t.instance.setVerboseLogging(e)}trace(e,t){this.verboseLogging&&this._onDidLogMessage.fire({type:"trace",message:this.toMessage(e,t)})}warn(e){this._onDidLogMessage.fire({type:"warn",message:this.toMessage(e)})}toMessage(e,t){return t?`[File Watcher (node.js)] ${e} (${this.requestToString(t.request)})`:`[File Watcher (node.js)] ${e}`}};var Up=class extends wp{constructor(r,e,t){super(r,e,t),this.init()}createWatcher(r){return r.add(new kp(void 0))}};var Lp=class o extends Tp{constructor(){super(...arguments);this.onDidChangeCapabilities=k.None;this.resourceLocks=new He(e=>Xi.getComparisonKey(e));this.mapHandleToPos=new Map;this.mapHandleToLock=new Map;this.writeHandles=new Map}static{this.TRACE_LOG_RESOURCE_LOCKS=!1}get capabilities(){return this._capabilities||(this._capabilities=1040414,Be&&(this._capabilities|=1024)),this._capabilities}async stat(e){try{let{stat:t,symbolicLink:n}=await pr.stat(this.toFilePath(e)),i;return(t.mode&128)===0&&(i=2),(t.mode&Dh.S_IXUSR||t.mode&Dh.S_IXGRP||t.mode&Dh.S_IXOTH)&&(i=(i??0)|4),{type:this.toType(t,n),ctime:t.birthtime.getTime(),mtime:t.mtime.getTime(),size:t.size,permissions:i}}catch(t){throw this.toFileSystemProviderError(t)}}async statIgnoreError(e){try{return await this.stat(e)}catch{return}}async realpath(e){let t=this.toFilePath(e);return ce.realpath(t)}async readdir(e){try{let t=await ce.readdir(this.toFilePath(e),{withFileTypes:!0}),n=[];return await Promise.all(t.map(async i=>{try{let s;i.isSymbolicLink()?s=(await this.stat($(e,i.name))).type:s=this.toType(i),n.push([i.name,s])}catch(s){this.logService.trace(s)}})),n}catch(t){throw this.toFileSystemProviderError(t)}}toType(e,t){let n;return t?.dangling?n=0:e.isFile()?n=1:e.isDirectory()?n=2:n=0,t&&(n|=64),n}async createResourceLock(e){let t=this.toFilePath(e);this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - request to acquire resource lock (${t})`);let n;for(;n=this.resourceLocks.get(e);)this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - waiting for resource lock to be released (${t})`),await n.wait();let i=new Kr;return this.resourceLocks.set(e,i),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${t})`),oe(()=>{this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock dispose() (${t})`),this.resourceLocks.get(e)===i&&(this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock removed from resource-lock map (${t})`),this.resourceLocks.delete(e)),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock barrier open() (${t})`),i.open()})}async readFile(e,t){let n;try{t?.atomic&&(this.traceLock(`[Disk FileSystemProvider]: atomic read operation started (${this.toFilePath(e)})`),n=await this.createResourceLock(e));let i=this.toFilePath(e);return await go.readFile(i)}catch(i){throw this.toFileSystemProviderError(i)}finally{n?.dispose()}}traceLock(e){o.TRACE_LOG_RESOURCE_LOCKS&&this.logService.trace(e)}readFileStream(e,t,n){let i=Vn(s=>U.concat(s.map(a=>U.wrap(a))).buffer);return Ip(this,e,i,s=>s.buffer,{...t,bufferSize:256*1024},n),i}async writeFile(e,t,n){return n?.atomic!==!1&&n?.atomic?.postfix&&await this.canWriteFileAtomic(e)?this.doWriteFileAtomic(e,$(wd(e),`${Nn(e)}${n.atomic.postfix}`),t,n):this.doWriteFile(e,t,n)}async canWriteFileAtomic(e){try{let t=this.toFilePath(e),{symbolicLink:n}=await pr.stat(t);if(n)return!1}catch{}return!0}async doWriteFileAtomic(e,t,n,i){let s=new se;try{s.add(await this.createResourceLock(e)),s.add(await this.createResourceLock(t)),await this.doWriteFile(t,n,{...i,create:!0,overwrite:!0},!0);try{await this.rename(t,e,{overwrite:!0})}catch(a){try{await this.delete(t,{recursive:!1,useTrash:!1,atomic:!1})}catch{}throw a}}finally{s.dispose()}}async doWriteFile(e,t,n,i){let s;try{let a=this.toFilePath(e);if(!n.create||!n.overwrite){if(await ce.exists(a)){if(!n.overwrite)throw Fr(S(2101,null),"EntryExists")}else if(!n.create)throw Fr(S(2104,null),"EntryNotFound")}s=await this.open(e,{create:!0,append:n.append,unlock:n.unlock},i),await this.write(s,0,t,0,t.byteLength)}catch(a){throw await this.toFileSystemProviderWriteError(e,a)}finally{typeof s=="number"&&await this.close(s)}}static{this.canFlush=!0}static configureFlushOnWrite(e){o.canFlush=e}async open(e,t,n){let i=this.toFilePath(e),s;io(t)&&!n&&(s=await this.createResourceLock(e));let a;try{if(io(t)&&t.unlock)try{let{stat:l}=await pr.stat(i);l.mode&128||await go.chmod(i,l.mode|128)}catch(l){l.code!=="ENOENT"&&this.logService.trace(l)}if(he&&io(t)&&!t.append)try{a=await ce.open(i,"r+"),await ce.ftruncate(a,0)}catch(l){if(l.code!=="ENOENT"&&this.logService.trace(l),typeof a=="number"){try{await ce.close(a)}catch(c){this.logService.trace(c)}a=void 0}}typeof a!="number"&&(a=await ce.open(i,io(t)?t.append?"a":"w":"r"))}catch(l){throw s?.dispose(),io(t)?await this.toFileSystemProviderWriteError(e,l):this.toFileSystemProviderError(l)}if(this.mapHandleToPos.set(a,0),io(t)&&this.writeHandles.set(a,e),s){let l=this.mapHandleToLock.get(a);this.traceLock(`[Disk FileSystemProvider]: open() - storing lock for handle ${a} (${i})`),this.mapHandleToLock.set(a,s),l&&(this.traceLock(`[Disk FileSystemProvider]: open() - disposing a previous lock that was still stored on same handle ${a} (${i})`),l.dispose())}return a}async close(e){let t=this.mapHandleToLock.get(e);try{if(this.mapHandleToPos.delete(e),this.writeHandles.delete(e)&&o.canFlush)try{await ce.fdatasync(e)}catch(n){o.configureFlushOnWrite(!1),this.logService.error(n)}return await ce.close(e)}catch(n){throw this.toFileSystemProviderError(n)}finally{t&&(this.mapHandleToLock.get(e)===t&&(this.traceLock(`[Disk FileSystemProvider]: close() - resource lock removed from handle-lock map ${e}`),this.mapHandleToLock.delete(e)),this.traceLock(`[Disk FileSystemProvider]: close() - disposing lock for handle ${e}`),t.dispose())}}async read(e,t,n,i,s){let a=this.normalizePos(e,t),l=null;try{l=(await ce.read(e,n,i,s,a)).bytesRead}catch(c){throw this.toFileSystemProviderError(c)}finally{this.updatePos(e,a,l)}return l}normalizePos(e,t){return t===this.mapHandleToPos.get(e)?null:t}updatePos(e,t,n){let i=this.mapHandleToPos.get(e);typeof i=="number"&&(typeof t=="number"||(typeof n=="number"?this.mapHandleToPos.set(e,i+n):this.mapHandleToPos.delete(e)))}async write(e,t,n,i,s){return OS(()=>this.doWrite(e,t,n,i,s),100,3)}async doWrite(e,t,n,i,s){let a=this.normalizePos(e,t),l=null;try{l=(await ce.write(e,n,i,s,a)).bytesWritten}catch(c){throw await this.toFileSystemProviderWriteError(this.writeHandles.get(e),c)}finally{this.updatePos(e,a,l)}return l}async mkdir(e){try{await go.mkdir(this.toFilePath(e))}catch(t){throw this.toFileSystemProviderError(t)}}async delete(e,t){try{let n=this.toFilePath(e);if(t.recursive){let i;t?.atomic!==!1&&t.atomic.postfix&&(i=G($e(n),`${lt(n)}${t.atomic.postfix}`)),await ce.rm(n,1,i)}else try{await go.unlink(n)}catch(i){if(i.code==="EPERM"||i.code==="EISDIR"){let s=!1;try{let{stat:a,symbolicLink:l}=await pr.stat(n);s=a.isDirectory()&&!l}catch{}if(s)await go.rmdir(n);else throw i}else throw i}}catch(n){throw this.toFileSystemProviderError(n)}}async rename(e,t,n){let i=this.toFilePath(e),s=this.toFilePath(t);if(i!==s)try{await this.validateMoveCopy(e,t,"move",n.overwrite),await ce.rename(i,s)}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(S(2105,null,lt(i),lt($e(s)),a.toString()))),this.toFileSystemProviderError(a)}}async copy(e,t,n){let i=this.toFilePath(e),s=this.toFilePath(t);if(i!==s)try{await this.validateMoveCopy(e,t,"copy",n.overwrite),await ce.copy(i,s,{preserveSymlinks:!0})}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(S(2099,null,lt(i),lt($e(s)),a.toString()))),this.toFileSystemProviderError(a)}}async validateMoveCopy(e,t,n,i){let s=this.toFilePath(e),a=this.toFilePath(t),l=!1;if(this.capabilities&1024||(l=es(s,a,!0)),l){if(n==="copy")throw Fr(S(2100,null),"EntryExists");if(n==="move")return}let d=await this.statIgnoreError(e);if(!d)throw Fr(S(2103,null),"EntryNotFound");let u=await this.statIgnoreError(t);if(u){if(!i)throw Fr(S(2102,null),"EntryExists");(d.type&1)!==0&&(u.type&1)!==0||await this.delete(t,{recursive:!0,useTrash:!1,atomic:!1})}}async cloneFile(e,t){return this.doCloneFile(e,t,!1)}async doCloneFile(e,t,n){let i=this.toFilePath(e),s=this.toFilePath(t),a=!!(this.capabilities&1024);if(es(i,s,!a))return;let l=new se;try{l.add(await this.createResourceLock(e)),l.add(await this.createResourceLock(t)),n&&await go.mkdir($e(s),{recursive:!0}),await go.copyFile(i,s)}catch(c){if(c.code==="ENOENT"&&!n)return this.doCloneFile(e,t,!0);throw this.toFileSystemProviderError(c)}finally{l.dispose()}}createUniversalWatcher(e,t,n){return new Cp(i=>e(i),i=>t(i),n)}createNonRecursiveWatcher(e,t,n){return new Up(i=>e(i),i=>t(i),n)}toFileSystemProviderError(e){if(e instanceof vs)return e;let t=e,n;switch(e.code){case"ENOENT":n="EntryNotFound";break;case"EISDIR":n="EntryIsADirectory";break;case"ENOTDIR":n="EntryNotADirectory";break;case"EEXIST":n="EntryExists";break;case"EPERM":case"EACCES":n="NoPermissions";break;case"ERR_UNC_HOST_NOT_ALLOWED":t=`${e.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`,n="Unknown";break;default:n="Unknown"}return Fr(t,n)}async toFileSystemProviderWriteError(e,t){let n=this.toFileSystemProviderError(t);if(e&&n.code==="NoPermissions")try{let{stat:i}=await pr.stat(this.toFilePath(e));i.mode&128||(n=Fr(t,"EntryWriteLocked"))}catch(i){this.logService.trace(i)}return n}};var Se=class{constructor(r,e=[],t=!1){this.ctor=r,this.staticArguments=e,this.supportsDelayedInstantiation=t}};var _h=class{constructor(r,e){this.key=r;this.data=e;this.incoming=new Map;this.outgoing=new Map}},bc=class{constructor(r){this._hashFn=r;this._nodes=new Map}roots(){let r=[];for(let e of this._nodes.values())e.outgoing.size===0&&r.push(e);return r}insertEdge(r,e){let t=this.lookupOrInsertNode(r),n=this.lookupOrInsertNode(e);t.outgoing.set(n.key,n),n.incoming.set(t.key,t)}removeNode(r){let e=this._hashFn(r);this._nodes.delete(e);for(let t of this._nodes.values())t.outgoing.delete(e),t.incoming.delete(e)}lookupOrInsertNode(r){let e=this._hashFn(r),t=this._nodes.get(e);return t||(t=new _h(e,r),this._nodes.set(e,t)),t}lookup(r){return this._nodes.get(this._hashFn(r))}isEmpty(){return this._nodes.size===0}toString(){let r=[];for(let[e,t]of this._nodes)r.push(`${e}
	(-> incoming)[${[...t.incoming.keys()].join(", ")}]
	(outgoing ->)[${[...t.outgoing.keys()].join(",")}]
`);return r.join(`
`)}findCycleSlow(){for(let[r,e]of this._nodes){let t=new Set([r]),n=this._findCycle(e,t);if(n)return n}}_findCycle(r,e){for(let[t,n]of r.outgoing){if(e.has(t))return[...e,t].join(" -> ");e.add(t);let i=this._findCycle(n,e);if(i)return i;e.delete(t)}}};var Ei=class{constructor(...r){this._entries=new Map;for(let[e,t]of r)this.set(e,t)}set(r,e){let t=this._entries.get(r);return this._entries.set(r,e),t}has(r){return this._entries.has(r)}get(r){return this._entries.get(r)}};var rR=!1,Mp=class extends Error{constructor(r){super("cyclic dependency between services"),this.message=r.findCycleSlow()??`UNABLE to detect cycle, dumping graph: 
${r.toString()}`}},Ap=class o{constructor(r=new Ei,e=!1,t,n=rR){this._services=r;this._strict=e;this._parent=t;this._enableTracing=n;this._isDisposed=!1;this._servicesToMaybeDispose=new Set;this._children=new Set;this._activeInstantiations=new Set;this._services.set(bt,this),this._globalGraph=n?t?._globalGraph??new bc(i=>i):void 0}dispose(){if(!this._isDisposed){this._isDisposed=!0,$t(this._children),this._children.clear();for(let r of this._servicesToMaybeDispose)qo(r)&&r.dispose();this._servicesToMaybeDispose.clear()}}_throwIfDisposed(){if(this._isDisposed)throw new Error("InstantiationService has been disposed")}createChild(r,e){this._throwIfDisposed();let t=this,n=new class extends o{dispose(){t._children.delete(n),super.dispose()}}(r,this._strict,this,this._enableTracing);return this._children.add(n),e?.add(n),n}invokeFunction(r,...e){this._throwIfDisposed();let t=xc.traceInvocation(this._enableTracing,r),n=!1;try{return r({get:s=>{if(n)throw Zc("service accessor is only valid during the invocation of its target method");let a=this._getOrCreateServiceInstance(s,t);return a||this._throwIfStrict(`[invokeFunction] unknown service '${s}'`,!1),a}},...e)}finally{n=!0,t.stop()}}createInstance(r,...e){this._throwIfDisposed();let t,n;return r instanceof Se?(t=xc.traceCreation(this._enableTracing,r.ctor),n=this._createInstance(r.ctor,r.staticArguments.concat(e),t)):(t=xc.traceCreation(this._enableTracing,r),n=this._createInstance(r,e,t)),t.stop(),n}_createInstance(r,e=[],t){let n=nn.getServiceDependencies(r).sort((a,l)=>a.index-l.index),i=[];for(let a of n){let l=this._getOrCreateServiceInstance(a.id,t);l||this._throwIfStrict(`[createInstance] ${r.name} depends on UNKNOWN service ${a.id}.`,!1),i.push(l)}let s=n.length>0?n[0].index:e.length;if(e.length!==s){console.trace(`[createInstance] First service dependency of ${r.name} at position ${s+1} conflicts with ${e.length} static arguments`);let a=s-e.length;a>0?e=e.concat(new Array(a)):e=e.slice(0,s)}return Reflect.construct(r,e.concat(i))}_setCreatedServiceInstance(r,e){if(this._services.get(r)instanceof Se)this._services.set(r,e);else if(this._parent)this._parent._setCreatedServiceInstance(r,e);else throw new Error("illegalState - setting UNKNOWN service instance")}_getServiceInstanceOrDescriptor(r){let e=this._services.get(r);return!e&&this._parent?this._parent._getServiceInstanceOrDescriptor(r):e}_getOrCreateServiceInstance(r,e){this._globalGraph&&this._globalGraphImplicitDependency&&this._globalGraph.insertEdge(this._globalGraphImplicitDependency,String(r));let t=this._getServiceInstanceOrDescriptor(r);return t instanceof Se?this._safeCreateAndCacheServiceInstance(r,t,e.branch(r,!0)):(e.branch(r,!1),t)}_safeCreateAndCacheServiceInstance(r,e,t){if(this._activeInstantiations.has(r))throw new Error(`illegal state - RECURSIVELY instantiating service '${r}'`);this._activeInstantiations.add(r);try{return this._createAndCacheServiceInstance(r,e,t)}finally{this._activeInstantiations.delete(r)}}_createAndCacheServiceInstance(r,e,t){let n=new bc(l=>l.id.toString()),i=0,s=[{id:r,desc:e,_trace:t}],a=new Set;for(;s.length;){let l=s.pop();if(!a.has(String(l.id))){if(a.add(String(l.id)),n.lookupOrInsertNode(l),i++>1e3)throw new Mp(n);for(let c of nn.getServiceDependencies(l.desc.ctor)){let d=this._getServiceInstanceOrDescriptor(c.id);if(d||this._throwIfStrict(`[createInstance] ${r} depends on ${c.id} which is NOT registered.`,!0),this._globalGraph?.insertEdge(String(l.id),String(c.id)),d instanceof Se){let u={id:c.id,desc:d,_trace:l._trace.branch(c.id,!0)};n.insertEdge(l,u),s.push(u)}}}}for(;;){let l=n.roots();if(l.length===0){if(!n.isEmpty())throw new Mp(n);break}for(let{data:c}of l){if(this._getServiceInstanceOrDescriptor(c.id)instanceof Se){let u=this._createServiceInstanceWithOwner(c.id,c.desc.ctor,c.desc.staticArguments,c.desc.supportsDelayedInstantiation,c._trace);this._setCreatedServiceInstance(c.id,u)}n.removeNode(c)}}return this._getServiceInstanceOrDescriptor(r)}_createServiceInstanceWithOwner(r,e,t=[],n,i){if(this._services.get(r)instanceof Se)return this._createServiceInstance(r,e,t,n,i,this._servicesToMaybeDispose);if(this._parent)return this._parent._createServiceInstanceWithOwner(r,e,t,n,i);throw new Error(`illegalState - creating UNKNOWN service instance ${e.name}`)}_createServiceInstance(r,e,t=[],n,i,s){if(n){let a=new o(void 0,this._strict,this,this._enableTracing);a._globalGraphImplicitDependency=String(r);let l=new Map,c=new Cd(()=>{let d=a._createInstance(e,t,i);for(let[u,p]of l){let m=d[u];if(typeof m=="function")for(let h of p)h.disposable=m.apply(d,h.listener)}return l.clear(),s.add(d),d});return new Proxy(Object.create(null),{get(d,u){if(!c.isInitialized&&typeof u=="string"&&(u.startsWith("onDid")||u.startsWith("onWill"))){let h=l.get(u);return h||(h=new jo,l.set(u,h)),(y,x,E)=>{if(c.isInitialized)return c.value[u](y,x,E);{let R={listener:[y,x,E],disposable:void 0},F=h.push(R);return oe(()=>{F(),R.disposable?.dispose()})}}}if(u in d)return d[u];let p=c.value,m=p[u];return typeof m!="function"||(m=m.bind(p),d[u]=m),m},set(d,u,p){return c.value[u]=p,!0},getPrototypeOf(d){return e.prototype}})}else{let a=this._createInstance(e,t,i);return s.add(a),a}}_throwIfStrict(r,e){if(e&&console.warn(r),this._strict)throw new Error(r)}};var xc=class o{constructor(r,e){this.type=r;this.name=e;this._start=Date.now();this._dep=[]}static{this.all=new Set}static{this._None=new class extends o{constructor(){super(0,null)}stop(){}branch(){return this}}}static traceInvocation(r,e){return r?new o(2,e.name||new Error().stack.split(`
`).slice(3,4).join(`
`)):o._None}static traceCreation(r,e){return r?new o(1,e.name):o._None}static{this._totals=0}branch(r,e){let t=new o(3,r.toString());return this._dep.push([r,e,t]),t}stop(){let r=Date.now()-this._start;o._totals+=r;let e=!1;function t(i,s){let a=[],l=new Array(i+1).join("	");for(let[c,d,u]of s._dep)if(d&&u){e=!0,a.push(`${l}CREATES -> ${c}`);let p=t(i+1,u);p&&a.push(p)}else a.push(`${l}uses -> ${c}`);return a.join(`
`)}let n=[`${this.type===1?"CREATE":"CALL"} ${this.name}`,`${t(1,this)}`,`DONE, took ${r.toFixed(2)}ms (grand total ${o._totals.toFixed(2)}ms)`];(r>2||e)&&o.all.add(n.join(`
`))}};import*as Dx from"fs";import{createHash as nR}from"crypto";var ca=class extends bs{constructor(e,t,n,i){super(n);this.extensionManagementService=e;this.logService=i;this.cache=this._register(new Ec(t,i)),this.extensionManagementService.registerParticipant({postInstall:async s=>this.postInstallExtension(s),postUninstall:async s=>this.postUninstallExtension(s)})}async getBuiltInExtensionTranslationsUri(e,t){let i=(await this.cache.getLanguagePacks())[t];if(!i){this.logService.warn(`No language pack found for ${t}`);return}let s=i.translations[e];return s?P.file(s):void 0}async getInstalledLanguages(){let e=await this.cache.getLanguagePacks(),t=Object.keys(e).map(n=>{let i=e[n];return{...this.createQuickPickItem(n,i.label),extensionId:i.extensions[0].extensionIdentifier.id}});return t.push(this.createQuickPickItem("en","English")),t.sort((n,i)=>n.label.localeCompare(i.label)),t}async postInstallExtension(e){e&&e.manifest&&e.manifest.contributes&&e.manifest.contributes.localizations&&e.manifest.contributes.localizations.length&&(this.logService.info("Adding language packs from the extension",e.identifier.id),await this.update())}async postUninstallExtension(e){let t=await this.cache.getLanguagePacks();Object.keys(t).some(n=>t[n]&&t[n].extensions.some(i=>j(i.extensionIdentifier,e.identifier)))&&(this.logService.info("Removing language packs from the extension",e.identifier.id),await this.update())}async update(){let[e,t]=await Promise.all([this.cache.getLanguagePacks(),this.extensionManagementService.getInstalled()]),n=await this.cache.update(t);return!Pt(Object.keys(e),Object.keys(n))}};ca=b([g(0,rr),g(1,nt),g(2,At),g(3,V)],ca);var Ec=class extends T{constructor(e,t){super();this.logService=t;this.languagePacks={};this.languagePacksFilePath=G(e.userDataPath,"languagepacks.json"),this.languagePacksFileLimiter=new kr}getLanguagePacks(){return this.languagePacksFileLimiter.size||!this.initializedCache?this.withLanguagePacks().then(()=>this.languagePacks):Promise.resolve(this.languagePacks)}update(e){return this.withLanguagePacks(t=>{Object.keys(t).forEach(n=>delete t[n]),this.createLanguagePacksFromExtensions(t,...e)}).then(()=>this.languagePacks)}createLanguagePacksFromExtensions(e,...t){for(let n of t)n&&n.manifest&&n.manifest.contributes&&n.manifest.contributes.localizations&&n.manifest.contributes.localizations.length&&this.createLanguagePacksFromExtension(e,n);Object.keys(e).forEach(n=>this.updateHash(e[n]))}createLanguagePacksFromExtension(e,t){let n=t.identifier,i=t.manifest.contributes&&t.manifest.contributes.localizations?t.manifest.contributes.localizations:[];for(let s of i)if(t.location.scheme===re.file&&iR(s)){let a=e[s.languageId];a||(a={hash:"",extensions:[],translations:{},label:s.localizedLanguageName??s.languageName},e[s.languageId]=a);let l=a.extensions.filter(c=>j(c.extensionIdentifier,n))[0];l?l.version=t.manifest.version:a.extensions.push({extensionIdentifier:n,version:t.manifest.version});for(let c of s.translations)a.translations[c.id]=G(t.location.fsPath,c.path)}}updateHash(e){if(e){let t=nR("md5");for(let n of e.extensions)t.update(n.extensionIdentifier.uuid||n.extensionIdentifier.id).update(n.version);e.hash=t.digest("hex")}}withLanguagePacks(e=()=>null){return this.languagePacksFileLimiter.queue(()=>{let t=null;return Dx.promises.readFile(this.languagePacksFilePath,"utf8").then(void 0,n=>n.code==="ENOENT"?Promise.resolve("{}"):Promise.reject(n)).then(n=>{try{return JSON.parse(n)}catch{return{}}}).then(n=>(t=e(n),n)).then(n=>{for(let s of Object.keys(n))n[s]||delete n[s];this.languagePacks=n,this.initializedCache=!0;let i=JSON.stringify(this.languagePacks);return this.logService.debug("Writing language packs",i),ce.writeFile(this.languagePacksFilePath,i)}).then(()=>t,n=>this.logService.error(n))})}};Ec=b([g(0,nt),g(1,V)],Ec);function iR(o){if(typeof o.languageId!="string"||!Array.isArray(o.translations)||o.translations.length===0)return!1;for(let r of o.translations)if(typeof r.id!="string"||typeof r.path!="string")return!1;return!(o.languageName&&typeof o.languageName!="string"||o.localizedLanguageName&&typeof o.localizedLanguageName!="string")}var Fp=class extends jd{constructor(e,t,n,i,s){super(t,n,i);this.windowId=e;this.channel=s;this._register(s.listen("onDidChangeLogLevel",e)(a=>{hI(a)?super.setLogLevel(a):super.setLogLevel(P.revive(a[0]),a[1])})),this._register(s.listen("onDidChangeVisibility",e)(([a,l])=>super.setVisibility(P.revive(a),l))),this._register(s.listen("onDidChangeLoggers",e)(({added:a,removed:l})=>{for(let c of a)super.registerLogger({...c,resource:P.revive(c.resource)});for(let c of l)super.deregisterLogger(c.resource)}))}createConsoleMainLogger(){return new zd({log:(e,t)=>{this.channel.call("consoleLog",[e,t])}})}registerLogger(e){super.registerLogger(e),this.channel.call("registerLogger",[e,this.windowId])}deregisterLogger(e){let t=this.toResource(e);super.deregisterLogger(t),this.channel.call("deregisterLogger",[t,this.windowId])}setLogLevel(e,t){super.setLogLevel(e,t),this.channel.call("setLogLevel",[e,t])}setVisibility(e,t){super.setVisibility(e,t),this.channel.call("setVisibility",[this.toResource(e),t])}doCreateLogger(e,t,n){return new kh(this.channel,e,t,n,this.windowId)}static setLogLevel(e,t,n){return e.call("setLogLevel",[t,n])}},kh=class extends Gd{constructor(e,t,n,i,s){super(i?.logLevel==="always");this.channel=e;this.file=t;this.isLoggerCreated=!1;this.buffer=[];this.setLevel(n),this.channel.call("createLogger",[t,i,s]).then(()=>{this.doLog(this.buffer),this.isLoggerCreated=!0})}log(e,t){let n=[[e,t]];this.isLoggerCreated?this.doLog(n):this.buffer.push(...n)}doLog(e){this.channel.call("log",[this.file,e])}};var Op=class{constructor(r){this.appenders=r}listen(r,e){throw new Error(`Event not found: ${e}`)}call(r,e,{eventName:t,data:n}){return this.appenders.forEach(i=>i.log(t,n??{})),Promise.resolve(null)}},Np=class{constructor(r){this.channel=r}log(r,e){return this.channel.call("log",{eventName:r,data:e}).then(void 0,t=>`Failed to log telemetry: ${console.warn(t)}`),Promise.resolve(null)}flush(){return Promise.resolve()}};var wi=class extends T{constructor(e,t,n,i,s){super();this.prefix=e;let a=t?"remoteTelemetry":Jg,l=n.getLogger(a);if(l)this.logger=this._register(l);else{let d=Wu(s,i)?" (Not Sent)":"";this.logger=this._register(n.createLogger(a,{name:S(2295,null,d),group:gb,hidden:!0}))}}flush(){return Promise.resolve()}log(e,t){this.logger.trace(`${this.prefix}telemetry/${e}`,$u(t))}};wi=b([g(2,wn),g(3,X),g(4,ne)],wi);var cn=class{constructor(r,e,t){this._configurationService=e;this._productService=t;this._experimentProperties={};this._pendingEvents=[];this._isExperimentPropertySet=!1;this._disposables=new se;this._cleanupPatterns=[];this._appenders=r.appenders,this._commonProperties=r.commonProperties??Object.create(null),this.sessionId=this._commonProperties.sessionID,this.machineId=this._commonProperties["common.machineId"],this.sqmId=this._commonProperties["common.sqmId"],this.devDeviceId=this._commonProperties["common.devDeviceId"],this.firstSessionDate=this._commonProperties["common.firstSessionDate"],this.msftInternal=this._commonProperties["common.msftInternal"],this._piiPaths=r.piiPaths||[],this._telemetryLevel=3,this._sendErrorTelemetry=!!r.sendErrorTelemetry,this._meteredConnectionService=r.meteredConnectionService,this._cleanupPatterns=[/(vscode-)?file:\/\/.*?\/resources\/app\//gi];for(let n of this._piiPaths)this._cleanupPatterns.push(new RegExp(zr(n),"gi")),n.indexOf("\\")>=0&&this._cleanupPatterns.push(new RegExp(zr(n.replace(/\\/g,"/")),"gi"));this._updateTelemetryLevel(),this._disposables.add(this._configurationService.onDidChangeConfiguration(n=>{(n.affectsConfiguration(Fs)||n.affectsConfiguration(lc)||n.affectsConfiguration(Au))&&this._updateTelemetryLevel()})),r.waitForExperimentProperties?this._flushTimeout=setTimeout(()=>this._flushPendingEvents(),cn.BUFFER_FLUSH_TIMEOUT):this._isExperimentPropertySet=!0}static{this.IDLE_START_EVENT_NAME="UserIdleStart"}static{this.IDLE_STOP_EVENT_NAME="UserIdleStop"}static{this.BUFFER_FLUSH_TIMEOUT=1e4}static{this.MAX_BUFFER_SIZE=1e3}setExperimentProperty(r,e){this._experimentProperties[r]=e,this._isExperimentPropertySet||this._flushPendingEvents()}_flushPendingEvents(){if(!this._isExperimentPropertySet){this._isExperimentPropertySet=!0,this._flushTimeout!==void 0&&(clearTimeout(this._flushTimeout),this._flushTimeout=void 0);for(let r of this._pendingEvents)this._doLog(r.eventName,r.eventLevel,r.data);this._pendingEvents=[]}}_updateTelemetryLevel(){let r=Bu(this._configurationService),e=this._productService.enabledTelemetryLevels;if(e){this._sendErrorTelemetry=this.sendErrorTelemetry?e.error:!1;let t=e.usage?3:e.error?2:0;r=Math.min(r,t)}this._telemetryLevel=r}get sendErrorTelemetry(){return this._sendErrorTelemetry}get telemetryLevel(){return this._telemetryLevel}dispose(){this._flushPendingEvents(),this._disposables.dispose()}_log(r,e,t){if(!(this._telemetryLevel<e)&&!this._meteredConnectionService?.isConnectionMetered){if(!this._isExperimentPropertySet){this._pendingEvents.length<cn.MAX_BUFFER_SIZE&&this._pendingEvents.push({eventName:r,eventLevel:e,data:t});return}this._doLog(r,e,t)}}_doLog(r,e,t){t=ks(t,this._experimentProperties),t=Ib(t,this._cleanupPatterns),t=ks(t,this._commonProperties),this._appenders.forEach(n=>n.log(r,t??{}))}publicLog(r,e){this._log(r,3,e)}publicLog2(r,e){this.publicLog(r,e)}publicLogError(r,e){this._sendErrorTelemetry&&this._log(r,2,e)}publicLogError2(r,e){this.publicLogError(r,e)}};cn=b([g(1,Q),g(2,ne)],cn);function oR(){let o=S(2314,null,fr.nameLong,"https://windsurf.com/redirect/windsurf/settings"),r=S(2312,null,fr.nameLong),e=fr.privacyStatementUrl?S(2298,null,"https://aka.ms/vscode-telemetry",fr.privacyStatementUrl):S(2299,null,"https://aka.ms/vscode-telemetry"),t=ze?"":S(2304,null),n=S(2297,null),i=S(2302,null),s=S(2313,null),a=S(2311,null),l=`
|       | ${n} | ${i} | ${s} |
|:------|:-------------:|:---------------:|:----------:|
| all   |       \u2713       |        \u2713        |     \u2713      |
| error |       \u2713       |        \u2713        |     -      |
| crash |       \u2713       |        -        |     -      |
| off   |       -       |        -        |     -      |
`,c=S(2307,null);return`
${o}
${r} ${e} ${t}

&nbsp;

${a}
${l}

&nbsp;

${c}
`}var sR=gt.as(zt.Configuration);sR.registerConfiguration({id:ib,order:1,type:"object",title:S(2315,null),properties:{[Fs]:{type:"string",enum:["all","error","crash","off"],enumDescriptions:[S(2306,null),S(2308,null),S(2305,null),S(2309,null)],markdownDescription:oR(),default:"all",restricted:!0,scope:1,tags:["usesOnlineServices","telemetry"],policy:{name:"TelemetryLevel",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.telemetryLevel.policyDescription",value:S(2310,null)},enumDescriptions:[{key:"telemetry.telemetryLevel.default",value:S(2306,null)},{key:"telemetry.telemetryLevel.error",value:S(2308,null)},{key:"telemetry.telemetryLevel.crash",value:S(2305,null)},{key:"telemetry.telemetryLevel.off",value:S(2309,null)}]}}},"telemetry.feedback.enabled":{type:"boolean",default:!0,description:S(2303,null),policy:{name:"EnableFeedback",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.feedback.enabled",value:S(2303,null)}}}},[lc]:{type:"boolean",markdownDescription:fr.privacyStatementUrl?S(2301,null,fr.nameLong,fr.privacyStatementUrl):S(2300,null,fr.nameLong),default:!0,restricted:!0,markdownDeprecationMessage:S(2296,null,`\`#${Fs}#\``),scope:1,tags:["usesOnlineServices","telemetry"]}}});var da=class{constructor(r,e,t,n,i){this.configurationService=r;this.telemetryService=e;this.loggerService=t;this.environmentService=n;this.productService=i;this.customTelemetryServices=new Map}getCustomTelemetryService(r){if(!this.customTelemetryServices.has(r.id)){let e=Object.create(null);e["common.vscodemachineid"]=this.telemetryService.machineId,e["common.vscodesessionid"]=this.telemetryService.sessionId;let t=[r.id,JSON.stringify(e),r.aiKey],i=new la(dr.asFileUri("bootstrap-fork").fsPath,{serverName:"Debug Telemetry",timeout:1e3*60*5,args:t,env:{ELECTRON_RUN_AS_NODE:1,VSCODE_PIPE_LOGGING:"true",VSCODE_ESM_ENTRYPOINT:"vs/workbench/contrib/debug/node/telemetryApp"}}).getChannel("telemetryAppender"),s=[new Np(i),new wi(`[${r.id}] `,!1,this.loggerService,this.environmentService,this.productService)];this.customTelemetryServices.set(r.id,new cn({appenders:s,sendErrorTelemetry:r.sendErrorTelemetry},this.configurationService,this.productService))}return this.customTelemetryServices.get(r.id)}publicLog(r,e,t){this.getCustomTelemetryService(r).publicLog(e,t)}publicLogError(r,e,t){this.getCustomTelemetryService(r).publicLogError(e,t)}};da=b([g(0,Q),g(1,de),g(2,wn),g(3,X),g(4,ne)],da);var ua=L("IExtensionStorageService"),aR=/^extensionKeys\/([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/,Ot=class extends T{constructor(e,t,n){super();this.storageService=e;this.productService=t;this.logService=n;this._onDidChangeExtensionStorageToSync=this._register(new w);this.onDidChangeExtensionStorageToSync=this._onDidChangeExtensionStorageToSync.event;this.extensionsWithKeysForSync=Ot.readAllExtensionsWithKeysForSync(e),this._register(this.storageService.onDidChangeValue(0,void 0,this._store)(i=>this.onDidChangeStorageValue(i)))}static{this.LARGE_STATE_WARNING_THRESHOLD=512*1024}static toKey(e){return`extensionKeys/${oo(e.id)}@${e.version}`}static fromKey(e){let t=aR.exec(e);if(t&&t[1])return{id:t[1],version:t[2]}}static async removeOutdatedExtensionVersions(e,t){let n=await e.getInstalled(),i=[];for(let[s,a]of Ot.readAllExtensionsWithKeysForSync(t)){let l=n.find(c=>j(c.identifier,{id:s}))?.manifest.version;for(let c of a)l!==c&&i.push(Ot.toKey({id:s,version:c}))}for(let s of i)t.remove(s,0)}static readAllExtensionsWithKeysForSync(e){let t=new Map,n=e.keys(0,1);for(let i of n){let s=Ot.fromKey(i);if(s){let a=t.get(s.id.toLowerCase());a||t.set(s.id.toLowerCase(),a=[]),a.push(s.version)}}return t}onDidChangeStorageValue(e){if(this.extensionsWithKeysForSync.has(e.key.toLowerCase())){this._onDidChangeExtensionStorageToSync.fire();return}let t=Ot.fromKey(e.key);if(t){if(this.storageService.get(e.key,0)===void 0)this.extensionsWithKeysForSync.delete(t.id.toLowerCase());else{let n=this.extensionsWithKeysForSync.get(t.id.toLowerCase());n||this.extensionsWithKeysForSync.set(t.id.toLowerCase(),n=[]),n.push(t.version),this._onDidChangeExtensionStorageToSync.fire()}return}}getExtensionId(e){if(ue(e))return e;let t=e.manifest?e.manifest.publisher:e.publisher,n=e.manifest?e.manifest.name:e.name;return so(t,n)}getExtensionState(e,t){let n=this.getExtensionId(e),i=this.getExtensionStateRaw(e,t);if(i)try{return JSON.parse(i)}catch(s){this.logService.error(`[mainThreadStorage] unexpected error parsing storage contents (extensionId: ${n}, global: ${t}): ${s}`)}}getExtensionStateRaw(e,t){let n=this.getExtensionId(e),i=this.storageService.get(n,t?0:1);return i&&i?.length>Ot.LARGE_STATE_WARNING_THRESHOLD&&this.logService.warn(`[mainThreadStorage] large extension state detected (extensionId: ${n}, global: ${t}): ${i.length/1024}kb. Consider to use 'storageUri' or 'globalStorageUri' to store this data on disk instead.`),i}setExtensionState(e,t,n){let i=this.getExtensionId(e);t===void 0?this.storageService.remove(i,n?0:1):this.storageService.store(i,JSON.stringify(t),n?0:1,1)}setKeysForSync(e,t){this.storageService.store(Ot.toKey(e),JSON.stringify(t),0,1)}getKeysForSync(e){let t=this.productService.extensionSyncedKeys?.[e.id.toLowerCase()],n=this.storageService.get(Ot.toKey(e),0),i=n?JSON.parse(n):void 0;return i&&t?dt([...i,...t]):i||t}addToMigrationList(e,t){if(e!==t){let n=this.migrationList.filter(i=>!i.includes(e)&&!i.includes(t));n.push([e,t]),this.migrationList=n}}getSourceExtensionToMigrate(e){let t=this.migrationList.find(([,n])=>e===n);return t?t[0]:void 0}get migrationList(){let e=this.storageService.get("extensionStorage.migrationList",-1,"[]");try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[]}set migrationList(e){e.length?this.storageService.store("extensionStorage.migrationList",JSON.stringify(e),-1,1):this.storageService.remove("extensionStorage.migrationList",-1)}};Ot=b([g(0,K),g(1,ne),g(2,V)],Ot);var fa=L("IIgnoredExtensionsManagementService"),pa=class{constructor(r){this.configurationService=r}hasToNeverSyncExtension(r){return this.getConfiguredIgnoredExtensions().includes(r.toLowerCase())}hasToAlwaysSyncExtension(r){return this.getConfiguredIgnoredExtensions().includes(`-${r.toLowerCase()}`)}updateIgnoredExtensions(r,e){let t=[...this.configurationService.getValue("settingsSync.ignoredExtensions")].map(n=>n.toLowerCase());return t=t.filter(n=>n!==r&&n!==`-${r}`),e&&t.push(r.toLowerCase()),this.configurationService.updateValue("settingsSync.ignoredExtensions",t.length?t:void 0,2)}updateSynchronizedExtensions(r,e){let t=[...this.configurationService.getValue("settingsSync.ignoredExtensions")].map(n=>n.toLowerCase());return t=t.filter(n=>n!==r&&n!==`-${r}`),e&&t.push(`-${r.toLowerCase()}`),this.configurationService.updateValue("settingsSync.ignoredExtensions",t.length?t:void 0,2)}getIgnoredExtensions(r){let e=r.filter(s=>s.isMachineScoped).map(s=>s.identifier.id.toLowerCase()),t=this.getConfiguredIgnoredExtensions().map(s=>s.toLowerCase()),n=[],i=[];if(Array.isArray(t))for(let s of t)s.startsWith("-")?i.push(s.substring(1)):n.push(s);return dt([...e,...n].filter(s=>!i.includes(s)))}getConfiguredIgnoredExtensions(){return(this.configurationService.getValue("settingsSync.ignoredExtensions")||[]).map(r=>r.toLowerCase())}};pa=b([g(0,Q)],pa);function Vp(){let o=gt.as(zt.Configuration).getConfigurationProperties();return Object.keys(o).filter(r=>!!o[r].disallowSyncIgnore)}function lR(o=!1){let r=gt.as(zt.Configuration).getConfigurationProperties(),e=_x(r,o),t=Vp();return dt([...e,...t])}function Uh(o){if(!o.contributes?.configuration)return[];let r=Array.isArray(o.contributes.configuration)?o.contributes.configuration:[o.contributes.configuration];if(!r.length)return[];let e=gg(r);return _x(e,!1)}function _x(o,r){let e=new Set;for(let t in o){if(r&&o[t].source)continue;let n=ue(o[t].scope)?CI(o[t].scope):o[t].scope;(o[t].ignoreSync||n===2||n===7)&&e.add(t)}return[...e.values()]}var ho="settingsSync",wc="settingsSync.keybindingsPerPlatform";function kx(){let o="vscode://schemas/ignoredSettings",r=gt.as(zt.Configuration);r.registerConfiguration({id:"settingsSync",order:30,title:S(2718,null),type:"object",properties:{[wc]:{type:"boolean",description:S(2721,null),default:!0,scope:1,tags:["sync","usesOnlineServices"]},"settingsSync.ignoredExtensions":{type:"array",markdownDescription:S(2719,null),items:[{type:"string",pattern:xg,errorMessage:S(2717,null)}],default:[],scope:1,uniqueItems:!0,disallowSyncIgnore:!0,tags:["sync","usesOnlineServices"]},"settingsSync.ignoredSettings":{type:"array",description:S(2720,null),default:[],scope:1,$ref:o,additionalProperties:!0,uniqueItems:!0,disallowSyncIgnore:!0,tags:["sync","usesOnlineServices"]}}});let e=gt.as(Hl.JSONContribution),t=()=>{let n=Vp(),i=lR(),s=Object.keys(ms.properties).filter(c=>!i.includes(c)),a=i.filter(c=>!n.includes(c)),l={items:{type:"string",enum:[...s,...a.map(c=>`-${c}`)]}};e.registerSchema(o,l)};return r.onDidUpdateConfiguration(()=>t())}var Ux="0";var Dn=["settings","keybindings","snippets","prompts","tasks","extensions","globalState","profiles","mcp"];function Lh(o,...r){return o?[o,...r]:r}function Mh(o,r,e,t){return t.joinPath(e.userDataSyncHome,...Lh(o,r,`lastSync${r}.json`))}function Lx(o){return o&&ue(o.session)&&ue(o.ref)&&(Re(o.latest)||o.latest===void 0)&&(Re(o.collections)||o.collections===void 0)}var Pr=L("IUserDataSyncStoreManagementService"),Ce=L("IUserDataSyncStoreService"),Qe=L("IUserDataSyncLocalStoreService"),un="x-operation-id",Ah="X-Execution-Id";function Pi(o){let r={};return r[Ah]=o,r}var xe=class extends Error{constructor(e,t,n,i){super(e);this.code=t;this.resource=n;this.operationId=i;this.name=`${this.code} (UserDataSyncError) syncResource:${this.resource||"unknown"} operationId:${this.operationId||"unknown"}`}},Ae=class extends xe{constructor(e,t,n,i,s){super(e,n,void 0,s);this.url=t;this.serverCode=i}},dn=class extends xe{constructor(r,e){super(r,e)}};(r=>{function o(e){if(e instanceof r)return e;let t=/^(.+) \(UserDataSyncError\) syncResource:(.+) operationId:(.+)$/.exec(e.name);if(t&&t[1]){let n=t[2]==="unknown"?void 0:t[2],i=t[3]==="unknown"?void 0:t[3];return new r(e.message,t[1],n,i)}return new r(e.message,"Unknown")}r.toUserDataSyncError=o})(xe||={});var pn="sync.store.url.type";function vo(o){return`sync.enable.${o}`}var Oe=L("IUserDataSyncEnablementService"),yo=L("IUserDataSyncService"),Pc=L("IUserDataSyncResourceProviderService"),iK=L("IUserDataAutoSyncService"),Ri=L("IUserDataSyncUtilService"),me=L("IUserDataSyncLogService"),Fh="userDataSync",M="vscode-userdata-sync",Mx="preview";var So=L("IUserDataSyncAccountService"),ma=class extends T{constructor(e,t){super();this.userDataSyncStoreService=e;this.logService=t;this._onDidChangeAccount=this._register(new w);this.onDidChangeAccount=this._onDidChangeAccount.event;this._onTokenFailed=this._register(new w);this.onTokenFailed=this._onTokenFailed.event;this.wasTokenFailed=!1;this._register(e.onTokenFailed(n=>{this.logService.info("Settings Sync auth token failed",this.account?.authenticationProviderId,this.wasTokenFailed,n),this.updateAccount(void 0),n==="Forbidden"?this._onTokenFailed.fire(!0):this._onTokenFailed.fire(this.wasTokenFailed),this.wasTokenFailed=!0})),this._register(e.onTokenSucceed(()=>this.wasTokenFailed=!1))}get account(){return this._account}async updateAccount(e){(e&&this._account?e.token!==this._account.token||e.authenticationProviderId!==this._account.authenticationProviderId:e!==this._account)&&(this._account=e,this._account&&this.userDataSyncStoreService.setAuthToken(this._account.token,this._account.authenticationProviderId),this._onDidChangeAccount.fire(e))}};ma=b([g(0,Ce),g(1,me)],ma);var cR=60,dR=cR*60,Oh=dR*24,hK=Oh*7,vK=Oh*30,yK=Oh*365;function ga(o){return o.getFullYear()+"-"+String(o.getMonth()+1).padStart(2,"0")+"-"+String(o.getDate()).padStart(2,"0")+"T"+String(o.getHours()).padStart(2,"0")+":"+String(o.getMinutes()).padStart(2,"0")+":"+String(o.getSeconds()).padStart(2,"0")+"."+(o.getMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"}var ha=class extends T{constructor(e,t,n,i,s){super();this.environmentService=e;this.fileService=t;this.configurationService=n;this.logService=i;this.userDataProfilesService=s;this.cleanUp()}async cleanUp(){for(let t of this.userDataProfilesService.profiles)for(let n of Dn)try{await this.cleanUpBackup(this.getResourceBackupHome(n,t.isDefault?void 0:t.id))}catch(i){this.logService.error(i)}let e;try{e=await this.fileService.resolve(this.environmentService.userDataSyncHome)}catch(t){_e(t)!==1&&this.logService.error(t);return}if(e.children){for(let t of e.children)if(t.isDirectory&&!Dn.includes(t.name)&&!this.userDataProfilesService.profiles.some(n=>n.id===t.name))try{this.logService.info("Deleting non existing profile from backup",t.resource.path),await this.fileService.del(t.resource,{recursive:!0})}catch(n){this.logService.error(n)}}}async getAllResourceRefs(e,t,n){let i=this.getResourceBackupHome(e,t,n);try{let s=await this.fileService.resolve(i);if(s.children)return s.children.filter(l=>l.isFile&&!l.name.startsWith("lastSync")).sort().reverse().map(l=>({ref:l.name,created:this.getCreationTime(l)}))}catch(s){if(_e(s)!==1)throw s}return[]}async resolveResourceContent(e,t,n,i){let s=this.getResourceBackupHome(e,n,i),a=$(s,t);try{return(await this.fileService.readFile(a)).value.toString()}catch(l){return this.logService.error(l),null}}async writeResource(e,t,n,i,s){let a=this.getResourceBackupHome(e,i,s),l=$(a,`${ga(n).replace(/-|:|\.\d+Z$/g,"")}.json`);try{await this.fileService.writeFile(l,U.fromString(t))}catch(c){this.logService.error(c)}}getResourceBackupHome(e,t,n=this.environmentService.userDataSyncHome){return $(n,...t?[t,e]:[e])}async cleanUpBackup(e){try{try{if(!await this.fileService.exists(e))return}catch{return}let t=await this.fileService.resolve(e);if(t.children){let n=t.children.filter(l=>l.isFile&&/^\d{8}T\d{6}(\.json)?$/.test(l.name)).sort(),i=1e3*60*60*24*(this.configurationService.getValue("sync.localBackupDuration")||30),s=n.filter(l=>Date.now()-this.getCreationTime(l)>i),a=n.length-s.length;a<10&&(s=s.slice(10-a)),await Ke.settled(s.map(async l=>{this.logService.info("Deleting from backup",l.resource.path),await this.fileService.del(l.resource)}))}}catch(t){this.logService.error(t)}}getCreationTime(e){return new Date(parseInt(e.name.substring(0,4)),parseInt(e.name.substring(4,6))-1,parseInt(e.name.substring(6,8)),parseInt(e.name.substring(9,11)),parseInt(e.name.substring(11,13)),parseInt(e.name.substring(13,15))).getTime()}};ha=b([g(0,X),g(1,W),g(2,Q),g(3,me),g(4,fe)],ha);var Wp=Object.freeze({text:"text/plain",binary:"application/octet-stream",unknown:"application/unknown",markdown:"text/markdown",latex:"text/latex",uriList:"text/uri-list",html:"text/html"});var Ax="configurationSync.store",Nh="sync.previous.store",Vh="sync.donot-make-requests-until",Bp="sync.user-session-id",Wh="sync.machine-session-id",uR=100,pR=1e3*60*5,Io=class extends T{constructor(e,t,n){super();this.productService=e;this.configurationService=t;this.storageService=n;this._onDidChangeUserDataSyncStore=this._register(new w);this.onDidChangeUserDataSyncStore=this._onDidChangeUserDataSyncStore.event;this.updateUserDataSyncStore();let i=this._register(new se);this._register(k.filter(n.onDidChangeValue(-1,pn,i),()=>this.userDataSyncStoreType!==this.userDataSyncStore?.type,i)(()=>this.updateUserDataSyncStore()))}get userDataSyncStore(){return this._userDataSyncStore}get userDataSyncStoreType(){return this.storageService.get(pn,-1)}set userDataSyncStoreType(e){this.storageService.store(pn,e,-1,ze?0:1)}updateUserDataSyncStore(){this._userDataSyncStore=this.toUserDataSyncStore(this.productService[Ax]),this._onDidChangeUserDataSyncStore.fire()}toUserDataSyncStore(e){if(e&&(e=ze&&e.web?{...e,...e.web}:e,ue(e.url)&&Re(e.authenticationProviders)&&Object.keys(e.authenticationProviders).every(t=>Array.isArray(e.authenticationProviders[t].scopes)))){let t=e,n=!!t.canSwitch,i=t.url===t.insidersUrl?"insiders":"stable",s=(n?this.userDataSyncStoreType:void 0)||i,a=s==="insiders"?t.insidersUrl:s==="stable"?t.stableUrl:t.url;return{url:P.parse(a),type:s,defaultType:i,defaultUrl:P.parse(t.url),stableUrl:P.parse(t.stableUrl),insidersUrl:P.parse(t.insidersUrl),canSwitch:n,authenticationProviders:Object.keys(t.authenticationProviders).reduce((l,c)=>(l.push({id:c,scopes:t.authenticationProviders[c].scopes}),l),[])}}}};Io=b([g(0,ne),g(1,Q),g(2,K)],Io);var va=class extends Io{constructor(r,e,t){super(r,e,t);let n=this.storageService.get(Nh,-1);n&&(this.previousConfigurationSyncStore=JSON.parse(n));let i=this.productService[Ax];i?this.storageService.store(Nh,JSON.stringify(i),-1,1):this.storageService.remove(Nh,-1)}async switch(r){r!==this.userDataSyncStoreType&&(this.userDataSyncStoreType=r,this.updateUserDataSyncStore())}async getPreviousUserDataSyncStore(){return this.toUserDataSyncStore(this.previousConfigurationSyncStore)}};va=b([g(0,ne),g(1,Q),g(2,K)],va);var Rc=class extends T{constructor(e,t,n,i,s,a,l){super();this.requestService=n;this.logService=i;this.storageService=l;this._onTokenFailed=this._register(new w);this.onTokenFailed=this._onTokenFailed.event;this._onTokenSucceed=this._register(new w);this.onTokenSucceed=this._onTokenSucceed.event;this._donotMakeRequestsUntil=void 0;this._onDidChangeDonotMakeRequestsUntil=this._register(new w);this.onDidChangeDonotMakeRequestsUntil=this._onDidChangeDonotMakeRequestsUntil.event;this.resetDonotMakeRequestsUntilPromise=void 0;this.updateUserDataSyncStoreUrl(e),this.commonHeadersPromise=Hr(s,a,l).then(c=>{let d={"X-Client-Name":`${t.applicationName}${ze?"-web":""}`,"X-Client-Version":t.version};return t.commit&&(d["X-Client-Commit"]=t.commit),d}),this.session=new Bh(uR,pR,this.requestService,this.logService),this.initDonotMakeRequestsUntil(),this._register(oe(()=>{this.resetDonotMakeRequestsUntilPromise&&(this.resetDonotMakeRequestsUntilPromise.cancel(),this.resetDonotMakeRequestsUntilPromise=void 0)}))}get donotMakeRequestsUntil(){return this._donotMakeRequestsUntil}setAuthToken(e,t){this.authToken={token:e,type:t}}updateUserDataSyncStoreUrl(e){this.userDataSyncStoreUrl=e?$(e,"v1"):void 0}initDonotMakeRequestsUntil(){let e=this.storageService.getNumber(Vh,-1);e&&Date.now()<e&&this.setDonotMakeRequestsUntil(new Date(e))}setDonotMakeRequestsUntil(e){this._donotMakeRequestsUntil?.getTime()!==e?.getTime()&&(this._donotMakeRequestsUntil=e,this.resetDonotMakeRequestsUntilPromise&&(this.resetDonotMakeRequestsUntilPromise.cancel(),this.resetDonotMakeRequestsUntilPromise=void 0),this._donotMakeRequestsUntil?(this.storageService.store(Vh,this._donotMakeRequestsUntil.getTime(),-1,1),this.resetDonotMakeRequestsUntilPromise=Je(t=>Lr(this._donotMakeRequestsUntil.getTime()-Date.now(),t).then(()=>this.setDonotMakeRequestsUntil(void 0))),this.resetDonotMakeRequestsUntilPromise.then(null,t=>null)):this.storageService.remove(Vh,-1),this._onDidChangeDonotMakeRequestsUntil.fire())}async getAllCollections(e={}){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let t=$(this.userDataSyncStoreUrl,"collection").toString();e={...e},e["Content-Type"]="application/json";let n=await this.request(t,{type:"GET",headers:e},[],Y.None);return(await jr(n))?.map(({id:i})=>i)||[]}async createCollection(e={}){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let t=$(this.userDataSyncStoreUrl,"collection").toString();e={...e},e["Content-Type"]=Wp.text;let n=await this.request(t,{type:"POST",headers:e},[],Y.None),i=await Vr(n);if(!i)throw new Ae("Server did not return the collection id",t,"NoCollection",n.res.statusCode,n.res.headers[un]);return i}async deleteCollection(e,t={}){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let n=e?$(this.userDataSyncStoreUrl,"collection",e).toString():$(this.userDataSyncStoreUrl,"collection").toString();t={...t},await this.request(n,{type:"DELETE",headers:t},[],Y.None)}async getAllResourceRefs(e,t){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let n=this.getResourceUrl(this.userDataSyncStoreUrl,t,e),i={},s=await this.request(n.toString(),{type:"GET",headers:i},[],Y.None);return(await jr(s)||[]).map(({url:l,created:c})=>({ref:_S(n,n.with({path:l})),created:c*1e3}))}async resolveResourceContent(e,t,n,i={}){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let s=$(this.getResourceUrl(this.userDataSyncStoreUrl,n,e),t).toString();i={...i},i["Cache-Control"]="no-cache";let a=await this.request(s,{type:"GET",headers:i},[],Y.None);return await Vr(a)}async deleteResource(e,t,n){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let i=t!==null?$(this.getResourceUrl(this.userDataSyncStoreUrl,n,e),t).toString():this.getResourceUrl(this.userDataSyncStoreUrl,n,e).toString(),s={};await this.request(i,{type:"DELETE",headers:s},[],Y.None)}async deleteResources(){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let e=$(this.userDataSyncStoreUrl,"resource").toString(),t={"Content-Type":Wp.text};await this.request(e,{type:"DELETE",headers:t},[],Y.None)}async readResource(e,t,n,i={}){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let s=$(this.getResourceUrl(this.userDataSyncStoreUrl,n,e),"latest").toString();i={...i},i["Cache-Control"]="no-cache",t&&(i["If-None-Match"]=t.ref);let a=await this.request(s,{type:"GET",headers:i},[304],Y.None),l=null;if(a.res.statusCode===304&&(l=t),l===null){let c=a.res.headers.etag;if(!c)throw new Ae("Server did not return the ref",s,"NoRef",a.res.statusCode,a.res.headers[un]);let d=await Vr(a);if(!d&&a.res.statusCode===304)throw new Ae("Empty response",s,"EmptyResponse",a.res.statusCode,a.res.headers[un]);l={ref:c,content:d}}return l}async writeResource(e,t,n,i,s={}){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let a=this.getResourceUrl(this.userDataSyncStoreUrl,i,e).toString();s={...s},s["Content-Type"]=Wp.text,n&&(s["If-Match"]=n);let l=await this.request(a,{type:"POST",data:t,headers:s},[],Y.None),c=l.res.headers.etag;if(!c)throw new Ae("Server did not return the ref",a,"NoRef",l.res.statusCode,l.res.headers[un]);return c}async manifest(e,t={}){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let n=$(this.userDataSyncStoreUrl,"manifest").toString();t={...t},t["Content-Type"]="application/json",e&&(t["If-None-Match"]=e.ref);let i=await this.request(n,{type:"GET",headers:t},[304],Y.None),s=null;if(i.res.statusCode===304&&(s=e),!s){let l=i.res.headers.etag;if(!l)throw new Ae("Server did not return the ref",n,"NoRef",i.res.statusCode,i.res.headers[un]);let c=await Vr(i);if(!c&&i.res.statusCode===304)throw new Ae("Empty response",n,"EmptyResponse",i.res.statusCode,i.res.headers[un]);c&&(s={...JSON.parse(c),ref:l})}let a=this.storageService.get(Bp,-1);return a&&s&&a!==s.session&&this.clearSession(),s===null&&a&&this.clearSession(),s&&this.storageService.store(Bp,s.session,-1,1),s}async clear(){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");await this.deleteCollection(),await this.deleteResources(),this.clearSession()}async getLatestData(e={}){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let t=$(this.userDataSyncStoreUrl,"download","latest").toString();e={...e},e["Content-Type"]="application/json";let n=await this.request(t,{type:"GET",headers:e},[],Y.None);if(!Kn(n))throw new Ae("Server returned "+n.res.statusCode,t,"EmptyResponse",n.res.statusCode,n.res.headers[un]);let i=await jr(n);if(!i)return null;let s={};if(i.resources){s.resources={};for(let a in i.resources){let[l]=i.resources[a];s.resources[a]={content:l.content,ref:l.ref}}}if(i.collections){s.collections={};for(let a in i.collections){let l={};s.collections[a]={resources:l};for(let c in i.collections[a].resources){let[d]=i.collections[a].resources[c];l[c]={content:d.content,ref:d.ref}}}}return s}async getActivityData(){if(!this.userDataSyncStoreUrl)throw new Error("No settings sync store url configured.");let e=$(this.userDataSyncStoreUrl,"download").toString(),t={},n=await this.request(e,{type:"GET",headers:t},[],Y.None);if(!Kn(n))throw new Ae("Server returned "+n.res.statusCode,e,"EmptyResponse",n.res.statusCode,n.res.headers[un]);if(Nu(n))throw new Ae("Empty response",e,"EmptyResponse",n.res.statusCode,n.res.headers[un]);return n.stream}getResourceUrl(e,t,n){return t?$(e,"collection",t,"resource",n):$(e,"resource",n)}clearSession(){this.storageService.remove(Bp,-1),this.storageService.remove(Wh,-1)}async request(e,t,n,i){if(!this.authToken)throw new Ae("No Auth Token Available",e,"Unauthorized",void 0,void 0);if(this._donotMakeRequestsUntil&&Date.now()<this._donotMakeRequestsUntil.getTime())throw new Ae(`${t.type} request '${e}' failed because of too many requests (429).`,e,"TooManyRequestsAndRetryAfter",void 0,void 0);this.setDonotMakeRequestsUntil(void 0);let s=await this.commonHeadersPromise;t.headers={...t.headers||{},...s,"X-Account-Type":this.authToken.type,authorization:`Bearer ${this.authToken.token}`},this.addSessionHeaders(t.headers),this.logService.trace("Sending request to server",{url:e,type:t.type,headers:{...t.headers,authorization:void 0}});let a;try{a=await this.session.request(e,t,i)}catch(p){if(!(p instanceof Ae)){let m="RequestFailed",h=ee(p).toLowerCase();h.includes("xhr timeout")?m="RequestTimeout":h.includes("protocol")&&h.includes("not supported")?m="RequestProtocolNotSupported":h.includes("request path contains unescaped characters")?m="RequestPathNotEscaped":h.includes("headers must be an object")?m="RequestHeadersNotObject":lr(p)&&(m="RequestCanceled"),p=new Ae(`Connection refused for the request '${e}'.`,e,m,void 0,void 0)}throw this.logService.info("Request failed",e),p}let l=a.res.headers[un],c={url:e,status:a.res.statusCode,"execution-id":t.headers[Ah],"operation-id":l},d=Kn(a)||a.res.statusCode&&n.includes(a.res.statusCode),u="";if(d?this.logService.trace("Request succeeded",c):(u=await cc(a)||"",this.logService.info("Request failed",c,u)),a.res.statusCode===401||a.res.statusCode===403){if(this.authToken=void 0,a.res.statusCode===401)throw this._onTokenFailed.fire("Unauthorized"),new Ae(`${t.type} request '${e}' failed because of Unauthorized (401).`,e,"Unauthorized",a.res.statusCode,l);if(a.res.statusCode===403)throw this._onTokenFailed.fire("Forbidden"),new Ae(`${t.type} request '${e}' failed because the access is forbidden (403).`,e,"Forbidden",a.res.statusCode,l)}if(this._onTokenSucceed.fire(),a.res.statusCode===404)throw new Ae(`${t.type} request '${e}' failed because the requested resource is not found (404).`,e,"NotFound",a.res.statusCode,l);if(a.res.statusCode===405)throw new Ae(`${t.type} request '${e}' failed because the requested endpoint is not found (405). ${u}`,e,"MethodNotFound",a.res.statusCode,l);if(a.res.statusCode===409)throw new Ae(`${t.type} request '${e}' failed because of Conflict (409). There is new data for this resource. Make the request again with latest data.`,e,"Conflict",a.res.statusCode,l);if(a.res.statusCode===410)throw new Ae(`${t.type} request '${e}' failed because the requested resource is not longer available (410).`,e,"Gone",a.res.statusCode,l);if(a.res.statusCode===412)throw new Ae(`${t.type} request '${e}' failed because of Precondition Failed (412). There is new data for this resource. Make the request again with latest data.`,e,"PreconditionFailed",a.res.statusCode,l);if(a.res.statusCode===413)throw new Ae(`${t.type} request '${e}' failed because of too large payload (413).`,e,"TooLarge",a.res.statusCode,l);if(a.res.statusCode===426)throw new Ae(`${t.type} request '${e}' failed with status Upgrade Required (426). Please upgrade the client and try again.`,e,"UpgradeRequired",a.res.statusCode,l);if(a.res.statusCode===429){let p=a.res.headers["retry-after"];throw p?(this.setDonotMakeRequestsUntil(new Date(Date.now()+parseInt(p)*1e3)),new Ae(`${t.type} request '${e}' failed because of too many requests (429).`,e,"TooManyRequestsAndRetryAfter",a.res.statusCode,l)):new Ae(`${t.type} request '${e}' failed because of too many requests (429).`,e,"RemoteTooManyRequests",a.res.statusCode,l)}if(!d)throw new Ae("Server returned "+a.res.statusCode,e,"Unknown",a.res.statusCode,l);return a}addSessionHeaders(e){let t=this.storageService.get(Wh,-1);t===void 0&&(t=Le(),this.storageService.store(Wh,t,-1,1)),e["X-Machine-Session-Id"]=t;let n=this.storageService.get(Bp,-1);n!==void 0&&(e["X-User-Session-Id"]=n)}};Rc=b([g(1,ne),g(2,Nr),g(3,me),g(4,X),g(5,W),g(6,K)],Rc);var ya=class extends Rc{constructor(r,e,t,n,i,s,a){super(r.userDataSyncStore?.url,e,t,n,i,s,a),this._register(r.onDidChangeUserDataSyncStore(()=>this.updateUserDataSyncStoreUrl(r.userDataSyncStore?.url)))}};ya=b([g(0,Pr),g(1,ne),g(2,Nr),g(3,me),g(4,X),g(5,W),g(6,K)],ya);var Bh=class{constructor(r,e,t,n){this.limit=r;this.interval=e;this.requestService=t;this.logService=n;this.requests=[];this.startTime=void 0}request(r,e,t){if(this.isExpired()&&this.reset(),e.url=r,this.requests.length>=this.limit)throw this.logService.info("Too many requests",...this.requests),new Ae(`Too many requests. Only ${this.limit} requests allowed in ${this.interval/(1e3*60)} minutes.`,r,"LocalTooManyRequests",void 0,void 0);return this.startTime=this.startTime||new Date,this.requests.push(r),this.requestService.request(e,t)}isExpired(){return this.startTime!==void 0&&new Date().getTime()-this.startTime.getTime()>this.interval}reset(){this.requests=[],this.startTime=void 0}};var Gp=class{constructor(r){this.service=r}listen(r,e){switch(e){case"onDidChangeAccount":return this.service.onDidChangeAccount;case"onTokenFailed":return this.service.onTokenFailed}throw new Error(`[UserDataSyncAccountServiceChannel] Event not found: ${e}`)}call(r,e,t){switch(e){case"_getInitialData":return Promise.resolve(this.service.account);case"updateAccount":return this.service.updateAccount(t)}throw new Error("Invalid call")}};var qp=class{constructor(r){this.service=r}listen(r,e){if(e==="onDidChangeUserDataSyncStore")return this.service.onDidChangeUserDataSyncStore;throw new Error(`[UserDataSyncStoreManagementServiceChannel] Event not found: ${e}`)}call(r,e,t){switch(e){case"switch":return this.service.switch(t[0]);case"getPreviousUserDataSyncStore":return this.service.getPreviousUserDataSyncStore()}throw new Error("Invalid call")}},$p=class extends Io{constructor(e,t,n,i){super(t,n,i);this.channel=e;this._register(this.channel.listen("onDidChangeUserDataSyncStore")(()=>this.updateUserDataSyncStore()))}async switch(e){return this.channel.call("switch",[e])}async getPreviousUserDataSyncStore(){let e=await this.channel.call("getPreviousUserDataSyncStore");return this.revive(e)}revive(e){return{url:P.revive(e.url),type:e.type,defaultUrl:P.revive(e.defaultUrl),insidersUrl:P.revive(e.insidersUrl),stableUrl:P.revive(e.stableUrl),canSwitch:e.canSwitch,authenticationProviders:e.authenticationProviders}}};$p=b([g(1,ne),g(2,Q),g(3,K)],$p);var Sa=class extends ui{constructor(r,e){super(),this.logger=this._register(r.createLogger($(e.logsHome,`${Fh}.log`),{id:Fh,name:S(2722,null)}))}trace(r,...e){this.logger.trace(r,...e)}debug(r,...e){this.logger.debug(r,...e)}info(r,...e){this.logger.info(r,...e)}warn(r,...e){this.logger.warn(r,...e)}error(r,...e){this.logger.error(r,...e)}flush(){this.logger.flush()}};Sa=b([g(0,wn),g(1,X)],Sa);var bo=L("IUserDataSyncMachinesService"),$h="sync.currentMachineName",fR="Safari",mR="Chrome",gR="Edge",hR="Firefox",vR="Android";function Fx(){return ud?fR:xl?mR:pd?gR:dd?hR:Yy?vR:cd(ze?0:In)}var Xr=class extends T{constructor(e,t,n,i,s,a){super();this.storageService=n;this.userDataSyncStoreService=i;this.logService=s;this.productService=a;this._onDidChange=this._register(new w);this.onDidChange=this._onDidChange.event;this.userData=null;this.currentMachineIdPromise=Hr(e,t,n)}static{this.VERSION=1}static{this.RESOURCE="machines"}async getMachines(e){let t=await this.currentMachineIdPromise;return(await this.readMachinesData(e)).machines.map(i=>({...i,isCurrent:i.id===t}))}async addCurrentMachine(e){let t=await this.currentMachineIdPromise,n=await this.readMachinesData(e);n.machines.some(({id:i})=>i===t)||(n.machines.push({id:t,name:this.computeCurrentMachineName(n.machines),platform:Fx()}),await this.writeMachinesData(n))}async removeCurrentMachine(e){let t=await this.currentMachineIdPromise,n=await this.readMachinesData(e),i=n.machines.filter(({id:s})=>s!==t);i.length!==n.machines.length&&(n.machines=i,await this.writeMachinesData(n))}async renameMachine(e,t,n){let i=await this.readMachinesData(n),s=i.machines.find(({id:a})=>a===e);if(s){s.name=t,await this.writeMachinesData(i);let a=await this.currentMachineIdPromise;e===a&&this.storageService.store($h,t,-1,1)}}async setEnablements(e){let t=await this.readMachinesData();for(let[n,i]of e){let s=t.machines.find(a=>a.id===n);s&&(s.disabled=i?void 0:!0)}await this.writeMachinesData(t)}computeCurrentMachineName(e){let t=this.storageService.get($h,-1);if(t){if(!e.some(a=>a.name===t))return t;this.storageService.remove($h,-1)}let n=`${this.productService.embedderIdentifier?`${this.productService.embedderIdentifier} - `:""}${Fx()} (${this.productService.nameShort})`,i=new RegExp(`${zr(n)}\\s#(\\d+)`),s=0;for(let a of e){let l=i.exec(a.name),c=l?parseInt(l[1]):0;s=c>s?c:s}return`${n} #${s+1}`}async readMachinesData(e){this.userData=await this.readUserData(e);let t=this.parse(this.userData);if(t.version!==Xr.VERSION)throw new Error(S(2723,null,this.productService.nameLong));return t}async writeMachinesData(e){let t=JSON.stringify(e),n=await this.userDataSyncStoreService.writeResource(Xr.RESOURCE,t,this.userData?.ref||null);this.userData={ref:n,content:t},this._onDidChange.fire()}async readUserData(e){if(this.userData){let t=e&&e.latest?e.latest[Xr.RESOURCE]:void 0;if(this.userData.ref===t)return this.userData;if(t===void 0&&this.userData.content===null)return this.userData}return this.userDataSyncStoreService.readResource(Xr.RESOURCE,this.userData)}parse(e){if(e.content!==null)try{return JSON.parse(e.content)}catch(t){this.logService.error(t)}return{version:Xr.VERSION,machines:[]}}};Xr=b([g(0,X),g(1,W),g(2,K),g(3,Ce),g(4,me),g(5,ne)],Xr);var Gh="sync.enable",Ia=class extends T{constructor(e,t,n){super();this.storageService=e;this.environmentService=t;this.userDataSyncStoreManagementService=n;this._onDidChangeEnablement=this._register(new w);this.onDidChangeEnablement=this._onDidChangeEnablement.event;this._onDidChangeResourceEnablement=this._register(new w);this.onDidChangeResourceEnablement=this._onDidChangeResourceEnablement.event;this._register(e.onDidChangeValue(-1,void 0,this._store)(i=>this.onDidStorageChange(i)))}isEnabled(){switch(this.environmentService.sync){case"on":return!0;case"off":return!1}return this.storageService.getBoolean(Gh,-1,!1)}canToggleEnablement(){return this.userDataSyncStoreManagementService.userDataSyncStore!==void 0&&this.environmentService.sync===void 0}setEnablement(e){e&&!this.canToggleEnablement()||this.storageService.store(Gh,e,-1,1)}isResourceEnabled(e,t){let n=this.storageService.getBoolean(vo(e),-1);return t=t??e!=="prompts",n??t}isResourceEnablementConfigured(e){return this.storageService.getBoolean(vo(e),-1)!==void 0}setResourceEnablement(e,t){if(this.isResourceEnabled(e)!==t){let n=vo(e);this.storeResourceEnablement(n,t)}}getResourceSyncStateVersion(e){}storeResourceEnablement(e,t){this.storageService.store(e,t,-1,ze?0:1)}onDidStorageChange(e){if(Gh===e.key){this._onDidChangeEnablement.fire(this.isEnabled());return}let t=Dn.filter(n=>vo(n)===e.key)[0];if(t){this._onDidChangeResourceEnablement.fire([t,this.isResourceEnabled(t)]);return}}};Ia=b([g(0,K),g(1,X),g(2,Pr)],Ia);function yR(o){return!!(o&&o.ref!==void 0&&typeof o.ref=="string"&&o.ref!==""&&o.syncData!==void 0&&(o.syncData===null||Eo(o.syncData)))}function Eo(o){return!!(o&&o.version!==void 0&&typeof o.version=="number"&&o.content!==void 0&&typeof o.content=="string"&&(Object.keys(o).length===2||Object.keys(o).length===3&&o.machineId!==void 0&&typeof o.machineId=="string"))}function ba(o,r){return`${Pl(o)}${r.isDefault?"":` (${r.name})`}`}var mr=class extends T{constructor(e,t,n,i,s,a,l,c,d,u,p,m){super();this.syncResource=e;this.collection=t;this.fileService=n;this.environmentService=i;this.storageService=s;this.userDataSyncStoreService=a;this.userDataSyncLocalStoreService=l;this.userDataSyncEnablementService=c;this.telemetryService=d;this.logService=u;this.configurationService=p;this.syncPreviewPromise=null;this._status="idle";this._onDidChangStatus=this._register(new w);this.onDidChangeStatus=this._onDidChangStatus.event;this._conflicts=[];this._onDidChangeConflicts=this._register(new w);this.onDidChangeConflicts=this._onDidChangeConflicts.event;this.localChangeTriggerThrottler=this._register(new ur(50));this._onDidChangeLocal=this._register(new w);this.onDidChangeLocal=this._onDidChangeLocal.event;this.hasSyncResourceStateVersionChanged=!1;this.syncHeaders={};this.lastSyncUserDataStateKey=`${t?`${t}.`:""}${e.syncResource}.lastSyncUserData`,this.resource=e.syncResource,this.syncResourceLogLabel=ba(e.syncResource,e.profile),this.extUri=m.extUri,this.syncFolder=this.extUri.joinPath(i.userDataSyncHome,...Lh(e.profile.isDefault?void 0:e.profile.id,e.syncResource)),this.syncPreviewFolder=this.extUri.joinPath(this.syncFolder,Mx),this.lastSyncResource=Mh(e.profile.isDefault?void 0:e.profile.id,e.syncResource,i,this.extUri),this.currentMachineIdPromise=Hr(i,n,s)}get status(){return this._status}get conflicts(){return{...this.syncResource,conflicts:this._conflicts}}triggerLocalChange(){this.localChangeTriggerThrottler.trigger(()=>this.doTriggerLocalChange())}async doTriggerLocalChange(){if(this.status==="hasConflicts"){this.logService.info(`${this.syncResourceLogLabel}: In conflicts state and local change detected. Syncing again...`);let e=await this.syncPreviewPromise;this.syncPreviewPromise=null;let t=await this.performSync(e.remoteUserData,e.lastSyncUserData,"merge",this.getUserDataSyncConfiguration());this.setStatus(t)}else{this.logService.trace(`${this.syncResourceLogLabel}: Checking for local changes...`);let e=await this.getLastSyncUserData();(!e||await this.hasRemoteChanged(e))&&this._onDidChangeLocal.fire()}}setStatus(e){this._status!==e&&(this._status=e,this._onDidChangStatus.fire(e))}async sync(e,t=!1,n=this.getUserDataSyncConfiguration(),i={}){try{if(this.syncHeaders={...i},this.status==="hasConflicts")return this.logService.info(`${this.syncResourceLogLabel}: Skipped synchronizing ${this.resource.toLowerCase()} as there are conflicts.`),this.syncPreviewPromise;if(this.status==="syncing")return this.logService.info(`${this.syncResourceLogLabel}: Skipped synchronizing ${this.resource.toLowerCase()} as it is running already.`),this.syncPreviewPromise;this.logService.trace(`${this.syncResourceLogLabel}: Started synchronizing ${this.resource.toLowerCase()}...`),this.setStatus("syncing");let s="idle";try{let a=await this.getLastSyncUserData(),l=await this.getLatestRemoteUserData(e,a);return s=await this.performSync(l,a,t?"preview":"merge",n),s==="hasConflicts"?this.logService.info(`${this.syncResourceLogLabel}: Detected conflicts while synchronizing ${this.resource.toLowerCase()}.`):s==="idle"&&this.logService.trace(`${this.syncResourceLogLabel}: Finished synchronizing ${this.resource.toLowerCase()}.`),this.syncPreviewPromise||null}finally{this.setStatus(s)}}finally{this.syncHeaders={}}}async apply(e,t={}){try{this.syncHeaders={...t};let n=await this.doApply(e);return this.setStatus(n),this.syncPreviewPromise}finally{this.syncHeaders={}}}async replace(e){let t=this.parseSyncData(e);if(!t)return!1;await this.stop();try{this.logService.trace(`${this.syncResourceLogLabel}: Started resetting ${this.resource.toLowerCase()}...`),this.setStatus("syncing");let n=await this.getLastSyncUserData(),i=await this.getLatestRemoteUserData(null,n),s=await this.isRemoteDataFromCurrentMachine(i),a=await this.generateSyncPreview({ref:i.ref,syncData:t},n,s,this.getUserDataSyncConfiguration(),Y.None),l=[];for(let c of a){let d=await this.getAcceptResult(c,c.remoteResource,void 0,Y.None),{remoteChange:u}=await this.getAcceptResult(c,c.previewResource,c.remoteContent,Y.None);l.push([c,{...d,remoteChange:u!==0?u:2}])}await this.applyResult(i,n,l,!1),this.logService.info(`${this.syncResourceLogLabel}: Finished resetting ${this.resource.toLowerCase()}.`)}finally{this.setStatus("idle")}return!0}async isRemoteDataFromCurrentMachine(e){let t=await this.currentMachineIdPromise;return!!e.syncData?.machineId&&e.syncData.machineId===t}async getLatestRemoteUserData(e,t){return e===null?{ref:Ux,syncData:null}:ue(e)?t?.ref===e?t:this.getRemoteUserData(t):this.toRemoteUserData(e)}async performSync(e,t,n,i){if(e.syncData&&e.syncData.version>this.version)throw new xe(S(2708,null,this.resource,this.version,e.syncData.version),"IncompatibleLocalContent",this.resource);try{return await this.doSync(e,t,n,i)}catch(s){if(s instanceof xe)switch(s.code){case"LocalPreconditionFailed":return this.logService.info(`${this.syncResourceLogLabel}: Failed to synchronize ${this.syncResourceLogLabel} as there is a new local version available. Synchronizing again...`),this.performSync(e,t,n,i);case"Conflict":case"PreconditionFailed":return this.logService.info(`${this.syncResourceLogLabel}: Failed to synchronize as there is a new remote version available. Synchronizing again...`),e=await this.getRemoteUserData(null),t=await this.getLastSyncUserData(),this.performSync(e,t,"merge",i)}throw s}}async doSync(e,t,n,i){try{let s=await this.isRemoteDataFromCurrentMachine(e),a=!s&&t===null&&this.getStoredLastSyncUserDataStateContent()!==void 0,l=n==="preview"||n==="merge"&&!a,c=n==="merge"||n==="pull-push";this.syncPreviewPromise||(this.syncPreviewPromise=Je(u=>this.doGenerateSyncResourcePreview(e,t,s,l,i,u)));let d=await this.syncPreviewPromise;if(n==="merge"&&a){this.logService.info(`${this.syncResourceLogLabel}: Accepting remote because it was synced before and the last sync data is not available.`);for(let u of d.resourcePreviews)d=await this.accept(u.remoteResource)||d}else if(n==="pull-push")for(let u of d.resourcePreviews)u.mergeState!=="accepted"&&(e.ref===t?.ref||s?d=await this.accept(u.localResource)??d:d=await this.accept(u.remoteResource)??d);return this.updateConflicts(d.resourcePreviews),d.resourcePreviews.some(({mergeState:u})=>u==="conflict")?"hasConflicts":c?await this.doApply(!1):"syncing"}catch(s){throw this.syncPreviewPromise=null,s}}async accept(e,t){return await this.updateSyncResourcePreview(e,async n=>{let i=await this.getAcceptResult(n,e,t,Y.None);return n.acceptResult=i,n.mergeState="accepted",n.localChange=i.localChange,n.remoteChange=i.remoteChange,n}),this.syncPreviewPromise}async discard(e){return await this.updateSyncResourcePreview(e,async t=>{let n=await this.getMergeResult(t,Y.None);return await this.fileService.writeFile(t.previewResource,U.fromString(n.content||"")),t.acceptResult=void 0,t.mergeState="preview",t.localChange=n.localChange,t.remoteChange=n.remoteChange,t}),this.syncPreviewPromise}async updateSyncResourcePreview(e,t){if(!this.syncPreviewPromise)return;let n=await this.syncPreviewPromise,i=n.resourcePreviews.findIndex(({localResource:s,remoteResource:a,previewResource:l})=>this.extUri.isEqual(s,e)||this.extUri.isEqual(a,e)||this.extUri.isEqual(l,e));i!==-1&&(this.syncPreviewPromise=Je(async s=>{let a=[...n.resourcePreviews];return a[i]=await t(a[i]),{...n,resourcePreviews:a}}),n=await this.syncPreviewPromise,this.updateConflicts(n.resourcePreviews),n.resourcePreviews.some(({mergeState:s})=>s==="conflict")?this.setStatus("hasConflicts"):this.setStatus("syncing"))}async doApply(e){if(!this.syncPreviewPromise)return"idle";let t=await this.syncPreviewPromise;return t.resourcePreviews.some(({mergeState:n})=>n==="conflict")?"hasConflicts":t.resourcePreviews.some(({mergeState:n})=>n!=="accepted")?"syncing":(await this.applyResult(t.remoteUserData,t.lastSyncUserData,t.resourcePreviews.map(n=>[n,n.acceptResult]),e),this.syncPreviewPromise=null,await this.clearPreviewFolder(),"idle")}async clearPreviewFolder(){try{await this.fileService.del(this.syncPreviewFolder,{recursive:!0})}catch{}}updateConflicts(e){let t=e.filter(({mergeState:n})=>n==="conflict");Pt(this._conflicts,t,(n,i)=>this.extUri.isEqual(n.previewResource,i.previewResource))||(this._conflicts=t,this._onDidChangeConflicts.fire(this.conflicts))}async hasPreviouslySynced(){let e=await this.getLastSyncUserData();return!!e&&e.syncData!==null}async resolvePreviewContent(e){let t=this.syncPreviewPromise?await this.syncPreviewPromise:null;if(t)for(let n of t.resourcePreviews){if(this.extUri.isEqual(n.acceptedResource,e))return n.acceptResult?n.acceptResult.content:null;if(this.extUri.isEqual(n.remoteResource,e))return n.remoteContent;if(this.extUri.isEqual(n.localResource,e))return n.localContent;if(this.extUri.isEqual(n.baseResource,e))return n.baseContent}return null}async resetLocal(){this.storageService.remove(this.lastSyncUserDataStateKey,-1);try{await this.fileService.del(this.lastSyncResource)}catch(e){_e(e)!==1&&this.logService.error(e)}}async doGenerateSyncResourcePreview(e,t,n,i,s,a){let l=await this.generateSyncPreview(e,t,n,s,a),c=[];for(let d of l){let u=d.previewResource.with({scheme:M,authority:"accepted"});if(d.localChange===0&&d.remoteChange===0)c.push({...d,acceptedResource:u,acceptResult:{content:null,localChange:0,remoteChange:0},mergeState:"accepted"});else{let p=i?await this.getMergeResult(d,a):void 0;if(a.isCancellationRequested)break;await this.fileService.writeFile(d.previewResource,U.fromString(p?.content||""));let m=p&&!p.hasConflicts?await this.getAcceptResult(d,d.previewResource,void 0,a):void 0;c.push({...d,acceptResult:m,mergeState:p?.hasConflicts?"conflict":m?"accepted":"preview",localChange:m?m.localChange:p?p.localChange:d.localChange,remoteChange:m?m.remoteChange:p?p.remoteChange:d.remoteChange})}}return{syncResource:this.resource,profile:this.syncResource.profile,remoteUserData:e,lastSyncUserData:t,resourcePreviews:c,isLastSyncFromCurrentMachine:n}}async getLastSyncUserData(){let e=this.getStoredLastSyncUserDataStateContent();if(!e)return this.logService.info(`${this.syncResourceLogLabel}: Last sync data state does not exist.`),null;let t=JSON.parse(e),n=this.userDataSyncEnablementService.getResourceSyncStateVersion(this.resource);if(this.hasSyncResourceStateVersionChanged=!!t.version&&!!n&&t.version!==n,this.hasSyncResourceStateVersionChanged)return this.logService.info(`${this.syncResourceLogLabel}: Reset last sync state because last sync state version ${t.version} is not compatible with current sync state version ${n}.`),await this.resetLocal(),null;let i,s=1;for(;i===void 0&&s++<6;)try{let a=await this.readLastSyncStoredRemoteUserData();a&&(a.ref===t.ref?i=a.syncData:this.logService.info(`${this.syncResourceLogLabel}: Last sync data stored locally is not same as the last sync state.`));break}catch(a){if(a instanceof et&&a.fileOperationResult===1){this.logService.info(`${this.syncResourceLogLabel}: Last sync resource does not exist locally.`);break}else{if(a instanceof xe)throw a;this.logService.error(a,s)}}if(i===void 0)try{let a=await this.userDataSyncStoreService.resolveResourceContent(this.resource,t.ref,this.collection,this.syncHeaders);i=a===null?null:this.parseSyncData(a),await this.writeLastSyncStoredRemoteUserData({ref:t.ref,syncData:i})}catch(a){if(a instanceof xe&&a.code==="NotFound")this.logService.info(`${this.syncResourceLogLabel}: Last sync resource does not exist remotely.`);else throw a}return i===void 0?null:{...t,syncData:i}}async updateLastSyncUserData(e,t={}){if(t.ref||t.version)throw new Error("Cannot have core properties as additional");let n=this.userDataSyncEnablementService.getResourceSyncStateVersion(this.resource),i={ref:e.ref,version:n,...t};this.storageService.store(this.lastSyncUserDataStateKey,JSON.stringify(i),-1,1),await this.writeLastSyncStoredRemoteUserData(e)}getStoredLastSyncUserDataStateContent(){return this.storageService.get(this.lastSyncUserDataStateKey,-1)}async readLastSyncStoredRemoteUserData(){let e=(await this.fileService.readFile(this.lastSyncResource)).value.toString();try{let t=e?JSON.parse(e):void 0;if(yR(t))return t}catch(t){this.logService.error(t)}}async writeLastSyncStoredRemoteUserData(e){await this.fileService.writeFile(this.lastSyncResource,U.fromString(JSON.stringify(e)))}async getRemoteUserData(e){let t=await this.getUserData(e);return this.toRemoteUserData(t)}toRemoteUserData({ref:e,content:t}){let n=null;return t!==null&&(n=this.parseSyncData(t)),{ref:e,syncData:n}}parseSyncData(e){try{let t=JSON.parse(e);if(Eo(t))return t}catch(t){this.logService.error(t)}throw new xe(S(2709,null),"IncompatibleRemoteContent",this.resource)}async getUserData(e){let t=e?{ref:e.ref,content:e.syncData?JSON.stringify(e.syncData):null}:null;return this.userDataSyncStoreService.readResource(this.resource,t,this.collection,this.syncHeaders)}async updateRemoteUserData(e,t){let n=await this.currentMachineIdPromise,i={version:this.version,machineId:n,content:e};try{return t=await this.userDataSyncStoreService.writeResource(this.resource,JSON.stringify(i),t,this.collection,this.syncHeaders),{ref:t,syncData:i}}catch(s){throw s instanceof xe&&s.code==="TooLarge"&&(s=new xe(s.message,s.code,this.resource)),s}}async backupLocal(e){let t={version:this.version,content:e};return this.userDataSyncLocalStoreService.writeResource(this.resource,JSON.stringify(t),new Date,this.syncResource.profile.isDefault?void 0:this.syncResource.profile.id)}async stop(){this.status!=="idle"&&(this.logService.trace(`${this.syncResourceLogLabel}: Stopping synchronizing ${this.resource.toLowerCase()}.`),this.syncPreviewPromise&&(this.syncPreviewPromise.cancel(),this.syncPreviewPromise=null),this.updateConflicts([]),await this.clearPreviewFolder(),this.setStatus("idle"),this.logService.info(`${this.syncResourceLogLabel}: Stopped synchronizing ${this.resource.toLowerCase()}.`))}getUserDataSyncConfiguration(){return this.configurationService.getValue(ho)}};mr=b([g(2,W),g(3,X),g(4,K),g(5,Ce),g(6,Qe),g(7,Oe),g(8,de),g(9,me),g(10,Q),g(11,te)],mr);var xo=class extends mr{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h){super(t,n,i,s,a,l,c,d,u,p,m,h);this.file=e;this._register(this.fileService.watch(this.extUri.dirname(e))),this._register(this.fileService.onDidFilesChange(v=>this.onFileChanges(v)))}async getLocalFileContent(){try{return await this.fileService.readFile(this.file)}catch{return null}}async updateLocalFileContent(e,t,n){try{t?await this.fileService.writeFile(this.file,U.fromString(e),n?void 0:t):await this.fileService.createFile(this.file,U.fromString(e),{overwrite:n})}catch(i){throw i instanceof et&&i.fileOperationResult===1||i instanceof et&&i.fileOperationResult===3?new xe(i.message,"LocalPreconditionFailed"):i}}async deleteLocalFile(){try{await this.fileService.del(this.file)}catch(e){if(!(e instanceof et&&e.fileOperationResult===1))throw e}}onFileChanges(e){e.contains(this.file)&&this.triggerLocalChange()}};xo=b([g(3,W),g(4,X),g(5,K),g(6,Ce),g(7,Qe),g(8,Oe),g(9,de),g(10,me),g(11,Q),g(12,te)],xo);var Ti=class extends xo{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h,v){super(e,t,n,i,s,a,l,c,d,u,p,h,v);this.userDataSyncUtilService=m;this._formattingOptions=void 0}hasErrors(e,t){let n=[],i=je(e,n,{allowEmptyContent:!0,allowTrailingComma:!0});return n.length>0||!st(i)&&t!==Array.isArray(i)}getFormattingOptions(){return this._formattingOptions||(this._formattingOptions=this.userDataSyncUtilService.resolveFormattingOptions(this.file)),this._formattingOptions}};Ti=b([g(3,W),g(4,X),g(5,K),g(6,Ce),g(7,Qe),g(8,Oe),g(9,de),g(10,me),g(11,Ri),g(12,Q),g(13,te)],Ti);var ir=class{constructor(r,e,t,n,i,s,a){this.resource=r;this.userDataProfilesService=e;this.environmentService=t;this.logService=n;this.fileService=i;this.storageService=s;this.extUri=a.extUri,this.lastSyncResource=Mh(void 0,this.resource,t,this.extUri)}async initialize({ref:r,content:e}){if(!e){this.logService.info("Remote content does not exist.",this.resource);return}let t=this.parseSyncData(e);if(t)try{await this.doInitialize({ref:r,syncData:t})}catch(n){this.logService.error(n)}}parseSyncData(r){try{let e=JSON.parse(r);if(Eo(e))return e}catch(e){this.logService.error(e)}this.logService.info("Cannot parse sync data as it is not compatible with the current version.",this.resource)}async updateLastSyncUserData(r,e={}){if(e.ref||e.version)throw new Error("Cannot have core properties as additional");let t={ref:r.ref,version:void 0,...e};this.storageService.store(`${this.resource}.lastSyncUserData`,JSON.stringify(t),-1,1),await this.fileService.writeFile(this.lastSyncResource,U.fromString(JSON.stringify(r)))}};ir=b([g(1,fe),g(2,X),g(3,V),g(4,W),g(5,K),g(6,te)],ir);function Cc(o,r,e,t,n,i){let s=[],a=[],l=[];if(!r){let C=o.filter(({identifier:A})=>n.every(ae=>ae.toLowerCase()!==A.id.toLowerCase()));return{local:{added:s,removed:a,updated:l},remote:C.length>0?{added:C,updated:[],removed:[],all:C}:null}}o=o.map(qh),r=r.map(qh),e=e?e.map(qh):null;let c=new Map,d=C=>{C.uuid&&c.set(C.id.toLowerCase(),C.uuid)};o.forEach(({identifier:C})=>d(C)),r.forEach(({identifier:C})=>d(C)),e?.forEach(({identifier:C})=>d(C)),t?.forEach(({identifier:C})=>d(C)),i?.forEach(C=>d(C));let u=C=>{let A=C.identifier.uuid||c.get(C.identifier.id.toLowerCase());return A?`uuid:${A}`:`id:${C.identifier.id.toLowerCase()}`},p=(C,A)=>(C.set(u(A),A),C),m=o.reduce(p,new Map),h=r.reduce(p,new Map),v=r.reduce((C,A)=>p(C,Ct(A)),new Map),y=e?e.reduce(p,new Map):null,x=t.reduce(p,new Map),E=n.reduce((C,A)=>{let ae=c.get(A.toLowerCase());return C.add(ae?`uuid:${ae}`:`id:${A.toLowerCase()}`)},new Set),R=i?i.reduce((C,{id:A,uuid:ae})=>(ae=ae??c.get(A.toLowerCase()),C.add(ae?`uuid:${ae}`:`id:${A.toLowerCase()}`)),new Set):null,F=zp(m,h,E,!1);if(F.added.size>0||F.removed.size>0||F.updated.size>0){let C=zp(y,m,E,!1),A=zp(y,h,E,!0),ae=(J,ge,Xe,Ze)=>{let N,O,q;return ge.installed?(N=Ze.pinned,q=Ze.preRelease,N&&(O=Ze.version)):(N=Xe.pinned,q=Xe.preRelease,N&&(O=Xe.version)),N===void 0&&(N=ge.pinned,N&&(O=ge.version)),q===void 0&&(q=ge.preRelease),{...Ze,installed:ge.installed||Xe.installed,pinned:N,preRelease:q,version:O??(Xe.version&&(!ge.installed||Hn(Xe.version,ge.version))?Xe.version:ge.version),state:SR(ge,Xe,y?.get(J))}};for(let J of A.removed.values()){let ge=m.get(J);if(!ge)continue;let Xe=Tr(y?.get(J)),Ze=R&&!R.has(J)&&Xe.installed;ge.installed&&Ze?a.push(ge.identifier):v.set(J,ge)}for(let J of A.added.values()){let ge=Tr(h.get(J)),Xe=m.get(J);if(Xe){if(F.updated.has(J)){let Ze=ae(J,Xe,ge,ge);Nx(Xe,ge,!1,!1)||l.push(Tc(Ze,J)),v.set(J,Ze)}}else ge.installed&&s.push(Tc(ge,J))}for(let J of A.updated.values()){let ge=Tr(h.get(J)),Xe=Tr(y?.get(J)),Ze=m.get(J);if(Ze)if(R&&!R.has(J)&&Xe.installed&&Ze.installed&&!ge.installed)a.push(Ze.identifier);else{let O=ae(J,Ze,ge,ge);l.push(Tc(O,J)),v.set(J,O)}else ge.installed&&s.push(Tc(ge,J))}for(let J of C.added.values())A.added.has(J)||v.set(J,Tr(m.get(J)));for(let J of C.updated.values()){if(A.removed.has(J)||A.updated.has(J))continue;let ge=Tr(m.get(J)),Xe=Tr(h.get(J));v.set(J,ae(J,ge,Xe,ge))}for(let J of C.removed.values())A.updated.has(J)||A.removed.has(J)||x.has(J)||Tr(h.get(J)).installed&&R&&(R.has(J)||!Tr(y?.get(J)).installed||v.delete(J))}let H=[],qe=zp(h,v,new Set,!0),B=qe.added.size>0||qe.updated.size>0||qe.removed.size>0;return B&&v.forEach((C,A)=>H.push(Tc(C,A))),{local:{added:s,removed:a,updated:l},remote:B?{added:[...qe.added].map(C=>v.get(C)),updated:[...qe.updated].map(C=>v.get(C)),removed:[...qe.removed].map(C=>h.get(C)),all:H}:null}}function zp(o,r,e,t){let n=o?[...o.keys()].filter(c=>!e.has(c)):[],i=[...r.keys()].filter(c=>!e.has(c)),s=i.filter(c=>!n.includes(c)).reduce((c,d)=>(c.add(d),c),new Set),a=n.filter(c=>!i.includes(c)).reduce((c,d)=>(c.add(d),c),new Set),l=new Set;for(let c of n){if(a.has(c))continue;let d=o.get(c),u=r.get(c);(!u||!Nx(d,u,t,!0))&&l.add(c)}return{added:s,removed:a,updated:l}}function Nx(o,r,e,t){return!(o.disabled!==r.disabled||!!o.isApplicationScoped!=!!r.isApplicationScoped||t&&o.installed!==r.installed||o.installed&&r.installed&&(o.preRelease!==r.preRelease||o.pinned!==r.pinned||r.pinned&&o.version!==r.version)||!IR(o.state,r.state)||e&&o.version!==r.version)}function SR(o,r,e){let t=o.state,n=r.state,i=e?.state;if(!r.version||t&&Hn(o.version,r.version))return t;if(n&&Hn(r.version,o.version)||!t)return n;if(!n)return t;let s=Ct(t),a=i?zh(i,n):{added:Object.keys(n).reduce((c,d)=>(c.add(d),c),new Set),removed:new Set,updated:new Set},l=i?zh(i,t):{added:Object.keys(t).reduce((c,d)=>(c.add(d),c),new Set),removed:new Set,updated:new Set};for(let c of[...a.added.values(),...a.updated.values()])s[c]=n[c];for(let c of a.removed.values())l.updated.has(c)||delete s[c];return s}function zh(o,r){let e=Object.keys(o),t=Object.keys(r),n=t.filter(a=>!e.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),i=e.filter(a=>!t.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),s=new Set;for(let a of e){if(i.has(a))continue;let l=o[a],c=r[a];it(l,c)||s.add(a)}return{added:n,removed:i,updated:s}}function IR(o={},r={}){let{added:e,removed:t,updated:n}=zh(o,r);return e.size===0&&t.size===0&&n.size===0}function qh(o){return{...o,disabled:!!o.disabled,installed:!!o.installed}}function Tc(o,r){let e={...o,identifier:{id:o.identifier.id,uuid:r.startsWith("uuid:")?r.substring(5):void 0},preRelease:!!o.preRelease,pinned:!!o.pinned};return o.disabled||delete e.disabled,o.installed||delete e.installed,o.state||delete e.state,o.isApplicationScoped||delete e.isApplicationScoped,e}var Di=L("IUserDataProfileStorageService"),Dc=class extends T{constructor(e,t){super();this.storageService=t;e&&(this.storageServicesMap=this._register(new Gr))}async readStorageData(e){return this.withProfileScopedStorageService(e,async t=>this.getItems(t))}async updateStorageData(e,t,n){return this.withProfileScopedStorageService(e,async i=>this.writeItems(i,t,n))}async withProfileScopedStorageService(e,t){if(this.storageService.hasScope(e))return t(this.storageService);let n=this.storageServicesMap?.get(e.id);if(!n){n=new Kh(this.createStorageDatabase(e)),this.storageServicesMap?.set(e.id,n);try{await n.initialize()}catch(i){throw this.storageServicesMap?.has(e.id)?this.storageServicesMap.deleteAndDispose(e.id):n.dispose(),i}}try{let i=await t(n);return await n.flush(),i}finally{this.storageServicesMap?.has(e.id)||n.dispose()}}getItems(e){let t=new Map,n=i=>{for(let s of e.keys(0,i))t.set(s,{value:e.get(s,0),target:i})};return n(0),n(1),t}writeItems(e,t,n){e.storeAll(Array.from(t.entries()).map(([i,s])=>({key:i,value:s,scope:0,target:n})),!0)}};Dc=b([g(1,K)],Dc);var Kp=class extends Dc{constructor(e,t,n,i,s){super(e,i);this.remoteService=t;let a=t.getChannel("profileStorageListener"),l=this._register(new kt);this._onDidChange=this._register(new w({onWillAddFirstListener:()=>{l.value=a.listen("onDidChange")(c=>{s.trace("profile storage changes",c),this._onDidChange.fire({targetChanges:c.targetChanges.map(d=>nr(d,n.profilesHome.scheme)),valueChanges:c.valueChanges.map(d=>({...d,profile:nr(d.profile,n.profilesHome.scheme)}))})})},onDidRemoveLastListener:()=>l.value=void 0})),this.onDidChange=this._onDidChange.event}async createStorageDatabase(e){let t=this.remoteService.getChannel("storage");return Ws(e)?new ws(t):new Ps(t,e)}},Kh=class extends Vs{constructor(e){super({flushInterval:100});this.profileStorageDatabase=e}async doInitialize(){let e=await this.profileStorageDatabase,t=new jn(e);return this._register(t.onDidChangeStorage(n=>{this.emitDidChangeValue(0,n)})),this._register(oe(()=>{t.close(),t.dispose(),qo(e)&&e.dispose()})),this.profileStorage=t,this.profileStorage.init()}getStorage(e){return e===0?this.profileStorage:void 0}getLogDetails(){}async switchToProfile(){}async switchToWorkspace(){}hasScope(){return!1}};async function Hp(o,r){let e=JSON.parse(o.content);if(o.version===1||o.version===2){let t=(await r.getInstalled(0)).filter(n=>n.isBuiltin);for(let n of e)o.version===1&&(n.enabled===!1&&(n.disabled=!0),delete n.enabled),o.version===2&&t.every(i=>!j(i.identifier,n.identifier))&&(n.installed=!0)}return e}function Vx(o){return JSON.parse(o.content)}function Jp(o,r){return o.sort((e,t)=>!e.identifier.uuid&&t.identifier.uuid?-1:e.identifier.uuid&&!t.identifier.uuid?1:zi(e.identifier.id,t.identifier.id)),r?zn(o,{}):JSON.stringify(o)}var xa=class extends mr{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h,v,y,x,E){super({syncResource:"extensions",profile:e},t,i,n,s,a,l,m,h,u,p,y);this.extensionManagementService=c;this.ignoredExtensionsManagementService=d;this.instantiationService=E;this.version=6;this.previewResource=this.extUri.joinPath(this.syncPreviewFolder,"extensions.json");this.baseResource=this.previewResource.with({scheme:M,authority:"base"});this.localResource=this.previewResource.with({scheme:M,authority:"local"});this.remoteResource=this.previewResource.with({scheme:M,authority:"remote"});this.acceptedResource=this.previewResource.with({scheme:M,authority:"accepted"});this.localExtensionsProvider=this.instantiationService.createInstance(wo),this._register(k.any(k.filter(this.extensionManagementService.onDidInstallExtensions,(R=>R.some(({local:F})=>!!F))),k.filter(this.extensionManagementService.onDidUninstallExtension,(R=>!R.error)),k.filter(x.onDidChange,R=>R.valueChanges.some(({profile:F,changes:H})=>this.syncResource.profile.id===F.id&&H.some(qe=>qe.key===nc))),v.onDidChangeExtensionStorageToSync)(()=>this.triggerLocalChange()))}async generateSyncPreview(e,t){let n=e.syncData?await Hp(e.syncData,this.extensionManagementService):null,i=t?.skippedExtensions??[],s=t?.builtinExtensions??null,a=t?.syncData?await Hp(t.syncData,this.extensionManagementService):null,{localExtensions:l,ignoredExtensions:c}=await this.localExtensionsProvider.getLocalExtensions(this.syncResource.profile);n?this.logService.trace(`${this.syncResourceLogLabel}: Merging remote extensions with local extensions...`):this.logService.trace(`${this.syncResourceLogLabel}: Remote extensions does not exist. Synchronizing extensions for the first time.`);let{local:d,remote:u}=Cc(l,n,a,i,c,s),p={local:d,remote:u,content:this.getPreviewContent(l,d.added,d.updated,d.removed),localChange:d.added.length>0||d.removed.length>0||d.updated.length>0?2:0,remoteChange:u!==null?2:0},m=this.stringify(l,!1);return[{skippedExtensions:i,builtinExtensions:s,baseResource:this.baseResource,baseContent:a?this.stringify(a,!1):m,localResource:this.localResource,localContent:m,localExtensions:l,remoteResource:this.remoteResource,remoteExtensions:n,remoteContent:n?this.stringify(n,!1):null,previewResource:this.previewResource,previewResult:p,localChange:p.localChange,remoteChange:p.remoteChange,acceptedResource:this.acceptedResource}]}async hasRemoteChanged(e){let t=e.syncData?await Hp(e.syncData,this.extensionManagementService):null,{localExtensions:n,ignoredExtensions:i}=await this.localExtensionsProvider.getLocalExtensions(this.syncResource.profile),{remote:s}=Cc(n,t,t,e.skippedExtensions||[],i,e.builtinExtensions||[]);return s!==null}getPreviewContent(e,t,n,i){let s=[...t,...n],a=new Set,l=c=>{a.add(c.id.toLowerCase()),c.uuid&&a.add(c.uuid)};s.forEach(({identifier:c})=>l(c)),i.forEach(l);for(let c of e)a.has(c.identifier.id.toLowerCase())||c.identifier.uuid&&a.has(c.identifier.uuid)||s.push(c);return this.stringify(s,!1)}async getMergeResult(e,t){return{...e.previewResult,hasConflicts:!1}}async getAcceptResult(e,t,n,i){if(this.extUri.isEqual(t,this.localResource))return this.acceptLocal(e);if(this.extUri.isEqual(t,this.remoteResource))return this.acceptRemote(e);if(this.extUri.isEqual(t,this.previewResource))return e.previewResult;throw new Error(`Invalid Resource: ${t.toString()}`)}async acceptLocal(e){let t=await this.extensionManagementService.getInstalled(void 0,this.syncResource.profile.extensionsResource),n=this.ignoredExtensionsManagementService.getIgnoredExtensions(t),i=e.remoteContent?JSON.parse(e.remoteContent):null,s=Cc(e.localExtensions,i,i,e.skippedExtensions,n,e.builtinExtensions),{local:a,remote:l}=s;return{content:e.localContent,local:a,remote:l,localChange:a.added.length>0||a.removed.length>0||a.updated.length>0?2:0,remoteChange:l!==null?2:0}}async acceptRemote(e){let t=await this.extensionManagementService.getInstalled(void 0,this.syncResource.profile.extensionsResource),n=this.ignoredExtensionsManagementService.getIgnoredExtensions(t),i=e.remoteContent?JSON.parse(e.remoteContent):null;if(i!==null){let s=Cc(e.localExtensions,i,e.localExtensions,[],n,e.builtinExtensions),{local:a,remote:l}=s;return{content:e.remoteContent,local:a,remote:l,localChange:a.added.length>0||a.removed.length>0||a.updated.length>0?2:0,remoteChange:l!==null?2:0}}else return{content:e.remoteContent,local:{added:[],removed:[],updated:[]},remote:null,localChange:0,remoteChange:0}}async applyResult(e,t,n,i){let{skippedExtensions:s,builtinExtensions:a,localExtensions:l}=n[0][0],{local:c,remote:d,localChange:u,remoteChange:p}=n[0][1];if(u===0&&p===0&&this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing extensions.`),u!==0&&(await this.backupLocal(JSON.stringify(l)),s=await this.localExtensionsProvider.updateLocalExtensions(c.added,c.removed,c.updated,s,this.syncResource.profile)),d){this.logService.trace(`${this.syncResourceLogLabel}: Updating remote extensions...`);let m=JSON.stringify(d.all);e=await this.updateRemoteUserData(m,i?null:e.ref),this.logService.info(`${this.syncResourceLogLabel}: Updated remote extensions.${d.added.length?` Added: ${JSON.stringify(d.added.map(h=>h.identifier.id))}.`:""}${d.updated.length?` Updated: ${JSON.stringify(d.updated.map(h=>h.identifier.id))}.`:""}${d.removed.length?` Removed: ${JSON.stringify(d.removed.map(h=>h.identifier.id))}.`:""}`)}t?.ref!==e.ref&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized extensions...`),a=this.computeBuiltinExtensions(l,a),await this.updateLastSyncUserData(e,{skippedExtensions:s,builtinExtensions:a}),this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized extensions.${s.length?` Skipped: ${JSON.stringify(s.map(m=>m.identifier.id))}.`:""}`))}computeBuiltinExtensions(e,t){let n=new Set,i=[];for(let s of e)n.add(s.identifier.id.toLowerCase()),s.installed||i.push(s.identifier);if(t)for(let s of t)n.has(s.id.toLowerCase())||i.push(s);return i}async resolveContent(e){if(this.extUri.isEqual(this.remoteResource,e)||this.extUri.isEqual(this.baseResource,e)||this.extUri.isEqual(this.localResource,e)||this.extUri.isEqual(this.acceptedResource,e)){let t=await this.resolvePreviewContent(e);return t&&this.stringify(JSON.parse(t),!0)}return null}stringify(e,t){return Jp(e,t)}async hasLocalData(){try{let{localExtensions:e}=await this.localExtensionsProvider.getLocalExtensions(this.syncResource.profile);if(e.some(t=>t.installed||t.disabled))return!0}catch{}return!1}};xa=b([g(2,X),g(3,W),g(4,K),g(5,Ce),g(6,Qe),g(7,rr),g(8,fa),g(9,me),g(10,Q),g(11,Oe),g(12,de),g(13,ua),g(14,te),g(15,Di),g(16,bt)],xa);var wo=class{constructor(r,e,t,n,i,s){this.extensionManagementService=r;this.userDataProfileStorageService=e;this.extensionGalleryService=t;this.ignoredExtensionsManagementService=n;this.instantiationService=i;this.logService=s}async getLocalExtensions(r){let e=await this.extensionManagementService.getInstalled(void 0,r.extensionsResource),t=this.ignoredExtensionsManagementService.getIgnoredExtensions(e);return{localExtensions:await this.withProfileScopedServices(r,async(i,s)=>{let a=i.getDisabledExtensions();return e.map(l=>{let{identifier:c,isBuiltin:d,manifest:u,preRelease:p,pinned:m,isApplicationScoped:h}=l,v={identifier:c,preRelease:p,version:u.version,pinned:!!m};h&&!Ql(u)&&(v.isApplicationScoped=h),a.some(y=>j(y,c))&&(v.disabled=!0),d||(v.installed=!0);try{let y=s.getKeysForSync({id:c.id,version:u.version});if(y){let x=s.getExtensionState(l,!0)||{};v.state=Object.keys(x).reduce((E,R)=>(y.includes(R)&&(E[R]=x[R]),E),{})}}catch(y){this.logService.info(`${ba("extensions",r)}: Error while parsing extension state`,ee(y))}return v})}),ignoredExtensions:t}}async updateLocalExtensions(r,e,t,n,i){let s=ba("extensions",i),a=[],l=new Map,c=[],d=[],u=await this.extensionManagementService.getInstalled(void 0,i.extensionsResource);if((r.length||t.length)&&await this.withProfileScopedServices(i,async(h,v)=>{await Ke.settled([...r,...t].map(async y=>{let x=u.find(F=>j(F.identifier,y.identifier));if(x&&x.isBuiltin){y.state&&x.manifest.version===y.version&&this.updateExtensionState(y.state,x,x.manifest.version,v),h.getDisabledExtensions().some(H=>j(H,y.identifier))!==!!y.disabled&&(y.disabled?(this.logService.trace(`${s}: Disabling extension...`,y.identifier.id),await h.disableExtension(y.identifier),this.logService.info(`${s}: Disabled extension`,y.identifier.id)):(this.logService.trace(`${s}: Enabling extension...`,y.identifier.id),await h.enableExtension(y.identifier),this.logService.info(`${s}: Enabled extension`,y.identifier.id))),c.push(y.identifier);return}let E=y.pinned?y.version:void 0,R=(await this.extensionGalleryService.getExtensions([{...y.identifier,version:E,preRelease:E?void 0:y.preRelease}],Y.None))[0];if(y.state&&(x?x.manifest.version===y.version:R)&&this.updateExtensionState(y.state,x||R,x?.manifest.version,v),R)try{h.getDisabledExtensions().some(H=>j(H,y.identifier))!==!!y.disabled&&(y.disabled?(this.logService.trace(`${s}: Disabling extension...`,y.identifier.id,R.version),await h.disableExtension(R.identifier),this.logService.info(`${s}: Disabled extension`,y.identifier.id,R.version)):(this.logService.trace(`${s}: Enabling extension...`,y.identifier.id,R.version),await h.enableExtension(R.identifier),this.logService.info(`${s}: Enabled extension`,y.identifier.id,R.version))),(!x||x.preRelease!==y.preRelease||x.pinned!==y.pinned||E&&x.manifest.version!==E)&&(await this.extensionManagementService.canInstall(R)===!0?(a.push({extension:R,options:{isMachineScoped:!1,donotIncludePackAndDependencies:!0,installGivenVersion:y.pinned&&!!y.version,pinned:y.pinned,installPreReleaseVersion:y.preRelease,preRelease:y.preRelease,profileLocation:i.extensionsResource,isApplicationScoped:y.isApplicationScoped,context:{[OI]:!0,[tc]:"settingsSync",[ec]:!0}}}),l.set(R.identifier.id.toLowerCase(),y)):(this.logService.info(`${s}: Skipped synchronizing extension because it cannot be installed.`,R.displayName||R.identifier.id),d.push(y)))}catch(F){d.push(y),this.logService.error(F),this.logService.info(`${s}: Skipped synchronizing extension`,R.displayName||R.identifier.id)}else d.push(y),this.logService.info(`${s}: Skipped synchronizing extension because the extension is not found.`,y.identifier.id)}))}),e.length){let h=u.filter(({identifier:v,isBuiltin:y})=>!y&&e.some(x=>j(v,x)));await Ke.settled(h.map(async v=>{this.logService.trace(`${s}: Uninstalling local extension...`,v.identifier.id),await this.extensionManagementService.uninstall(v,{donotIncludePack:!0,donotCheckDependents:!0,profileLocation:i.extensionsResource}),this.logService.info(`${s}: Uninstalled local extension.`,v.identifier.id),c.push(v.identifier)}))}let p=await this.extensionManagementService.installGalleryExtensions(a);for(let{identifier:h,local:v,error:y,source:x}of p){let E=x;if(v)this.logService.info(`${s}: Installed extension.`,h.id,E.version),c.push(h);else{let R=l.get(h.id.toLowerCase());R&&(d.push(R),this.logService.info(`${s}: Skipped synchronizing extension`,E.displayName||E.identifier.id)),y instanceof Ge&&["Incompatible","IncompatibleApi","IncompatibleTargetPlatform"].includes(y.code)?this.logService.info(`${s}: Skipped synchronizing extension because the compatible extension is not found.`,E.displayName||E.identifier.id):y&&this.logService.error(y)}}let m=[];for(let h of n)c.some(v=>j(v,h.identifier))||m.push(h);for(let h of d)m.some(v=>j(v.identifier,h.identifier))||m.push(h);return m}updateExtensionState(r,e,t,n){let i=n.getExtensionState(e,!0)||{},s=t?n.getKeysForSync({id:e.identifier.id,version:t}):void 0;s?s.forEach(a=>{i[a]=r[a]}):Object.keys(r).forEach(a=>i[a]=r[a]),n.setExtensionState(e,i,!0)}async withProfileScopedServices(r,e){return this.userDataProfileStorageService.withProfileScopedStorageService(r,async t=>{let n=new se,i=n.add(this.instantiationService.createChild(new Ei([K,t]))),s=n.add(i.createInstance(Ii)),a=n.add(i.createInstance(Ot));try{return await e(s,a)}finally{n.dispose()}})}};wo=b([g(0,rr),g(1,Di),g(2,At),g(3,fa),g(4,bt),g(5,me)],wo);var jp=class extends ir{constructor(e,t,n,i,s,a,l,c){super("extensions",i,s,a,n,l,c);this.extensionManagementService=e;this.ignoredExtensionsManagementService=t}async parseExtensions(e){return e.syncData?await Hp(e.syncData,this.extensionManagementService):null}generatePreview(e,t){let n=[],i=[],s=[];for(let a of e){if(this.ignoredExtensionsManagementService.hasToNeverSyncExtension(a.identifier.id))continue;let l=t.find(c=>j(c.identifier,a.identifier));l?(n.push(l),a.disabled&&s.push(a.identifier)):a.installed&&(i.push({...a.identifier,preRelease:!!a.preRelease}),a.disabled&&s.push(a.identifier))}return{installedExtensions:n,newExtensions:i,disabledExtensions:s,remoteExtensions:e}}};jp=b([g(0,rr),g(1,fa),g(2,W),g(3,fe),g(4,X),g(5,V),g(6,K),g(7,te)],jp);function Xt(o,r,e,t){let n=Ds(o,r,e,t)[0];return n&&(o=o.substring(0,n.offset)+n.content+o.substring(n.offset+n.length)),o}function _c(o,r,e,t,n){if(!r)return{remote:{added:Object.keys(o),removed:[],updated:[],all:Object.keys(o).length>0?o:null},local:{added:{},removed:[],updated:{}}};let i=Qp(o,r);if(i.added.size===0&&i.removed.size===0&&i.updated.size===0)return{remote:{added:[],removed:[],updated:[],all:null},local:{added:{},removed:[],updated:{}}};let s=e?Qp(e,r):{added:Object.keys(r).reduce((p,m)=>(p.add(m),p),new Set),removed:new Set,updated:new Set},a=e?Qp(e,o):{added:Object.keys(o).reduce((p,m)=>(p.add(m),p),new Set),removed:new Set,updated:new Set},l={added:{},removed:[],updated:{}},c=Ct(r),d=!e;for(let p of a.added.values())p!==pn&&d&&s.added.has(p)||(c[p]=o[p]);for(let p of a.updated.values())c[p]=o[p];for(let p of a.removed.values())t.unregistered.includes(p)||delete c[p];for(let p of s.added.values()){let m=r[p];if(t.machine.includes(p)){n.info(`GlobalState: Skipped adding ${p} in local storage because it is declared as machine scoped.`);continue}if(e&&a.added.has(p))continue;let h=o[p];h&&h.value===m.value||p===pn&&d&&a.added.has(p)||(h?l.updated[p]=m:l.added[p]=m)}for(let p of s.updated.values()){let m=r[p];if(t.machine.includes(p)){n.info(`GlobalState: Skipped updating ${p} in local storage because it is declared as machine scoped.`);continue}if(a.updated.has(p)||a.removed.has(p))continue;let h=o[p];h&&h.value===m.value||(l.updated[p]=m)}for(let p of s.removed.values()){if(t.machine.includes(p)){n.trace(`GlobalState: Skipped removing ${p} in local storage because it is declared as machine scoped.`);continue}a.updated.has(p)||a.removed.has(p)||l.removed.push(p)}let u=Qp(r,c);return{local:l,remote:{added:[...u.added],updated:[...u.updated],removed:[...u.removed],all:u.added.size===0&&u.removed.size===0&&u.updated.size===0?null:c}}}function Qp(o,r){let e=Object.keys(o),t=Object.keys(r),n=t.filter(a=>!e.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),i=e.filter(a=>!t.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),s=new Set;for(let a of e){if(i.has(a))continue;let l=o[a],c=r[a];it(l,c)||s.add(a)}return{added:n,removed:i,updated:s}}var Ro="globalState.argv.",bR=["locale"];function _i(o,r){let e=o.storage?Object.keys(o.storage).sort():[],t={};return e.forEach(n=>t[n]=o.storage[n]),o.storage=t,r?zn(o,{}):JSON.stringify(o)}var jh=1,Ea=class extends mr{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h,v){super({syncResource:"globalState",profile:e},t,i,c,m,s,a,d,u,l,p,h);this.userDataProfileStorageService=n;this.version=jh;this.previewResource=this.extUri.joinPath(this.syncPreviewFolder,"globalState.json");this.baseResource=this.previewResource.with({scheme:M,authority:"base"});this.localResource=this.previewResource.with({scheme:M,authority:"local"});this.remoteResource=this.previewResource.with({scheme:M,authority:"remote"});this.acceptedResource=this.previewResource.with({scheme:M,authority:"accepted"});this.localGlobalStateProvider=v.createInstance(Po),this._register(i.watch(this.extUri.dirname(this.environmentService.argvResource))),this._register(k.any(k.filter(i.onDidFilesChange,y=>y.contains(this.environmentService.argvResource)),k.filter(n.onDidChange,y=>!!(y.targetChanges.some(x=>this.syncResource.profile.id===x.id)||y.valueChanges.some(({profile:x,changes:E})=>this.syncResource.profile.id===x.id&&E.some(R=>R.target===0)))))((()=>this.triggerLocalChange())))}async generateSyncPreview(e,t,n){let i=e.syncData?JSON.parse(e.syncData.content):null;t=t===null&&n?e:t;let s=t&&t.syncData?JSON.parse(t.syncData.content):null,a=await this.localGlobalStateProvider.getLocalGlobalState(this.syncResource.profile);i?this.logService.trace(`${this.syncResourceLogLabel}: Merging remote ui state with local ui state...`):this.logService.trace(`${this.syncResourceLogLabel}: Remote ui state does not exist. Synchronizing ui state for the first time.`);let l=await this.getStorageKeys(s),{local:c,remote:d}=_c(a.storage,i?i.storage:null,s?s.storage:null,l,this.logService),u={content:null,local:c,remote:d,localChange:Object.keys(c.added).length>0||Object.keys(c.updated).length>0||c.removed.length>0?2:0,remoteChange:d.all!==null?2:0},p=_i(a,!1);return[{baseResource:this.baseResource,baseContent:s?_i(s,!1):p,localResource:this.localResource,localContent:p,localUserData:a,remoteResource:this.remoteResource,remoteContent:i?_i(i,!1):null,previewResource:this.previewResource,previewResult:u,localChange:u.localChange,remoteChange:u.remoteChange,acceptedResource:this.acceptedResource,storageKeys:l}]}async hasRemoteChanged(e){let t=e.syncData?JSON.parse(e.syncData.content):null;if(t===null)return!0;let n=await this.localGlobalStateProvider.getLocalGlobalState(this.syncResource.profile),i=await this.getStorageKeys(t),{remote:s}=_c(n.storage,t.storage,t.storage,i,this.logService);return s.all!==null}async getMergeResult(e,t){return{...e.previewResult,hasConflicts:!1}}async getAcceptResult(e,t,n,i){if(this.extUri.isEqual(t,this.localResource))return this.acceptLocal(e);if(this.extUri.isEqual(t,this.remoteResource))return this.acceptRemote(e);if(this.extUri.isEqual(t,this.previewResource))return e.previewResult;throw new Error(`Invalid Resource: ${t.toString()}`)}async acceptLocal(e){if(e.remoteContent!==null){let t=JSON.parse(e.remoteContent),{local:n,remote:i}=_c(e.localUserData.storage,t.storage,t.storage,e.storageKeys,this.logService);return{content:e.remoteContent,local:n,remote:i,localChange:0,remoteChange:i.all!==null?2:0}}else return{content:e.localContent,local:{added:{},removed:[],updated:{}},remote:{added:Object.keys(e.localUserData.storage),removed:[],updated:[],all:e.localUserData.storage},localChange:0,remoteChange:2}}async acceptRemote(e){if(e.remoteContent!==null){let t=JSON.parse(e.remoteContent),{local:n,remote:i}=_c(e.localUserData.storage,t.storage,e.localUserData.storage,e.storageKeys,this.logService);return{content:e.remoteContent,local:n,remote:i,localChange:Object.keys(n.added).length>0||Object.keys(n.updated).length>0||n.removed.length>0?2:0,remoteChange:0}}else return{content:e.remoteContent,local:{added:{},removed:[],updated:{}},remote:{added:[],removed:[],updated:[],all:null},localChange:0,remoteChange:0}}async applyResult(e,t,n,i){let{localUserData:s}=n[0][0],{local:a,remote:l,localChange:c,remoteChange:d}=n[0][1];if(c===0&&d===0&&this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing ui state.`),c!==0&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating local ui state...`),await this.backupLocal(JSON.stringify(s)),await this.localGlobalStateProvider.writeLocalGlobalState(a,this.syncResource.profile),this.logService.info(`${this.syncResourceLogLabel}: Updated local ui state`)),d!==0){this.logService.trace(`${this.syncResourceLogLabel}: Updating remote ui state...`);let u=JSON.stringify({storage:l.all});e=await this.updateRemoteUserData(u,i?null:e.ref),this.logService.info(`${this.syncResourceLogLabel}: Updated remote ui state.${l.added.length?` Added: ${l.added}.`:""}${l.updated.length?` Updated: ${l.updated}.`:""}${l.removed.length?` Removed: ${l.removed}.`:""}`)}t?.ref!==e.ref&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized ui state...`),await this.updateLastSyncUserData(e),this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized ui state`))}async resolveContent(e){if(this.extUri.isEqual(this.remoteResource,e)||this.extUri.isEqual(this.baseResource,e)||this.extUri.isEqual(this.localResource,e)||this.extUri.isEqual(this.acceptedResource,e)){let t=await this.resolvePreviewContent(e);return t&&_i(JSON.parse(t),!0)}return null}async hasLocalData(){try{let{storage:e}=await this.localGlobalStateProvider.getLocalGlobalState(this.syncResource.profile);if(Object.keys(e).length>1||e[`${Ro}.locale`]?.value!=="en")return!0}catch{}return!1}async getStorageKeys(e){let t=await this.userDataProfileStorageService.readStorageData(this.syncResource.profile),n=[],i=[];for(let[l,c]of t)c.target===0?n.push(l):c.target===1&&i.push(l);let s=[...n,...i],a=e?.storage?Object.keys(e.storage).filter(l=>!l.startsWith(Ro)&&!s.includes(l)&&t.get(l)!==void 0):[];if(!ze){let l=[...Dn.map(c=>vo(c)),pn];a.push(...l),i.push(...l)}return{user:n,machine:i,unregistered:a}}};Ea=b([g(2,Di),g(3,W),g(4,Ce),g(5,Qe),g(6,me),g(7,X),g(8,Oe),g(9,de),g(10,Q),g(11,K),g(12,te),g(13,bt)],Ea);var Po=class{constructor(r,e,t,n){this.fileService=r;this.environmentService=e;this.userDataProfileStorageService=t;this.logService=n}async getLocalGlobalState(r){let e={};if(r.isDefault){let n=await this.getLocalArgvContent(),i=je(n);for(let s of bR)i[s]!==void 0&&(e[`${Ro}${s}`]={version:1,value:i[s]})}let t=await this.userDataProfileStorageService.readStorageData(r);for(let[n,i]of t)i.value&&i.target===0&&(e[n]={version:1,value:i.value});return{storage:e}}async getLocalArgvContent(){try{this.logService.debug("GlobalStateSync#getLocalArgvContent",this.environmentService.argvResource);let r=await this.fileService.readFile(this.environmentService.argvResource);return this.logService.debug("GlobalStateSync#getLocalArgvContent - Resolved",this.environmentService.argvResource),r.value.toString()}catch(r){this.logService.debug(ee(r))}return"{}"}async writeLocalGlobalState({added:r,removed:e,updated:t},n){let i=ba("globalState",n),s={},a=new Map,l=await this.userDataProfileStorageService.readStorageData(n),c=(d,u)=>{for(let p of d){if(p.startsWith(Ro)){s[p.substring(Ro.length)]=u?u[p].value:void 0;continue}if(u){let m=u[p];m.value!==l.get(p)?.value&&a.set(p,m.value)}else l.get(p)!==void 0&&a.set(p,void 0)}};if(c(Object.keys(r),r),c(Object.keys(t),t),c(e),Object.keys(s).length){this.logService.trace(`${i}: Updating locale...`);let d=await this.getLocalArgvContent(),u=d;for(let p of Object.keys(s))u=Xt(u,[p],s[p],{});d!==u&&(this.logService.trace(`${i}: Updating locale...`),await this.fileService.writeFile(this.environmentService.argvResource,U.fromString(u)),this.logService.info(`${i}: Updated locale.`)),this.logService.info(`${i}: Updated locale`)}a.size&&(this.logService.trace(`${i}: Updating global state...`),await this.userDataProfileStorageService.updateStorageData(n,a,0),this.logService.info(`${i}: Updated global state`,[...a.keys()]))}};Po=b([g(0,W),g(1,X),g(2,Di),g(3,me)],Po);var Xp=class extends ir{constructor(r,e,t,n,i,s){super("globalState",t,n,i,e,r,s)}async doInitialize(r){let e=r.syncData?JSON.parse(r.syncData.content):null;if(!e){this.logService.info("Skipping initializing global state because remote global state does not exist.");return}let t={},n={};for(let i of Object.keys(e.storage))i.startsWith(Ro)?t[i.substring(Ro.length)]=e.storage[i].value:this.storageService.get(i,0)===void 0&&(n[i]=e.storage[i].value);if(Object.keys(t).length){let i="{}";try{i=(await this.fileService.readFile(this.environmentService.argvResource)).value.toString()}catch{}for(let s of Object.keys(t))i=Xt(i,[s],t[s],{});await this.fileService.writeFile(this.environmentService.argvResource,U.fromString(i))}if(Object.keys(n).length){let i=[];for(let s of Object.keys(n))i.push({key:s,value:n[s],scope:0,target:0});this.storageService.storeAll(i,!0)}}};Xp=b([g(0,K),g(1,W),g(2,fe),g(3,X),g(4,me),g(5,te)],Xp);var Yp=class{constructor(r,e,t,n,i){this.userDataSyncStoreClient=r;this.storageService=e;this.environmentService=t;this.fileService=n;this.logService=i}getSyncStoreType(r){return this.parseGlobalState(r)?.storage[pn]?.value}async sync(r){let e=Pi(Le());try{return await this.doSync(r,e)}catch(t){if(t instanceof xe&&t.code==="PreconditionFailed")return this.logService.info("Failed to synchronize UserDataSyncStoreType as there is a new remote version available. Synchronizing again..."),this.doSync(r,e);throw t}}async doSync(r,e){let t=await this.userDataSyncStoreClient.readResource("globalState",null,void 0,e),n=this.parseGlobalState(t)||{storage:{}};n.storage[pn]={value:r,version:jh};let i=await Hr(this.environmentService,this.fileService,this.storageService),s={version:jh,machineId:i,content:_i(n,!1)};await this.userDataSyncStoreClient.writeResource("globalState",JSON.stringify(s),t.ref,void 0,e)}parseGlobalState({content:r}){if(!r)return null;let e=JSON.parse(r);if(Eo(e))return e?JSON.parse(e.content):null;throw new Error("Invalid remote data")}};Yp=b([g(1,K),g(2,X),g(3,W),g(4,V)],Yp);function kc(o){return je(o)||[]}async function Zh(o,r,e,t,n){let i=kc(o),s=kc(r),a=e?kc(e):null,l=[...i,...s,...a||[]].map(R=>R.key),c=await n.resolveUserBindings(l),d=xR(i,s,a,c);if(!d.hasLocalForwarded&&!d.hasRemoteForwarded)return{mergeContent:o,hasChanges:!1,hasConflicts:!1};if(!d.hasLocalForwarded&&d.hasRemoteForwarded)return{mergeContent:r,hasChanges:!0,hasConflicts:!1};if(d.hasLocalForwarded&&!d.hasRemoteForwarded)return{mergeContent:o,hasChanges:!0,hasConflicts:!1};let u=Jh(i),p=Jh(s),m=a?Jh(a):null,h=Xh(u,p,c),v=m?Xh(m,u,c):{added:[...u.keys()].reduce((R,F)=>(R.add(F),R),new Set),removed:new Set,updated:new Set},y=m?Xh(m,p,c):{added:[...p.keys()].reduce((R,F)=>(R.add(F),R),new Set),removed:new Set,updated:new Set},x=Bx(h,v,y),E=o;for(let R of x.removed.values())x.conflicts.has(R)||(E=PR(E,R,t));for(let R of x.added.values()){if(x.conflicts.has(R))continue;let F=p.get(R);if(F.some(H=>H.command!==`-${R}`&&d.conflicts.has(c[H.key]))){x.conflicts.add(R);continue}E=wR(E,F,t)}for(let R of x.updated.values()){if(x.conflicts.has(R))continue;let F=p.get(R);if(F.some(H=>H.command!==`-${R}`&&d.conflicts.has(c[H.key]))){x.conflicts.add(R);continue}E=RR(E,R,F,t)}return{mergeContent:E,hasChanges:!0,hasConflicts:x.conflicts.size>0}}function Bx(o,r,e){let t=new Set,n=new Set,i=new Set,s=new Set;for(let a of r.removed.values())e.updated.has(a)&&s.add(a);for(let a of e.removed.values())s.has(a)||(r.updated.has(a)?s.add(a):n.add(a));for(let a of r.added.values())s.has(a)||e.added.has(a)&&o.updated.has(a)&&s.add(a);for(let a of e.added.values())s.has(a)||(r.added.has(a)?o.updated.has(a)&&s.add(a):t.add(a));for(let a of r.updated.values())s.has(a)||e.updated.has(a)&&o.updated.has(a)&&s.add(a);for(let a of e.updated.values())s.has(a)||(r.updated.has(a)?o.updated.has(a)&&s.add(a):i.add(a));return{added:t,removed:n,updated:i,conflicts:s}}function xR(o,r,e,t){let n=new Set,i=Hh(o,t),s=Hh(r,t),a=e?Hh(e,t):null,l=Qh(i,s);if(l.added.size===0&&l.removed.size===0&&l.updated.size===0)return{hasLocalForwarded:!1,hasRemoteForwarded:!1,added:n,removed:n,updated:n,conflicts:n};let c=a?Qh(a,i):{added:[...i.keys()].reduce((v,y)=>(v.add(y),v),new Set),removed:new Set,updated:new Set};if(c.added.size===0&&c.removed.size===0&&c.updated.size===0)return{hasLocalForwarded:!1,hasRemoteForwarded:!0,added:n,removed:n,updated:n,conflicts:n};let d=a?Qh(a,s):{added:[...s.keys()].reduce((v,y)=>(v.add(y),v),new Set),removed:new Set,updated:new Set};if(d.added.size===0&&d.removed.size===0&&d.updated.size===0)return{hasLocalForwarded:!0,hasRemoteForwarded:!1,added:n,removed:n,updated:n,conflicts:n};let{added:u,removed:p,updated:m,conflicts:h}=Bx(l,c,d);return{hasLocalForwarded:!0,hasRemoteForwarded:!0,added:u,removed:p,updated:m,conflicts:h}}function Hh(o,r){let e=new Map;for(let t of o){let n=r[t.key],i=e.get(n);i||(i=[],e.set(n,i)),i.push(t)}return e}function Jh(o){let r=new Map;for(let e of o){let t=e.command[0]==="-"?e.command.substring(1):e.command,n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}return r}function Qh(o,r){let e=[...o.keys()],t=[...r.keys()],n=t.filter(a=>!e.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),i=e.filter(a=>!t.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),s=new Set;for(let a of e){if(i.has(a))continue;let l=o.get(a).map(d=>({...d,key:a})),c=r.get(a).map(d=>({...d,key:a}));Pt(l,c,(d,u)=>Yh(d,u))||s.add(a)}return{added:n,removed:i,updated:s}}function Xh(o,r,e){let t=[...o.keys()],n=[...r.keys()],i=n.filter(l=>!t.includes(l)).reduce((l,c)=>(l.add(c),l),new Set),s=t.filter(l=>!n.includes(l)).reduce((l,c)=>(l.add(c),l),new Set),a=new Set;for(let l of t){if(s.has(l))continue;let c=o.get(l).map(u=>({...u,key:e[u.key]})),d=r.get(l).map(u=>({...u,key:e[u.key]}));ER(c,d)||a.add(l)}return{added:i,removed:s,updated:a}}function ER(o,r){return!(!Pt(o.filter(({command:e})=>e[0]!=="-"),r.filter(({command:e})=>e[0]!=="-"),(e,t)=>Yh(e,t))||!Pt(o.filter(({command:e})=>e[0]==="-"),r.filter(({command:e})=>e[0]==="-"),(e,t)=>Yh(e,t)))}function Yh(o,r){if(o.command!==r.command||o.key!==r.key)return!1;let e=Tt.deserialize(o.when),t=Tt.deserialize(r.when);return!(e&&!t||!e&&t||e&&t&&!e.equals(t)||!it(o.args,r.args))}function wR(o,r,e){for(let t of r)o=Xt(o,[-1],t,e);return o}function PR(o,r,e){let t=kc(o);for(let n=t.length-1;n>=0;n--)(t[n].command===r||t[n].command===`-${r}`)&&(o=Xt(o,[n],void 0,e));return o}function RR(o,r,e,t){let n=kc(o),i=n.findIndex(s=>s.command===r||s.command===`-${r}`);for(let s=n.length-1;s>=0;s--)(n[s].command===r||n[s].command===`-${r}`)&&(o=Xt(o,[s],void 0,t));for(let s=e.length-1;s>=0;s--)o=Xt(o,[i],e[s],t);return o}function Uc(o,r,e){try{let t=JSON.parse(o);if(!r)return st(t.all)?null:t.all;switch(bn){case 2:return st(t.mac)?null:t.mac;case 3:return st(t.linux)?null:t.linux;case 1:return st(t.windows)?null:t.windows}}catch(t){return e.error(t),null}}var wa=class extends Ti{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h){super(e.keybindingsResource,{syncResource:"keybindings",profile:e},t,c,d,u,n,i,l,m,s,p,a,h);this.version=2;this.previewResource=this.extUri.joinPath(this.syncPreviewFolder,"keybindings.json");this.baseResource=this.previewResource.with({scheme:M,authority:"base"});this.localResource=this.previewResource.with({scheme:M,authority:"local"});this.remoteResource=this.previewResource.with({scheme:M,authority:"remote"});this.acceptedResource=this.previewResource.with({scheme:M,authority:"accepted"});this._register(k.filter(a.onDidChangeConfiguration,v=>v.affectsConfiguration("settingsSync.keybindingsPerPlatform"))(()=>this.triggerLocalChange()))}async generateSyncPreview(e,t,n,i){let s=e.syncData?Uc(e.syncData.content,i.keybindingsPerPlatform??this.syncKeybindingsPerPlatform(),this.logService):null;t=t===null&&n?e:t;let a=t?this.getKeybindingsContentFromLastSyncUserData(t):null,l=await this.getLocalFileContent(),c=await this.getFormattingOptions(),d=null,u=!1,p=!1,m=!1;if(s){let y=l?l.value.toString():"[]";if(y=y||"[]",this.hasErrors(y,!0))throw new xe(S(2710,null),"LocalInvalidContent",this.resource);if(!a||a!==y||a!==s){this.logService.trace(`${this.syncResourceLogLabel}: Merging remote keybindings with local keybindings...`);let x=await Zh(y,s,a,c,this.userDataSyncUtilService);x.hasChanges&&(d=x.mergeContent,m=x.hasConflicts,u=m||x.mergeContent!==y,p=m||x.mergeContent!==s)}}else l&&(this.logService.trace(`${this.syncResourceLogLabel}: Remote keybindings does not exist. Synchronizing keybindings for the first time.`),d=l.value.toString(),p=!0);let h={content:m?a:d,localChange:u?l?2:1:0,remoteChange:p?2:0,hasConflicts:m},v=l?l.value.toString():null;return[{fileContent:l,baseResource:this.baseResource,baseContent:a,localResource:this.localResource,localContent:v,localChange:h.localChange,remoteResource:this.remoteResource,remoteContent:s,remoteChange:h.remoteChange,previewResource:this.previewResource,previewResult:h,acceptedResource:this.acceptedResource}]}async hasRemoteChanged(e){let t=this.getKeybindingsContentFromLastSyncUserData(e);if(t===null)return!0;let n=await this.getLocalFileContent(),i=n?n.value.toString():"",s=await this.getFormattingOptions(),a=await Zh(i||"[]",t,t,s,this.userDataSyncUtilService);return a.hasConflicts||a.mergeContent!==t}async getMergeResult(e,t){return e.previewResult}async getAcceptResult(e,t,n,i){if(this.extUri.isEqual(t,this.localResource))return{content:e.fileContent?e.fileContent.value.toString():null,localChange:0,remoteChange:2};if(this.extUri.isEqual(t,this.remoteResource))return{content:e.remoteContent,localChange:2,remoteChange:0};if(this.extUri.isEqual(t,this.previewResource))return n===void 0?{content:e.previewResult.content,localChange:e.previewResult.localChange,remoteChange:e.previewResult.remoteChange}:{content:n,localChange:2,remoteChange:2};throw new Error(`Invalid Resource: ${t.toString()}`)}async applyResult(e,t,n,i){let{fileContent:s}=n[0][0],{content:a,localChange:l,remoteChange:c}=n[0][1];if(l===0&&c===0&&this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing keybindings.`),a!==null&&(a=a.trim(),a=a||"[]",this.hasErrors(a,!0)))throw new xe(S(2710,null),"LocalInvalidContent",this.resource);if(l!==0&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating local keybindings...`),s&&await this.backupLocal(this.toSyncContent(s.value.toString())),await this.updateLocalFileContent(a||"[]",s,i),this.logService.info(`${this.syncResourceLogLabel}: Updated local keybindings`)),c!==0){this.logService.trace(`${this.syncResourceLogLabel}: Updating remote keybindings...`);let d=this.toSyncContent(a||"[]",e.syncData?.content);e=await this.updateRemoteUserData(d,i?null:e.ref),this.logService.info(`${this.syncResourceLogLabel}: Updated remote keybindings`)}try{await this.fileService.del(this.previewResource)}catch{}t?.ref!==e.ref&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized keybindings...`),await this.updateLastSyncUserData(e,{platformSpecific:this.syncKeybindingsPerPlatform()}),this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized keybindings`))}async hasLocalData(){try{let e=await this.getLocalFileContent();if(e){let t=je(e.value.toString());if(Zn(t))return!0}}catch(e){if(e.fileOperationResult!==1)return!0}return!1}async resolveContent(e){return this.extUri.isEqual(this.remoteResource,e)||this.extUri.isEqual(this.baseResource,e)||this.extUri.isEqual(this.localResource,e)||this.extUri.isEqual(this.acceptedResource,e)?this.resolvePreviewContent(e):null}getKeybindingsContentFromLastSyncUserData(e){return!e.syncData||e.platformSpecific!==void 0&&e.platformSpecific!==this.syncKeybindingsPerPlatform()?null:Uc(e.syncData.content,this.syncKeybindingsPerPlatform(),this.logService)}toSyncContent(e,t){let n={};try{n=JSON.parse(t||"{}")}catch(i){this.logService.error(i)}switch(this.syncKeybindingsPerPlatform()?delete n.all:n.all=e,bn){case 2:n.mac=e;break;case 3:n.linux=e;break;case 1:n.windows=e;break}return JSON.stringify(n)}syncKeybindingsPerPlatform(){return!!this.configurationService.getValue(wc)}};wa=b([g(2,Ce),g(3,Qe),g(4,me),g(5,Q),g(6,Oe),g(7,W),g(8,X),g(9,K),g(10,Ri),g(11,de),g(12,te)],wa);var Zp=class extends ir{constructor(r,e,t,n,i,s){super("keybindings",e,t,n,r,i,s)}async doInitialize(r){let e=r.syncData?this.getKeybindingsContentFromSyncContent(r.syncData.content):null;if(!e){this.logService.info("Skipping initializing keybindings because remote keybindings does not exist.");return}if(!await this.isEmpty()){this.logService.info("Skipping initializing keybindings because local keybindings exist.");return}await this.fileService.writeFile(this.userDataProfilesService.defaultProfile.keybindingsResource,U.fromString(e)),await this.updateLastSyncUserData(r)}async isEmpty(){try{let r=await this.fileService.readFile(this.userDataProfilesService.defaultProfile.settingsResource),e=je(r.value.toString());return!Zn(e)}catch(r){return r.fileOperationResult===1}}getKeybindingsContentFromSyncContent(r){try{return Uc(r,!0,this.logService)}catch(e){return this.logService.error(e),null}}};Zp=b([g(0,W),g(1,fe),g(2,X),g(3,me),g(4,K),g(5,te)],Zp);function ev(o,r,e){let t={},n={},i=new Set;if(!r)return{local:{added:t,updated:n,removed:[...i.values()]},remote:{added:o,updated:{},removed:[]},conflicts:[]};let s=ef(o,r);if(s.added.size===0&&s.removed.size===0&&s.updated.size===0)return{local:{added:t,updated:n,removed:[...i.values()]},remote:{added:{},updated:{},removed:[]},conflicts:[]};let a=ef(e,o),l=ef(e,r),c={},d={},u=new Set,p=new Set;for(let m of a.removed.values())l.updated.has(m)?t[m]=r[m]:u.add(m);for(let m of l.removed.values())p.has(m)||(a.updated.has(m)?p.add(m):i.add(m));for(let m of a.updated.values())p.has(m)||(l.updated.has(m)?s.updated.has(m)&&p.add(m):d[m]=o[m]);for(let m of l.updated.values())p.has(m)||(a.updated.has(m)?s.updated.has(m)&&p.add(m):o[m]!==void 0&&(n[m]=r[m]));for(let m of a.added.values())p.has(m)||(l.added.has(m)?s.updated.has(m)&&p.add(m):c[m]=o[m]);for(let m of l.added.values())p.has(m)||(a.added.has(m)?s.updated.has(m)&&p.add(m):t[m]=r[m]);return{local:{added:t,removed:[...i.values()],updated:n},remote:{added:c,removed:[...u.values()],updated:d},conflicts:[...p.values()]}}function ef(o,r){let e=o?Object.keys(o):[],t=r?Object.keys(r):[],n=t.filter(a=>!e.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),i=e.filter(a=>!t.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),s=new Set;for(let a of e){if(i.has(a))continue;let l=o[a],c=r[a];l!==c&&s.add(a)}return{added:n,removed:i,updated:s}}function $x(o,r){let{added:e,removed:t,updated:n}=ef(o,r);return e.size===0&&t.size===0&&n.size===0}function tf(o){return JSON.parse(o.content)}var Pa=class extends mr{constructor(e,t,n,i,s,a,l,c,d,u,p,m){let h={syncResource:"prompts",profile:e};super(h,t,i,n,s,a,l,u,p,c,d,m);this.version=1;this.promptsFolder=e.promptsHome,this._register(this.fileService.watch(n.userRoamingDataHome)),this._register(this.fileService.watch(this.promptsFolder)),this._register(k.filter(this.fileService.onDidFilesChange,v=>v.affects(this.promptsFolder))(()=>this.triggerLocalChange()))}async generateSyncPreview(e,t,n){let i=await this.getPromptsFileContents(),s=this.toPromptContents(i),a=e.syncData?this.parsePrompts(e.syncData):null;t=t===null&&n?e:t;let l=t&&t.syncData?this.parsePrompts(t.syncData):null;a?this.logService.trace(`${this.syncResourceLogLabel}: Merging remote prompts with local prompts...`):this.logService.trace(`${this.syncResourceLogLabel}: Remote prompts does not exist. Synchronizing prompts for the first time.`);let c=ev(s,a,l);return this.getResourcePreviews(c,i,a||{},l||{})}async hasRemoteChanged(e){let t=e.syncData?this.parsePrompts(e.syncData):null;if(t===null)return!0;let n=await this.getPromptsFileContents(),i=this.toPromptContents(n),s=ev(i,t,t);return Object.keys(s.remote.added).length>0||Object.keys(s.remote.updated).length>0||s.remote.removed.length>0||s.conflicts.length>0}async getMergeResult(e,t){return e.previewResult}async getAcceptResult(e,t,n,i){if(this.extUri.isEqualOrParent(t,this.syncPreviewFolder.with({scheme:M,authority:"local"})))return{content:e.fileContent?e.fileContent.value.toString():null,localChange:0,remoteChange:e.fileContent?e.remoteContent!==null?2:1:3};if(this.extUri.isEqualOrParent(t,this.syncPreviewFolder.with({scheme:M,authority:"remote"})))return{content:e.remoteContent,localChange:e.remoteContent!==null?e.fileContent?2:1:3,remoteChange:0};if(this.extUri.isEqualOrParent(t,this.syncPreviewFolder))return n===void 0?{content:e.previewResult.content,localChange:e.previewResult.localChange,remoteChange:e.previewResult.remoteChange}:{content:n,localChange:n===null?e.fileContent!==null?3:0:2,remoteChange:n===null?e.remoteContent!==null?3:0:2};throw new Error(`Invalid Resource: ${t.toString()}`)}async applyResult(e,t,n,i){let s=n.map(([a,l])=>({...a,acceptResult:l}));s.every(({localChange:a,remoteChange:l})=>a===0&&l===0)&&this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing prompts.`),s.some(({localChange:a})=>a!==0)&&(await this.updateLocalBackup(s),await this.updateLocalPrompts(s,i)),s.some(({remoteChange:a})=>a!==0)&&(e=await this.updateRemotePrompts(s,e,i)),t?.ref!==e.ref&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized prompts...`),await this.updateLastSyncUserData(e),this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized prompts`));for(let{previewResource:a}of s)try{await this.fileService.del(a)}catch{}}getResourcePreviews(e,t,n,i){let s=new Map;for(let a of Object.keys(e.local.added)){let l={content:e.local.added[a],hasConflicts:!1,localChange:1,remoteChange:0};s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:null,fileContent:null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),localContent:null,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a],previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of Object.keys(e.local.updated)){let l={content:e.local.updated[a],hasConflicts:!1,localChange:2,remoteChange:0},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a],localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a],previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of e.local.removed){let l={content:null,hasConflicts:!1,localChange:3,remoteChange:0},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a],localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:null,previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of Object.keys(e.remote.added)){let l={content:e.remote.added[a],hasConflicts:!1,localChange:0,remoteChange:1},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a],localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:null,previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of Object.keys(e.remote.updated)){let l={content:e.remote.updated[a],hasConflicts:!1,localChange:0,remoteChange:2},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a],localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a],previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of e.remote.removed){let l={content:null,hasConflicts:!1,localChange:0,remoteChange:3};s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:null,localContent:null,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a],previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of e.conflicts){let l={content:i[a]??null,hasConflicts:!0,localChange:t[a]?2:1,remoteChange:n[a]?2:1},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a]||null,localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a]||null,previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of Object.keys(t))if(!s.has(a)){let l={content:t[a]?t[a].value.toString():null,hasConflicts:!1,localChange:0,remoteChange:0},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a]||null,localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a]||null,previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}return[...s.values()]}async resolveContent(e){return this.extUri.isEqualOrParent(e,this.syncPreviewFolder.with({scheme:M,authority:"remote"}))||this.extUri.isEqualOrParent(e,this.syncPreviewFolder.with({scheme:M,authority:"local"}))||this.extUri.isEqualOrParent(e,this.syncPreviewFolder.with({scheme:M,authority:"base"}))||this.extUri.isEqualOrParent(e,this.syncPreviewFolder.with({scheme:M,authority:"accepted"}))?this.resolvePreviewContent(e):null}async hasLocalData(){try{let e=await this.getPromptsFileContents();if(Object.keys(e).length)return!0}catch{}return!1}async updateLocalBackup(e){let t={};for(let n of e)n.fileContent&&(t[this.extUri.basename(n.localResource)]=n.fileContent);await this.backupLocal(JSON.stringify(this.toPromptContents(t)))}async updateLocalPrompts(e,t){for(let{fileContent:n,acceptResult:i,localResource:s,remoteResource:a,localChange:l}of e)if(l!==0){let c=a?this.extUri.basename(a):this.extUri.basename(s),d=this.extUri.joinPath(this.promptsFolder,c);l===3?(this.logService.trace(`${this.syncResourceLogLabel}: Deleting prompt...`,this.extUri.basename(d)),await this.fileService.del(d),this.logService.info(`${this.syncResourceLogLabel}: Deleted prompt`,this.extUri.basename(d))):l===1?(this.logService.trace(`${this.syncResourceLogLabel}: Creating prompt...`,this.extUri.basename(d)),await this.fileService.createFile(d,U.fromString(i.content),{overwrite:t}),this.logService.info(`${this.syncResourceLogLabel}: Created prompt`,this.extUri.basename(d))):(this.logService.trace(`${this.syncResourceLogLabel}: Updating prompt...`,this.extUri.basename(d)),await this.fileService.writeFile(d,U.fromString(i.content),t?void 0:n),this.logService.info(`${this.syncResourceLogLabel}: Updated prompt`,this.extUri.basename(d)))}}async updateRemotePrompts(e,t,n){let i=t.syncData?this.parsePrompts(t.syncData):{},s=Ct(i);for(let{acceptResult:a,localResource:l,remoteResource:c,remoteChange:d}of e)if(d!==0){let u=l?this.extUri.basename(l):this.extUri.basename(c);d===3?delete s[u]:s[u]=a.content}return $x(i,s)||(this.logService.trace(`${this.syncResourceLogLabel}: Updating remote prompts...`),t=await this.updateRemoteUserData(JSON.stringify(s),n?null:t.ref),this.logService.info(`${this.syncResourceLogLabel}: Updated remote prompts`)),t}parsePrompts(e){return tf(e)}toPromptContents(e){let t={};for(let n of Object.keys(e))t[n]=e[n].value.toString();return t}async getPromptsFileContents(){let e={},t;try{t=await this.fileService.resolve(this.promptsFolder)}catch(n){if(n instanceof et&&n.fileOperationResult===1)return e;throw n}for(let n of t.children||[]){let i=n.resource,s=i.path;if([".prompt.md",".instructions.md",".chatmode.md",".agent.md"].some(a=>s.endsWith(a))){let a=this.extUri.relativePath(this.promptsFolder,i),l=await this.fileService.readFile(i);e[a]=l}}return e}};Pa=b([g(2,X),g(3,W),g(4,K),g(5,Ce),g(6,Qe),g(7,me),g(8,Q),g(9,Oe),g(10,de),g(11,te)],Pa);function Gx(o,r,e){let t=[];e?t=CR(e):t=TR(r);let n=[],i=[...Vp()];if(Array.isArray(t))for(let s of t)s.startsWith("-")?i.push(s.substring(1)):n.push(s);return dt([...o,...n].filter(s=>!i.includes(s)))}function TR(o){let r=o.inspect("settingsSync.ignoredSettings").userValue;return r!==void 0||(r=o.inspect("sync.ignoredSettings").userValue,r!==void 0)?r:o.getValue("settingsSync.ignoredSettings")||[]}function CR(o){let r=je(o);return r?r["settingsSync.ignoredSettings"]||r["sync.ignoredSettings"]||[]:[]}function _n(o,r,e,t){if(e.length){let n=Ta(r),i=je(r)||{},s=je(o);if(!s)return o;let a=[];for(let l of e){let c=i[l],d=s[l];c===void 0?o=Xt(o,[l],void 0,t):d!==void 0?o=Xt(o,[l],c,t):a.push(Lc(l,n))}a.sort((l,c)=>l.startOffset-c.startOffset),a.forEach(l=>o=rv(l.setting.key,r,o,t))}return o}function iv(o,r,e,t,n,i){let s=_n(o,r,t,i),a=e!==s,l=e!==r;if(!a&&!l)return{conflictsSettings:[],localContent:null,remoteContent:null,hasConflicts:!1};if(a&&!l)return{conflictsSettings:[],localContent:null,remoteContent:s,hasConflicts:!1};if(l&&!a)return{conflictsSettings:[],localContent:_n(r,o,t,i),remoteContent:null,hasConflicts:!1};if(e===null&&sf(o)){let C=rf(o,r,t)?null:_n(r,o,t,i);return{conflictsSettings:[],localContent:C,remoteContent:null,hasConflicts:!1}}let c=o,d=r,u=je(o),p=je(r),m=e?je(e):null,h=t.reduce((C,A)=>(C.add(A),C),new Set),v=tv(u,p,h),y=tv(m,u,h),x=tv(m,p,h),E=new Map,R=new Set,F=C=>{R.add(C);let A=n.filter(({key:ae})=>ae===C)[0];A?(c=Xt(c,[C],A.value,i),d=Xt(d,[C],A.value,i)):E.set(C,{key:C,localValue:u[C],remoteValue:p[C]})};for(let C of y.removed.values())x.updated.has(C)?F(C):d=Xt(d,[C],void 0,i);for(let C of x.removed.values())R.has(C)||(y.updated.has(C)?F(C):c=Xt(c,[C],void 0,i));for(let C of y.updated.values())R.has(C)||(x.updated.has(C)?v.updated.has(C)&&F(C):d=Xt(d,[C],u[C],i));for(let C of x.updated.values())R.has(C)||(y.updated.has(C)?v.updated.has(C)&&F(C):c=Xt(c,[C],p[C],i));for(let C of y.added.values())R.has(C)||(x.added.has(C)?v.updated.has(C)&&F(C):d=rv(C,c,d,i));for(let C of x.added.values())R.has(C)||(y.added.has(C)?v.updated.has(C)&&F(C):c=rv(C,d,c,i));let H=E.size>0||!rf(c,d,t),qe=H||!rf(c,o,[]),B=H||!rf(d,r,[]);return{localContent:qe?c:null,remoteContent:B?d:null,conflictsSettings:[...E.values()],hasConflicts:H}}function rf(o,r,e){if(o===r)return!0;let t=je(o),n=je(r),i=e.reduce((l,c)=>(l.add(c),l),new Set),s=Ta(o).filter(l=>!(l.setting&&i.has(l.setting.key))),a=Ta(r).filter(l=>!(l.setting&&i.has(l.setting.key)));if(s.length!==a.length)return!1;for(let l=0;l<s.length;l++){let c=s[l],d=a[l];if(c.setting&&d.setting){if(c.setting.key!==d.setting.key||!it(t[c.setting.key],n[c.setting.key]))return!1}else if(!c.setting&&!d.setting){if(c.value!==d.value)return!1}else return!1}return!0}function sf(o){return o?Ta(o).length===0:!0}function tv(o,r,e){let t=o?Object.keys(o).filter(l=>!e.has(l)):[],n=Object.keys(r).filter(l=>!e.has(l)),i=n.filter(l=>!t.includes(l)).reduce((l,c)=>(l.add(c),l),new Set),s=t.filter(l=>!n.includes(l)).reduce((l,c)=>(l.add(c),l),new Set),a=new Set;if(o)for(let l of t){if(s.has(l))continue;let c=o[l],d=r[l];it(c,d)||a.add(l)}return{added:i,removed:s,updated:a}}function rv(o,r,e,t){let n=je(r),i=Ta(r),s=Ta(e),a=DR(o,i,s);return _R(e,o,n[o],a,s,t)}function DR(o,r,e){let t=r.findIndex(i=>i.setting?.key===o),n=r[t-1];if(n){if(n.setting){let s=Lc(n.setting.key,e);if(s)return{index:e.indexOf(s),insertAfter:!0}}else{let s=nv(t,r);if(s){let a=Lc(s.setting.key,e);if(a){let l=of(e.indexOf(a),e),c=Ra(r,s,r[t]);if(l){let d=Ra(e,a,l),u=nf(c,d);return u?{index:e.indexOf(u),insertAfter:!0}:{index:e.indexOf(l),insertAfter:!1}}else{let d=Ra(e,a,e[e.length-1]),u=nf(c,d);return u?{index:e.indexOf(u),insertAfter:!0}:{index:e.length-1,insertAfter:!0}}}}}let i=r[t+1];if(i)if(i.setting){let s=Lc(i.setting.key,e);if(s)return{index:e.indexOf(s),insertAfter:!1}}else{let s=of(t,r);if(s){let a=Lc(s.setting.key,e);if(a){let l=nv(e.indexOf(a),e),c=Ra(r,r[t],s);if(l){let d=Ra(e,l,a),u=nf(c.reverse(),d.reverse());return u?{index:e.indexOf(u),insertAfter:!1}:{index:e.indexOf(l),insertAfter:!0}}else{let d=Ra(e,e[0],a),u=nf(c.reverse(),d.reverse());return u?{index:e.indexOf(u),insertAfter:!1}:{index:0,insertAfter:!1}}}}}}return{index:e.length-1,insertAfter:!0}}function _R(o,r,e,t,n,i){let s;return t.index===-1?s=Ds(o,[r],e,i):s=kR(o,r,e,t,n,i).map(a=>vi(o,a,i)[0]),Pu(o,s)}function kR(o,r,e,t,n,i){let s=`${JSON.stringify(r)}: ${JSON.stringify(e)}`,a=kg(i,o),l=n[t.index];if(t.insertAfter){let c=[];if(l.setting)c.push({offset:l.endOffset,length:0,content:","+s});else{let d=of(t.index,n),u=nv(t.index,n),p=u?.setting?.commaOffset;u&&p===void 0&&c.push({offset:u.endOffset,length:0,content:","});let m=p!==void 0&&p>l.endOffset;c.push({offset:m?p+1:l.endOffset,length:0,content:d?a+s+",":a+s})}return c}else{if(l.setting)return[{offset:l.startOffset,length:0,content:s+","}];let c=(n[t.index-1]&&!n[t.index-1].setting?a:"")+s+(of(t.index,n)?",":"")+a;return[{offset:l.startOffset,length:0,content:c}]}}function Lc(o,r){return r.filter(e=>e.setting?.key===o)[0]}function nv(o,r){for(let e=o-1;e>=0;e--)if(r[e].setting)return r[e]}function of(o,r){for(let e=o+1;e<r.length;e++)if(r[e].setting)return r[e]}function Ra(o,r,e){let t=o.indexOf(r),n=o.indexOf(e);return o.filter((i,s)=>t<s&&s<n)}function nf(o,r){if(o.length&&r.length){let e=0;for(;e<r.length&&e<o.length;e++)if(o[e].value!==r[e].value)return r[e-1];return r[e-1]}}function Ta(o){let r=[],e=-1,t,n;return gi(o,{onObjectBegin:s=>{e++},onObjectProperty:(s,a,l)=>{e===0&&(t=a,n=s)},onObjectEnd:(s,a)=>{e--,e===0&&r.push({startOffset:t,endOffset:s+a,value:o.substring(t,s+a),setting:{key:n,commaOffset:void 0}})},onArrayBegin:(s,a)=>{e++},onArrayEnd:(s,a)=>{e--,e===0&&r.push({startOffset:t,endOffset:s+a,value:o.substring(t,s+a),setting:{key:n,commaOffset:void 0}})},onLiteralValue:(s,a,l)=>{e===0&&r.push({startOffset:t,endOffset:a+l,value:o.substring(t,a+l),setting:{key:n,commaOffset:void 0}})},onSeparator:(s,a,l)=>{if(e===0&&s===","){let c=r.length-1;for(;c>=0&&!r[c].setting;c--);let d=r[c];d&&r.splice(c,1,{startOffset:d.startOffset,endOffset:d.endOffset,value:d.value,setting:{key:d.setting.key,commaOffset:a}})}},onComment:(s,a)=>{e===0&&r.push({startOffset:s,endOffset:s+a,value:o.substring(s,s+a)})}}),r}function UR(o){return o&&o.settings&&typeof o.settings=="string"&&Object.keys(o).length===1}function lf(o){let r=JSON.parse(o);return UR(r)?r:{settings:o}}var To=class extends Ti{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h,v){super(e.settingsResource,{syncResource:"settings",profile:e},t,n,i,s,a,l,p,m,c,d,u,v);this.profile=e;this.extensionManagementService=h;this.version=2;this.previewResource=this.extUri.joinPath(this.syncPreviewFolder,"settings.json");this.baseResource=this.previewResource.with({scheme:M,authority:"base"});this.localResource=this.previewResource.with({scheme:M,authority:"local"});this.remoteResource=this.previewResource.with({scheme:M,authority:"remote"});this.acceptedResource=this.previewResource.with({scheme:M,authority:"accepted"});this.coreIgnoredSettings=void 0;this.systemExtensionsIgnoredSettings=void 0;this.userExtensionsIgnoredSettings=void 0}async getRemoteUserDataSyncConfiguration(e){let t=await this.getLastSyncUserData(),n=await this.getLatestRemoteUserData(e,t),i=this.getSettingsSyncContent(n),s=new Us(ho,this.logService);return i?.settings&&s.parse(i.settings),s.configurationModel.getValue(ho)||{}}async generateSyncPreview(e,t,n){let i=await this.getLocalFileContent(),s=await this.getFormattingOptions(),a=this.getSettingsSyncContent(e);t=t===null&&n?e:t;let l=t?this.getSettingsSyncContent(t):null,c=await this.getIgnoredSettings(),d=null,u=!1,p=!1,m=!1;if(a){let x=i?i.value.toString().trim():"{}";x=x||"{}",this.validateContent(x),this.logService.trace(`${this.syncResourceLogLabel}: Merging remote settings with local settings...`);let E=iv(x,a.settings,l?l.settings:null,c,[],s);d=E.localContent||E.remoteContent,u=E.localContent!==null,p=E.remoteContent!==null,m=E.hasConflicts}else i&&(this.logService.trace(`${this.syncResourceLogLabel}: Remote settings does not exist. Synchronizing settings for the first time.`),d=i.value.toString().trim()||"{}",this.validateContent(d),p=!0);let h=i?i.value.toString():null,v=l?.settings??null,y={content:m?v:d,localChange:u?2:0,remoteChange:p?2:0,hasConflicts:m};return[{fileContent:i,baseResource:this.baseResource,baseContent:v,localResource:this.localResource,localContent:h,localChange:y.localChange,remoteResource:this.remoteResource,remoteContent:a?a.settings:null,remoteChange:y.remoteChange,previewResource:this.previewResource,previewResult:y,acceptedResource:this.acceptedResource}]}async hasRemoteChanged(e){let t=this.getSettingsSyncContent(e);if(t===null)return!0;let n=await this.getLocalFileContent(),i=n?n.value.toString().trim():"",s=await this.getIgnoredSettings(),a=await this.getFormattingOptions();return iv(i||"{}",t.settings,t.settings,s,[],a).remoteContent!==null}async getMergeResult(e,t){let n=await this.getFormattingOptions(),i=await this.getIgnoredSettings();return{...e.previewResult,content:e.previewResult.content?_n(e.previewResult.content,"{}",i,n):null}}async getAcceptResult(e,t,n,i){let s=await this.getFormattingOptions(),a=await this.getIgnoredSettings();if(this.extUri.isEqual(t,this.localResource))return{content:e.fileContent?_n(e.fileContent.value.toString(),"{}",a,s):null,localChange:0,remoteChange:2};if(this.extUri.isEqual(t,this.remoteResource))return{content:e.remoteContent!==null?_n(e.remoteContent,e.fileContent?e.fileContent.value.toString():"{}",a,s):null,localChange:2,remoteChange:0};if(this.extUri.isEqual(t,this.previewResource))return n===void 0?{content:e.previewResult.content,localChange:e.previewResult.localChange,remoteChange:e.previewResult.remoteChange}:{content:n!==null?_n(n,e.fileContent?e.fileContent.value.toString():"{}",a,s):null,localChange:2,remoteChange:2};throw new Error(`Invalid Resource: ${t.toString()}`)}async applyResult(e,t,n,i){let{fileContent:s}=n[0][0],{content:a,localChange:l,remoteChange:c}=n[0][1];if(l===0&&c===0&&this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing settings.`),a=a?a.trim():"{}",a=a||"{}",this.validateContent(a),l!==0&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating local settings...`),s&&await this.backupLocal(JSON.stringify(this.toSettingsSyncContent(s.value.toString()))),await this.updateLocalFileContent(a,s,i),await this.configurationService.reloadConfiguration(3),this.logService.info(`${this.syncResourceLogLabel}: Updated local settings`)),c!==0){let d=await this.getFormattingOptions(),u=this.getSettingsSyncContent(e),p=await this.getIgnoredSettings(a);a=_n(a,u?u.settings:"{}",p,d),this.logService.trace(`${this.syncResourceLogLabel}: Updating remote settings...`),e=await this.updateRemoteUserData(JSON.stringify(this.toSettingsSyncContent(a)),i?null:e.ref),this.logService.info(`${this.syncResourceLogLabel}: Updated remote settings`)}try{await this.fileService.del(this.previewResource)}catch{}t?.ref!==e.ref&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized settings...`),await this.updateLastSyncUserData(e),this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized settings`))}async hasLocalData(){try{let e=await this.getLocalFileContent();if(e)return!sf(e.value.toString())}catch(e){if(e.fileOperationResult!==1)return!0}return!1}async resolveContent(e){return this.extUri.isEqual(this.remoteResource,e)||this.extUri.isEqual(this.localResource,e)||this.extUri.isEqual(this.acceptedResource,e)||this.extUri.isEqual(this.baseResource,e)?this.resolvePreviewContent(e):null}async resolvePreviewContent(e){let t=await super.resolvePreviewContent(e);if(t){let n=await this.getFormattingOptions(),i=await this.getIgnoredSettings();t=_n(t,"{}",i,n)}return t}getSettingsSyncContent(e){return e.syncData?this.parseSettingsSyncContent(e.syncData.content):null}parseSettingsSyncContent(e){try{return lf(e)}catch(t){this.logService.error(t)}return null}toSettingsSyncContent(e){return{settings:e}}async getIgnoredSettings(e){if(this.coreIgnoredSettings||(this.coreIgnoredSettings=this.userDataSyncUtilService.resolveDefaultCoreIgnoredSettings()),this.systemExtensionsIgnoredSettings||(this.systemExtensionsIgnoredSettings=this.getIgnoredSettingForSystemExtensions()),!this.userExtensionsIgnoredSettings){this.userExtensionsIgnoredSettings=this.getIgnoredSettingForUserExtensions();let n=this._register(k.any(k.filter(this.extensionManagementService.onDidInstallExtensions,(i=>i.some(({local:s})=>!!s))),k.filter(this.extensionManagementService.onDidUninstallExtension,(i=>!i.error)))(()=>{n.dispose(),this.userExtensionsIgnoredSettings=void 0}))}let t=(await Promise.all([this.coreIgnoredSettings,this.systemExtensionsIgnoredSettings,this.userExtensionsIgnoredSettings])).flat();return Gx(t,this.configurationService,e)}async getIgnoredSettingForSystemExtensions(){let e=await this.extensionManagementService.getInstalled(0);return dt(e.map(t=>Uh(t.manifest)).flat())}async getIgnoredSettingForUserExtensions(){let e=await this.extensionManagementService.getInstalled(1,this.profile.extensionsResource);return dt(e.map(t=>Uh(t.manifest)).flat())}validateContent(e){if(this.hasErrors(e,!1))throw new xe(S(2711,null),"LocalInvalidContent",this.resource)}};To=b([g(2,W),g(3,X),g(4,K),g(5,Ce),g(6,Qe),g(7,me),g(8,Ri),g(9,Q),g(10,Oe),g(11,de),g(12,rr),g(13,te)],To);var af=class extends ir{constructor(r,e,t,n,i,s){super("settings",e,t,n,r,i,s)}async doInitialize(r){let e=r.syncData?this.parseSettingsSyncContent(r.syncData.content):null;if(!e){this.logService.info("Skipping initializing settings because remote settings does not exist.");return}if(!await this.isEmpty()){this.logService.info("Skipping initializing settings because local settings exist.");return}await this.fileService.writeFile(this.userDataProfilesService.defaultProfile.settingsResource,U.fromString(e.settings)),await this.updateLastSyncUserData(r)}async isEmpty(){try{let r=await this.fileService.readFile(this.userDataProfilesService.defaultProfile.settingsResource);return sf(r.value.toString().trim())}catch(r){return r.fileOperationResult===1}}parseSettingsSyncContent(r){try{return lf(r)}catch(e){this.logService.error(e)}return null}};af=b([g(0,W),g(1,fe),g(2,X),g(3,me),g(4,K),g(5,te)],af);function ov(o,r,e){let t={},n={},i=new Set;if(!r)return{local:{added:t,updated:n,removed:[...i.values()]},remote:{added:o,updated:{},removed:[]},conflicts:[]};let s=cf(o,r);if(s.added.size===0&&s.removed.size===0&&s.updated.size===0)return{local:{added:t,updated:n,removed:[...i.values()]},remote:{added:{},updated:{},removed:[]},conflicts:[]};let a=cf(e,o),l=cf(e,r),c={},d={},u=new Set,p=new Set;for(let m of a.removed.values())l.updated.has(m)?t[m]=r[m]:u.add(m);for(let m of l.removed.values())p.has(m)||(a.updated.has(m)?p.add(m):i.add(m));for(let m of a.updated.values())p.has(m)||(l.updated.has(m)?s.updated.has(m)&&p.add(m):d[m]=o[m]);for(let m of l.updated.values())p.has(m)||(a.updated.has(m)?s.updated.has(m)&&p.add(m):o[m]!==void 0&&(n[m]=r[m]));for(let m of a.added.values())p.has(m)||(l.added.has(m)?s.updated.has(m)&&p.add(m):c[m]=o[m]);for(let m of l.added.values())p.has(m)||(a.added.has(m)?s.updated.has(m)&&p.add(m):t[m]=r[m]);return{local:{added:t,removed:[...i.values()],updated:n},remote:{added:c,removed:[...u.values()],updated:d},conflicts:[...p.values()]}}function cf(o,r){let e=o?Object.keys(o):[],t=r?Object.keys(r):[],n=t.filter(a=>!e.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),i=e.filter(a=>!t.includes(a)).reduce((a,l)=>(a.add(l),a),new Set),s=new Set;for(let a of e){if(i.has(a))continue;let l=o[a],c=r[a];l!==c&&s.add(a)}return{added:n,removed:i,updated:s}}function qx(o,r){let{added:e,removed:t,updated:n}=cf(o,r);return e.size===0&&t.size===0&&n.size===0}function uf(o){return JSON.parse(o.content)}var Ca=class extends mr{constructor(e,t,n,i,s,a,l,c,d,u,p,m){super({syncResource:"snippets",profile:e},t,i,n,s,a,l,u,p,c,d,m);this.version=1;this.snippetsFolder=e.snippetsHome,this._register(this.fileService.watch(n.userRoamingDataHome)),this._register(this.fileService.watch(this.snippetsFolder)),this._register(k.filter(this.fileService.onDidFilesChange,h=>h.affects(this.snippetsFolder))(()=>this.triggerLocalChange()))}async generateSyncPreview(e,t,n){let i=await this.getSnippetsFileContents(),s=this.toSnippetsContents(i),a=e.syncData?this.parseSnippets(e.syncData):null;t=t===null&&n?e:t;let l=t&&t.syncData?this.parseSnippets(t.syncData):null;a?this.logService.trace(`${this.syncResourceLogLabel}: Merging remote snippets with local snippets...`):this.logService.trace(`${this.syncResourceLogLabel}: Remote snippets does not exist. Synchronizing snippets for the first time.`);let c=ov(s,a,l);return this.getResourcePreviews(c,i,a||{},l||{})}async hasRemoteChanged(e){let t=e.syncData?this.parseSnippets(e.syncData):null;if(t===null)return!0;let n=await this.getSnippetsFileContents(),i=this.toSnippetsContents(n),s=ov(i,t,t);return Object.keys(s.remote.added).length>0||Object.keys(s.remote.updated).length>0||s.remote.removed.length>0||s.conflicts.length>0}async getMergeResult(e,t){return e.previewResult}async getAcceptResult(e,t,n,i){if(this.extUri.isEqualOrParent(t,this.syncPreviewFolder.with({scheme:M,authority:"local"})))return{content:e.fileContent?e.fileContent.value.toString():null,localChange:0,remoteChange:e.fileContent?e.remoteContent!==null?2:1:3};if(this.extUri.isEqualOrParent(t,this.syncPreviewFolder.with({scheme:M,authority:"remote"})))return{content:e.remoteContent,localChange:e.remoteContent!==null?e.fileContent?2:1:3,remoteChange:0};if(this.extUri.isEqualOrParent(t,this.syncPreviewFolder))return n===void 0?{content:e.previewResult.content,localChange:e.previewResult.localChange,remoteChange:e.previewResult.remoteChange}:{content:n,localChange:n===null?e.fileContent!==null?3:0:2,remoteChange:n===null?e.remoteContent!==null?3:0:2};throw new Error(`Invalid Resource: ${t.toString()}`)}async applyResult(e,t,n,i){let s=n.map(([a,l])=>({...a,acceptResult:l}));s.every(({localChange:a,remoteChange:l})=>a===0&&l===0)&&this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing snippets.`),s.some(({localChange:a})=>a!==0)&&(await this.updateLocalBackup(s),await this.updateLocalSnippets(s,i)),s.some(({remoteChange:a})=>a!==0)&&(e=await this.updateRemoteSnippets(s,e,i)),t?.ref!==e.ref&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized snippets...`),await this.updateLastSyncUserData(e),this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized snippets`));for(let{previewResource:a}of s)try{await this.fileService.del(a)}catch{}}getResourcePreviews(e,t,n,i){let s=new Map;for(let a of Object.keys(e.local.added)){let l={content:e.local.added[a],hasConflicts:!1,localChange:1,remoteChange:0};s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:null,fileContent:null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),localContent:null,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a],previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of Object.keys(e.local.updated)){let l={content:e.local.updated[a],hasConflicts:!1,localChange:2,remoteChange:0},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a],localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a],previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of e.local.removed){let l={content:null,hasConflicts:!1,localChange:3,remoteChange:0},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a],localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:null,previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of Object.keys(e.remote.added)){let l={content:e.remote.added[a],hasConflicts:!1,localChange:0,remoteChange:1},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a],localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:null,previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of Object.keys(e.remote.updated)){let l={content:e.remote.updated[a],hasConflicts:!1,localChange:0,remoteChange:2},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a],localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a],previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of e.remote.removed){let l={content:null,hasConflicts:!1,localChange:0,remoteChange:3};s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:null,localContent:null,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a],previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of e.conflicts){let l={content:i[a]??null,hasConflicts:!0,localChange:t[a]?2:1,remoteChange:n[a]?2:1},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a]||null,localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a]||null,previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}for(let a of Object.keys(t))if(!s.has(a)){let l={content:t[a]?t[a].value.toString():null,hasConflicts:!1,localChange:0,remoteChange:0},c=t[a]?t[a].value.toString():null;s.set(a,{baseResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"base"}),baseContent:i[a]??null,localResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"local"}),fileContent:t[a]||null,localContent:c,remoteResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"remote"}),remoteContent:n[a]||null,previewResource:this.extUri.joinPath(this.syncPreviewFolder,a),previewResult:l,localChange:l.localChange,remoteChange:l.remoteChange,acceptedResource:this.extUri.joinPath(this.syncPreviewFolder,a).with({scheme:M,authority:"accepted"})})}return[...s.values()]}async resolveContent(e){return this.extUri.isEqualOrParent(e,this.syncPreviewFolder.with({scheme:M,authority:"remote"}))||this.extUri.isEqualOrParent(e,this.syncPreviewFolder.with({scheme:M,authority:"local"}))||this.extUri.isEqualOrParent(e,this.syncPreviewFolder.with({scheme:M,authority:"base"}))||this.extUri.isEqualOrParent(e,this.syncPreviewFolder.with({scheme:M,authority:"accepted"}))?this.resolvePreviewContent(e):null}async hasLocalData(){try{let e=await this.getSnippetsFileContents();if(Object.keys(e).length)return!0}catch{}return!1}async updateLocalBackup(e){let t={};for(let n of e)n.fileContent&&(t[this.extUri.basename(n.localResource)]=n.fileContent);await this.backupLocal(JSON.stringify(this.toSnippetsContents(t)))}async updateLocalSnippets(e,t){for(let{fileContent:n,acceptResult:i,localResource:s,remoteResource:a,localChange:l}of e)if(l!==0){let c=a?this.extUri.basename(a):this.extUri.basename(s),d=this.extUri.joinPath(this.snippetsFolder,c);l===3?(this.logService.trace(`${this.syncResourceLogLabel}: Deleting snippet...`,this.extUri.basename(d)),await this.fileService.del(d),this.logService.info(`${this.syncResourceLogLabel}: Deleted snippet`,this.extUri.basename(d))):l===1?(this.logService.trace(`${this.syncResourceLogLabel}: Creating snippet...`,this.extUri.basename(d)),await this.fileService.createFile(d,U.fromString(i.content),{overwrite:t}),this.logService.info(`${this.syncResourceLogLabel}: Created snippet`,this.extUri.basename(d))):(this.logService.trace(`${this.syncResourceLogLabel}: Updating snippet...`,this.extUri.basename(d)),await this.fileService.writeFile(d,U.fromString(i.content),t?void 0:n),this.logService.info(`${this.syncResourceLogLabel}: Updated snippet`,this.extUri.basename(d)))}}async updateRemoteSnippets(e,t,n){let i=t.syncData?this.parseSnippets(t.syncData):{},s=Ct(i);for(let{acceptResult:a,localResource:l,remoteResource:c,remoteChange:d}of e)if(d!==0){let u=l?this.extUri.basename(l):this.extUri.basename(c);d===3?delete s[u]:s[u]=a.content}return qx(i,s)||(this.logService.trace(`${this.syncResourceLogLabel}: Updating remote snippets...`),t=await this.updateRemoteUserData(JSON.stringify(s),n?null:t.ref),this.logService.info(`${this.syncResourceLogLabel}: Updated remote snippets`)),t}parseSnippets(e){return uf(e)}toSnippetsContents(e){let t={};for(let n of Object.keys(e))t[n]=e[n].value.toString();return t}async getSnippetsFileContents(){let e={},t;try{t=await this.fileService.resolve(this.snippetsFolder)}catch(n){if(n instanceof et&&n.fileOperationResult===1)return e;throw n}for(let n of t.children||[]){let i=n.resource,s=this.extUri.extname(i);if(s===".json"||s===".code-snippets"){let a=this.extUri.relativePath(this.snippetsFolder,i),l=await this.fileService.readFile(i);e[a]=l}}return e}};Ca=b([g(2,X),g(3,W),g(4,K),g(5,Ce),g(6,Qe),g(7,me),g(8,Q),g(9,Oe),g(10,de),g(11,te)],Ca);var df=class extends ir{constructor(r,e,t,n,i,s){super("snippets",e,t,n,r,i,s)}async doInitialize(r){let e=r.syncData?JSON.parse(r.syncData.content):null;if(!e){this.logService.info("Skipping initializing snippets because remote snippets does not exist.");return}if(!await this.isEmpty()){this.logService.info("Skipping initializing snippets because local snippets exist.");return}for(let n of Object.keys(e)){let i=e[n];if(i){let s=this.extUri.joinPath(this.userDataProfilesService.defaultProfile.snippetsHome,n);await this.fileService.createFile(s,U.fromString(i)),this.logService.info("Created snippet",this.extUri.basename(s))}}await this.updateLastSyncUserData(r)}async isEmpty(){try{return!(await this.fileService.resolve(this.userDataProfilesService.defaultProfile.snippetsHome)).children?.length}catch(r){return r.fileOperationResult===1}}};df=b([g(0,W),g(1,fe),g(2,X),g(3,me),g(4,K),g(5,te)],df);var ki=class extends xo{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h,v){super(e,t,n,s,a,l,c,d,u,p,m,h,v);this.version=1;this.previewResource=this.extUri.joinPath(this.syncPreviewFolder,i),this.baseResource=this.previewResource.with({scheme:M,authority:"base"}),this.localResource=this.previewResource.with({scheme:M,authority:"local"}),this.remoteResource=this.previewResource.with({scheme:M,authority:"remote"}),this.acceptedResource=this.previewResource.with({scheme:M,authority:"accepted"})}async generateSyncPreview(e,t,n,i){let s=e.syncData?this.getContentFromSyncContent(e.syncData.content):null;t=t===null&&n?e:t;let a=t?.syncData?this.getContentFromSyncContent(t.syncData.content):null,l=await this.getLocalFileContent(),c=null,d=!1,u=!1,p=!1;if(e.syncData){let v=l?l.value.toString():null;if(!a||a!==v||a!==s){this.logService.trace(`${this.syncResourceLogLabel}: Merging remote ${this.syncResource.syncResource} with local ${this.syncResource.syncResource}...`);let y=this.merge(v,s,a);c=y.content,p=y.hasConflicts,d=y.hasLocalChanged,u=y.hasRemoteChanged}}else l&&(this.logService.trace(`${this.syncResourceLogLabel}: Remote ${this.syncResource.syncResource} does not exist. Synchronizing ${this.syncResource.syncResource} for the first time.`),c=l.value.toString(),u=!0);let m={content:p?a:c,localChange:d?l?2:1:0,remoteChange:u?2:0,hasConflicts:p},h=l?l.value.toString():null;return[{fileContent:l,baseResource:this.baseResource,baseContent:a,localResource:this.localResource,localContent:h,localChange:m.localChange,remoteResource:this.remoteResource,remoteContent:s,remoteChange:m.remoteChange,previewResource:this.previewResource,previewResult:m,acceptedResource:this.acceptedResource}]}async hasRemoteChanged(e){let t=e?.syncData?this.getContentFromSyncContent(e.syncData.content):null;if(t===null)return!0;let n=await this.getLocalFileContent(),i=n?n.value.toString():null,s=this.merge(i,t,t);return s.hasLocalChanged||s.hasRemoteChanged}async getMergeResult(e,t){return e.previewResult}async getAcceptResult(e,t,n,i){if(this.extUri.isEqual(t,this.localResource))return{content:e.fileContent?e.fileContent.value.toString():null,localChange:0,remoteChange:2};if(this.extUri.isEqual(t,this.remoteResource))return{content:e.remoteContent,localChange:2,remoteChange:0};if(this.extUri.isEqual(t,this.previewResource))return n===void 0?{content:e.previewResult.content,localChange:e.previewResult.localChange,remoteChange:e.previewResult.remoteChange}:{content:n,localChange:2,remoteChange:2};throw new Error(`Invalid Resource: ${t.toString()}`)}async applyResult(e,t,n,i){let{fileContent:s}=n[0][0],{content:a,localChange:l,remoteChange:c}=n[0][1];if(l===0&&c===0&&this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing ${this.syncResource.syncResource}.`),l!==0&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating local ${this.syncResource.syncResource}...`),s&&await this.backupLocal(JSON.stringify(this.toSyncContent(s.value.toString()))),a?await this.updateLocalFileContent(a,s,i):await this.deleteLocalFile(),this.logService.info(`${this.syncResourceLogLabel}: Updated local ${this.syncResource.syncResource}`)),c!==0){this.logService.trace(`${this.syncResourceLogLabel}: Updating remote ${this.syncResource.syncResource}...`);let d=JSON.stringify(this.toSyncContent(a));e=await this.updateRemoteUserData(d,i?null:e.ref),this.logService.info(`${this.syncResourceLogLabel}: Updated remote ${this.syncResource.syncResource}`)}try{await this.fileService.del(this.previewResource)}catch{}t?.ref!==e.ref&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized ${this.syncResource.syncResource}...`),await this.updateLastSyncUserData(e),this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized ${this.syncResource.syncResource}`))}async hasLocalData(){return this.fileService.exists(this.file)}async resolveContent(e){return this.extUri.isEqual(this.remoteResource,e)||this.extUri.isEqual(this.baseResource,e)||this.extUri.isEqual(this.localResource,e)||this.extUri.isEqual(this.acceptedResource,e)?this.resolvePreviewContent(e):null}merge(e,t,n){if(e===null&&t===null&&n===null)return{content:null,hasLocalChanged:!1,hasRemoteChanged:!1,hasConflicts:!1};if(t=t??"",e=e??"",n=n??"",e===t)return{content:null,hasLocalChanged:!1,hasRemoteChanged:!1,hasConflicts:!1};let i=n!==e,s=n!==t;return!i&&!s?{content:null,hasLocalChanged:!1,hasRemoteChanged:!1,hasConflicts:!1}:i&&!s?{content:e,hasRemoteChanged:!0,hasLocalChanged:!1,hasConflicts:!1}:s&&!i?{content:t,hasLocalChanged:!0,hasRemoteChanged:!1,hasConflicts:!1}:{content:e,hasLocalChanged:!0,hasRemoteChanged:!0,hasConflicts:!0}}};ki=b([g(4,W),g(5,X),g(6,K),g(7,Ce),g(8,Qe),g(9,Oe),g(10,de),g(11,me),g(12,Q),g(13,te)],ki);function ff(o,r){try{return JSON.parse(o).tasks??null}catch(e){return r.error(e),null}}var Da=class extends ki{constructor(r,e,t,n,i,s,a,l,c,d,u,p){super(r.tasksResource,{syncResource:"tasks",profile:r},e,"tasks.json",l,c,d,t,n,a,u,i,s,p)}getContentFromSyncContent(r){return ff(r,this.logService)}toSyncContent(r){return r?{tasks:r}:{}}};Da=b([g(2,Ce),g(3,Qe),g(4,me),g(5,Q),g(6,Oe),g(7,W),g(8,X),g(9,K),g(10,de),g(11,te)],Da);var pf=class extends ir{constructor(e,t,n,i,s,a){super("tasks",t,n,i,e,s,a);this.tasksResource=this.userDataProfilesService.defaultProfile.tasksResource}async doInitialize(e){let t=e.syncData?ff(e.syncData.content,this.logService):null;if(!t){this.logService.info("Skipping initializing tasks because remote tasks does not exist.");return}if(!await this.isEmpty()){this.logService.info("Skipping initializing tasks because local tasks exist.");return}await this.fileService.writeFile(this.tasksResource,U.fromString(t)),await this.updateLastSyncUserData(e)}async isEmpty(){return this.fileService.exists(this.tasksResource)}};pf=b([g(0,W),g(1,fe),g(2,X),g(3,me),g(4,K),g(5,te)],pf);function sv(o,r){try{return JSON.parse(o).mcp??null}catch(e){return r.error(e),null}}var _a=class extends ki{constructor(r,e,t,n,i,s,a,l,c,d,u,p){super(r.mcpResource,{syncResource:"mcp",profile:r},e,"mcp.json",l,c,d,t,n,a,u,i,s,p)}getContentFromSyncContent(r){return sv(r,this.logService)}toSyncContent(r){return r?{mcp:r}:{}}};_a=b([g(2,Ce),g(3,Qe),g(4,me),g(5,Q),g(6,Oe),g(7,W),g(8,X),g(9,K),g(10,de),g(11,te)],_a);function Mc(o,r,e,t){let n={added:[],removed:[],updated:[]},i={added:[],removed:[],updated:[]};if(!r){let a=o.filter(({id:l})=>!t.includes(l));return a.length?i.added=a:i=null,{local:n,remote:i}}let s=av(o,r,t);if(s.added.length>0||s.removed.length>0||s.updated.length>0){let a=av(e,o,t),l=av(e,r,t);for(let c of l.removed){let d=o.find(u=>u.id===c);d&&n.removed.push(d)}for(let c of l.added){let d=r.find(u=>u.id===c);a.added.includes(c)?s.updated.includes(c)&&n.updated.push(d):n.added.push(d)}for(let c of l.updated)n.updated.push(r.find(d=>d.id===c));for(let c of a.added)l.added.includes(c)||i.added.push(o.find(d=>d.id===c));for(let c of a.updated)l.removed.includes(c)||l.updated.includes(c)||i.updated.push(o.find(d=>d.id===c));for(let c of a.removed){let d=r.find(u=>u.id===c);d&&i.removed.push(d)}}return i.added.length===0&&i.removed.length===0&&i.updated.length===0&&(i=null),{local:n,remote:i}}function av(o,r,e){o=o?o.filter(({id:l})=>!e.includes(l)):[],r=r.filter(({id:l})=>!e.includes(l));let t=o.map(({id:l})=>l),n=r.map(({id:l})=>l),i=n.filter(l=>!t.includes(l)),s=t.filter(l=>!n.includes(l)),a=[];for(let{id:l,name:c,icon:d,useDefaultFlags:u}of o){if(s.includes(l))continue;let p=r.find(m=>m.id===l);(!p||p.name!==c||p.icon!==d||!it(p.useDefaultFlags,u))&&a.push(l)}return{added:i,removed:s,updated:a}}var Li=class extends mr{constructor(e,t,n,i,s,a,l,c,d,u,p,m,h){super({syncResource:"profiles",profile:e},t,i,s,a,l,c,p,m,d,u,h);this.userDataProfilesService=n;this.version=2;this.previewResource=this.extUri.joinPath(this.syncPreviewFolder,"profiles.json");this.baseResource=this.previewResource.with({scheme:M,authority:"base"});this.localResource=this.previewResource.with({scheme:M,authority:"local"});this.remoteResource=this.previewResource.with({scheme:M,authority:"remote"});this.acceptedResource=this.previewResource.with({scheme:M,authority:"accepted"});this._register(n.onDidChangeProfiles(()=>this.triggerLocalChange()))}async getLastSyncedProfiles(){let e=await this.getLastSyncUserData();return e?.syncData?Ui(e.syncData):null}async getRemoteSyncedProfiles(e){let t=await this.getLastSyncUserData(),n=await this.getLatestRemoteUserData(e,t);return n?.syncData?Ui(n.syncData):null}async generateSyncPreview(e,t,n){let i=e.syncData?Ui(e.syncData):null,s=t?.syncData?Ui(t.syncData):null,a=this.getLocalUserDataProfiles(),{local:l,remote:c}=Mc(a,i,s,[]),d={local:l,remote:c,content:s?this.stringifyRemoteProfiles(s):null,localChange:l.added.length>0||l.removed.length>0||l.updated.length>0?2:0,remoteChange:c!==null?2:0},u=mf(a,!1);return[{baseResource:this.baseResource,baseContent:s?this.stringifyRemoteProfiles(s):null,localResource:this.localResource,localContent:u,remoteResource:this.remoteResource,remoteContent:i?this.stringifyRemoteProfiles(i):null,remoteProfiles:i,previewResource:this.previewResource,previewResult:d,localChange:d.localChange,remoteChange:d.remoteChange,acceptedResource:this.acceptedResource}]}async hasRemoteChanged(e){let t=e?.syncData?Ui(e.syncData):null,n=this.getLocalUserDataProfiles(),{remote:i}=Mc(n,t,t,[]);return!!i?.added.length||!!i?.removed.length||!!i?.updated.length}async getMergeResult(e,t){return{...e.previewResult,hasConflicts:!1}}async getAcceptResult(e,t,n,i){if(this.extUri.isEqual(t,this.localResource))return this.acceptLocal(e);if(this.extUri.isEqual(t,this.remoteResource))return this.acceptRemote(e);if(this.extUri.isEqual(t,this.previewResource))return e.previewResult;throw new Error(`Invalid Resource: ${t.toString()}`)}async acceptLocal(e){let t=this.getLocalUserDataProfiles(),n=Mc(t,null,null,[]),{local:i,remote:s}=n;return{content:e.localContent,local:i,remote:s,localChange:i.added.length>0||i.removed.length>0||i.updated.length>0?2:0,remoteChange:s!==null?2:0}}async acceptRemote(e){let t=e.remoteContent?JSON.parse(e.remoteContent):null,n=[],i=[];for(let s of this.getLocalUserDataProfiles()){let a=t?.find(l=>l.id===s.id);a&&(n.push({id:s.id,name:s.name,collection:a.collection}),i.push(s))}if(t!==null){let s=Mc(i,t,n,[]),{local:a,remote:l}=s;return{content:e.remoteContent,local:a,remote:l,localChange:a.added.length>0||a.removed.length>0||a.updated.length>0?2:0,remoteChange:l!==null?2:0}}else return{content:e.remoteContent,local:{added:[],removed:[],updated:[]},remote:null,localChange:0,remoteChange:0}}async applyResult(e,t,n,i){let{local:s,remote:a,localChange:l,remoteChange:c}=n[0][1];l===0&&c===0&&this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing profiles.`);let d=n[0][0].remoteProfiles||[];if(d.length+(a?.added.length??0)-(a?.removed.length??0)>20)throw new xe("Too many profiles to sync. Please remove some profiles and try again.","LocalTooManyProfiles");if(l!==0&&(await this.backupLocal(mf(this.getLocalUserDataProfiles(),!1)),await Promise.all(s.removed.map(async u=>{this.logService.trace(`${this.syncResourceLogLabel}: Removing '${u.name}' profile...`),await this.userDataProfilesService.removeProfile(u),this.logService.info(`${this.syncResourceLogLabel}: Removed profile '${u.name}'.`)})),await Promise.all(s.added.map(async u=>{this.logService.trace(`${this.syncResourceLogLabel}: Creating '${u.name}' profile...`),await this.userDataProfilesService.createProfile(u.id,u.name,{icon:u.icon,useDefaultFlags:u.useDefaultFlags}),this.logService.info(`${this.syncResourceLogLabel}: Created profile '${u.name}'.`)})),await Promise.all(s.updated.map(async u=>{let p=this.userDataProfilesService.profiles.find(m=>m.id===u.id);p?(this.logService.trace(`${this.syncResourceLogLabel}: Updating '${u.name}' profile...`),await this.userDataProfilesService.updateProfile(p,{name:u.name,icon:u.icon,useDefaultFlags:u.useDefaultFlags}),this.logService.info(`${this.syncResourceLogLabel}: Updated profile '${u.name}'.`)):this.logService.info(`${this.syncResourceLogLabel}: Could not find profile with id '${u.id}' to update.`)}))),c!==0){this.logService.trace(`${this.syncResourceLogLabel}: Updating remote profiles...`);let u=[],p=d.length+(a?.added.length??0)<=20;if(p)for(let m of a?.added||[]){let h=await this.userDataSyncStoreService.createCollection(this.syncHeaders);this.logService.trace(`${this.syncResourceLogLabel}: Created collection "${h}" for "${m.name}".`),u.push(h),d.push({id:m.id,name:m.name,collection:h,icon:m.icon,useDefaultFlags:m.useDefaultFlags})}else this.logService.info(`${this.syncResourceLogLabel}: Could not create remote profiles as there are too many profiles.`);for(let m of a?.removed||[])d.splice(d.findIndex(({id:h})=>m.id===h),1);for(let m of a?.updated||[]){let h=d.find(({id:v})=>m.id===v);h&&d.splice(d.indexOf(h),1,{...h,id:m.id,name:m.name,icon:m.icon,useDefaultFlags:m.useDefaultFlags})}try{e=await this.updateRemoteProfiles(d,i?null:e.ref),this.logService.info(`${this.syncResourceLogLabel}: Updated remote profiles.${p&&a?.added.length?` Added: ${JSON.stringify(a.added.map(m=>m.name))}.`:""}${a?.updated.length?` Updated: ${JSON.stringify(a.updated.map(m=>m.name))}.`:""}${a?.removed.length?` Removed: ${JSON.stringify(a.removed.map(m=>m.name))}.`:""}`)}catch(m){if(u.length){this.logService.info(`${this.syncResourceLogLabel}: Failed to update remote profiles. Cleaning up added collections...`);for(let h of u)await this.userDataSyncStoreService.deleteCollection(h,this.syncHeaders)}throw m}for(let m of a?.removed||[])await this.userDataSyncStoreService.deleteCollection(m.collection,this.syncHeaders)}t?.ref!==e.ref&&(this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized profiles...`),await this.updateLastSyncUserData(e),this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized profiles.`))}async updateRemoteProfiles(e,t){return this.updateRemoteUserData(this.stringifyRemoteProfiles(e),t)}async hasLocalData(){return this.getLocalUserDataProfiles().length>0}async resolveContent(e){if(this.extUri.isEqual(this.remoteResource,e)||this.extUri.isEqual(this.baseResource,e)||this.extUri.isEqual(this.localResource,e)||this.extUri.isEqual(this.acceptedResource,e)){let t=await this.resolvePreviewContent(e);return t&&zn(JSON.parse(t),{})}return null}getLocalUserDataProfiles(){return this.userDataProfilesService.profiles.filter(e=>!e.isDefault&&!e.isTransient)}stringifyRemoteProfiles(e){return JSON.stringify([...e].sort((t,n)=>t.name.localeCompare(n.name)))}};Li=b([g(2,fe),g(3,W),g(4,X),g(5,K),g(6,Ce),g(7,Qe),g(8,me),g(9,Q),g(10,Oe),g(11,de),g(12,te)],Li);function mf(o,r){let e=[...o].sort((t,n)=>t.name.localeCompare(n.name)).map(t=>({id:t.id,name:t.name}));return r?zn(e,{}):JSON.stringify(e)}function Ui(o){return JSON.parse(o.content)}var lv="sync.lastSyncTime",ka=class extends T{constructor(e,t,n,i,s,a,l,c,d,u,p){super();this.fileService=e;this.userDataSyncStoreService=t;this.userDataSyncStoreManagementService=n;this.instantiationService=i;this.logService=s;this.telemetryService=a;this.storageService=l;this.userDataSyncEnablementService=c;this.userDataProfilesService=d;this.userDataSyncResourceProviderService=u;this.userDataSyncLocalStoreService=p;this._status="uninitialized";this._onDidChangeStatus=this._register(new w);this.onDidChangeStatus=this._onDidChangeStatus.event;this._onDidChangeLocal=this._register(new w);this.onDidChangeLocal=this._onDidChangeLocal.event;this._conflicts=[];this._onDidChangeConflicts=this._register(new w);this.onDidChangeConflicts=this._onDidChangeConflicts.event;this._syncErrors=[];this._onSyncErrors=this._register(new w);this.onSyncErrors=this._onSyncErrors.event;this._lastSyncTime=void 0;this._onDidChangeLastSyncTime=this._register(new w);this.onDidChangeLastSyncTime=this._onDidChangeLastSyncTime.event;this._onDidResetLocal=this._register(new w);this.onDidResetLocal=this._onDidResetLocal.event;this._onDidResetRemote=this._register(new w);this.onDidResetRemote=this._onDidResetRemote.event;this.activeProfileSynchronizers=new Map;this._status=n.userDataSyncStore?"idle":"uninitialized",this._lastSyncTime=this.storageService.getNumber(lv,-1,void 0),this._register(oe(()=>this.clearActiveProfileSynchronizers())),this._register(new It(()=>this.cleanUpStaleStorageData(),5*1e3)).schedule()}get status(){return this._status}get conflicts(){return this._conflicts}get lastSyncTime(){return this._lastSyncTime}async createSyncTask(e,t){this.checkEnablement(),this.logService.info("Sync started.");let n=new Date().getTime(),i=Le();try{let c=Pi(i);t&&(c["Cache-Control"]="no-cache"),e=await this.userDataSyncStoreService.manifest(e,c)}catch(c){let d=xe.toUserDataSyncError(c);throw gf(d,i,this.userDataSyncStoreManagementService,this.telemetryService),d}let s=!1,a=this,l;return{manifest:e,async run(){if(s)throw new Error("Can run a task only once");l=Je(c=>a.sync(e,!1,i,c)),await l.finally(()=>l=void 0),a.logService.info(`Sync done. Took ${new Date().getTime()-n}ms`),a.updateLastSyncTime()},stop(){return l?.cancel(),a.stop()}}}async createManualSyncTask(){if(this.checkEnablement(),this.userDataSyncEnablementService.isEnabled())throw new xe("Cannot start manual sync when sync is enabled","LocalError");this.logService.info("Sync started.");let e=new Date().getTime(),t=Le(),n=Pi(t),i;try{i=await this.userDataSyncStoreService.getLatestData(n)}catch(l){let c=xe.toUserDataSyncError(l);this.telemetryService.publicLog2("sync.download.latest",{code:c.code,serverCode:c instanceof Ae?String(c.serverCode):void 0,url:c instanceof Ae?c.url:void 0,resource:c.resource,executionId:t,service:this.userDataSyncStoreManagementService.userDataSyncStore.url.toString()});try{i=await this.userDataSyncStoreService.manifest(null,n)}catch(d){let u=xe.toUserDataSyncError(d);throw gf(u,t,this.userDataSyncStoreManagementService,this.telemetryService),u}}await this.resetLocal();let s=this,a=new mt;return{id:t,async merge(){return s.sync(i,!0,t,a.token)},async apply(){try{try{await s.applyManualSync(i,t,a.token)}catch(l){if(xe.toUserDataSyncError(l).code==="MethodNotFound")s.logService.info("Client is making invalid requests. Cleaning up data..."),await s.cleanUpRemoteData(),s.logService.info("Applying manual sync again..."),await s.applyManualSync(i,t,a.token);else throw l}}catch(l){throw s.logService.error(l),l}s.logService.info(`Sync done. Took ${new Date().getTime()-e}ms`),s.updateLastSyncTime()},async stop(){a.cancel(),await s.stop(),await s.resetLocal()}}}async sync(e,t,n,i){this._syncErrors=[];try{this.status!=="hasConflicts"&&this.setStatus("syncing");let s=this.getOrCreateActiveProfileSynchronizer(this.userDataProfilesService.defaultProfile,void 0);this._syncErrors.push(...await this.syncProfile(s,e,t,n,i));let a=s.enabled.find(l=>l.resource==="profiles");if(a){let l=await a.getLastSyncedProfiles()||[];if(i.isCancellationRequested)return;await this.syncRemoteProfiles(l,e,t,n,i)}}finally{this.status!=="hasConflicts"&&this.setStatus("idle"),this._onSyncErrors.fire(this._syncErrors)}}async syncRemoteProfiles(e,t,n,i,s){for(let a of e){if(s.isCancellationRequested)return;let l=this.userDataProfilesService.profiles.find(d=>d.id===a.id);if(!l){this.logService.error(`Profile with id:${a.id} and name: ${a.name} does not exist locally to sync.`);continue}this.logService.info("Syncing profile.",a.name);let c=this.getOrCreateActiveProfileSynchronizer(l,a);this._syncErrors.push(...await this.syncProfile(c,t,n,i,s))}for(let[a,l]of this.activeProfileSynchronizers.entries())this.userDataProfilesService.profiles.some(c=>c.id===l[0].profile.id)||(await l[0].resetLocal(),l[1].dispose(),this.activeProfileSynchronizers.delete(a))}async applyManualSync(e,t,n){try{this.setStatus("syncing");let i=this.getActiveProfileSynchronizers();for(let d of i){if(n.isCancellationRequested)return;await d.apply(t,n)}let s=i.find(d=>d.profile.isDefault);if(!s)return;let a=s.enabled.find(d=>d.resource==="profiles");if(!a)return;let c=(await a.getRemoteSyncedProfiles(cv(e,void 0,"profiles")??null)||[]).filter(d=>i.every(u=>u.profile.id!==d.id));c.length&&await this.syncRemoteProfiles(c,e,!1,t,n)}finally{this.setStatus("idle")}}async syncProfile(e,t,n,i,s){return(await e.sync(t,n,i,s)).map(([l,c])=>({profile:e.profile,syncResource:l,error:c}))}async stop(){this.status!=="idle"&&await Promise.allSettled(this.getActiveProfileSynchronizers().map(e=>e.stop()))}async resolveContent(e){let t=await this.userDataSyncResourceProviderService.resolveContent(e);if(t)return t;for(let n of this.getActiveProfileSynchronizers())for(let i of n.enabled){let s=await i.resolveContent(e);if(s)return s}return null}async replace(e){this.checkEnablement();let t=this.userDataSyncResourceProviderService.resolveUserDataSyncResource(e);if(!t)return;let n=await this.resolveContent(e.uri);n&&await this.performAction(t.profile,async i=>{if(t.syncResource===i.resource)return await i.replace(n),!0})}async accept(e,t,n,i){this.checkEnablement(),await this.performAction(e.profile,async s=>{if(e.syncResource===s.resource)return await s.accept(t,n),i&&await s.apply(Bt(i)?!1:i.force,Pi(Le())),!0})}async hasLocalData(){return!!await this.performAction(this.userDataProfilesService.defaultProfile,async t=>{if(t.resource!=="globalState"&&await t.hasLocalData())return!0})}async hasPreviouslySynced(){return!!await this.performAction(this.userDataProfilesService.defaultProfile,async t=>{if(await t.hasPreviouslySynced())return!0})}async reset(){this.checkEnablement(),await this.resetRemote(),await this.resetLocal()}async resetRemote(){this.checkEnablement();try{await this.userDataSyncStoreService.clear(),this.logService.info("Cleared data on server")}catch(e){this.logService.error(e)}this._onDidResetRemote.fire()}async resetLocal(){this.checkEnablement(),this._lastSyncTime=void 0,this.storageService.remove(lv,-1);for(let[e]of this.activeProfileSynchronizers.values())try{await e.resetLocal()}catch(t){this.logService.error(t)}this.clearActiveProfileSynchronizers(),this._onDidResetLocal.fire(),this.logService.info("Did reset the local sync state.")}async cleanUpStaleStorageData(){let e=this.storageService.keys(-1,1),t=[];for(let i of e){if(!i.endsWith(".lastSyncUserData"))continue;let s=i.split(".");s.length===3&&t.push([i,s[0]])}if(!t.length)return;let n=new se;try{let i=this.activeProfileSynchronizers.get(this.userDataProfilesService.defaultProfile.id)?.[0];i||(i=n.add(this.instantiationService.createInstance(Mi,this.userDataProfilesService.defaultProfile,void 0)));let s=i.enabled.find(c=>c.resource==="profiles");if(!s)return;let l=(await s.getLastSyncedProfiles())?.map(c=>c.collection)??[];for(let[c,d]of t)l.includes(d)||(this.logService.info(`Removing last sync state for stale profile: ${d}`),this.storageService.remove(c,-1))}finally{n.dispose()}}async cleanUpRemoteData(){let e=await this.userDataSyncResourceProviderService.getRemoteSyncedProfiles(),t=e.map(a=>a.collection),n=await this.userDataSyncStoreService.getAllCollections(),i=n.filter(a=>!t.includes(a));i.length&&(this.logService.info(`Deleting ${i.length} redundant collections on server`),await Promise.allSettled(i.map(a=>this.userDataSyncStoreService.deleteCollection(a))),this.logService.info("Deleted redundant collections on server"));let s=e.filter(a=>n.includes(a.collection));if(s.length!==e.length){let a=this.instantiationService.createInstance(Li,this.userDataProfilesService.defaultProfile,void 0);try{this.logService.info("Resetting the last synced state of profiles"),await a.resetLocal(),this.logService.info("Did reset the last synced state of profiles"),this.logService.info("Updating remote profiles with invalid collections on server"),await a.updateRemoteProfiles(s,null),this.logService.info("Updated remote profiles on server")}finally{a.dispose()}}}async saveRemoteActivityData(e){this.checkEnablement();let t=await this.userDataSyncStoreService.getActivityData();await this.fileService.writeFile(e,t)}async extractActivityData(e,t){let n=(await this.fileService.readFile(e)).value.toString(),i=JSON.parse(n);if(i.resources)for(let s in i.resources)for(let a of i.resources[s])await this.userDataSyncLocalStoreService.writeResource(s,a.content,new Date(a.created*1e3),void 0,t);if(i.collections)for(let s in i.collections)for(let a in i.collections[s].resources)for(let l of i.collections[s].resources?.[a]??[])await this.userDataSyncLocalStoreService.writeResource(a,l.content,new Date(l.created*1e3),s,t)}async performAction(e,t){let n=new se;try{let i=this.activeProfileSynchronizers.get(e.id);if(i){let d=await this.performActionWithProfileSynchronizer(i[0],t,n);return st(d)?null:d}if(e.isDefault){let d=n.add(this.instantiationService.createInstance(Mi,e,void 0)),u=await this.performActionWithProfileSynchronizer(d,t,n);return st(u)?null:u}let s=n.add(this.instantiationService.createInstance(Li,e,void 0)),a=await this.userDataSyncStoreService.manifest(null),c=(await s.getRemoteSyncedProfiles(a?.latest?.profiles??null)||[]).find(d=>d.id===e.id);if(c){let d=n.add(this.instantiationService.createInstance(Mi,e,c.collection)),u=await this.performActionWithProfileSynchronizer(d,t,n);return st(u)?null:u}return null}finally{n.dispose()}}async performActionWithProfileSynchronizer(e,t,n){let i=[...e.enabled,...e.disabled.reduce((s,a)=>(a!=="workspaceState"&&s.push(n.add(e.createSynchronizer(a))),s),[])];for(let s of i){let a=await t(s);if(!st(a))return a}}setStatus(e){let t=this._status;this._status!==e&&(this._status=e,this._onDidChangeStatus.fire(e),t==="hasConflicts"&&this.updateLastSyncTime())}updateConflicts(){let e=this.getActiveProfileSynchronizers().map(t=>t.conflicts).flat();Pt(this._conflicts,e,(t,n)=>t.profile.id===n.profile.id&&t.syncResource===n.syncResource&&Pt(t.conflicts,n.conflicts,(i,s)=>_r(i.previewResource,s.previewResource)))||(this._conflicts=e,this._onDidChangeConflicts.fire(e))}updateLastSyncTime(){this.status==="idle"&&(this._lastSyncTime=new Date().getTime(),this.storageService.store(lv,this._lastSyncTime,-1,1),this._onDidChangeLastSyncTime.fire(this._lastSyncTime))}getOrCreateActiveProfileSynchronizer(e,t){let n=this.activeProfileSynchronizers.get(e.id);if(n&&n[0].collection!==t?.collection&&(this.logService.error("Profile synchronizer collection does not match with the remote sync profile collection"),n[1].dispose(),n=void 0,this.activeProfileSynchronizers.delete(e.id)),!n){let i=new se,s=i.add(this.instantiationService.createInstance(Mi,e,t?.collection));i.add(s.onDidChangeStatus(a=>this.setStatus(a))),i.add(s.onDidChangeConflicts(a=>this.updateConflicts())),i.add(s.onDidChangeLocal(a=>this._onDidChangeLocal.fire(a))),this.activeProfileSynchronizers.set(e.id,n=[s,i])}return n[0]}getActiveProfileSynchronizers(){let e=[];for(let[t]of this.activeProfileSynchronizers.values())e.push(t);return e}clearActiveProfileSynchronizers(){this.activeProfileSynchronizers.forEach(([,e])=>e.dispose()),this.activeProfileSynchronizers.clear()}checkEnablement(){if(!this.userDataSyncStoreManagementService.userDataSyncStore)throw new Error("Not enabled")}};ka=b([g(0,W),g(1,Ce),g(2,Pr),g(3,bt),g(4,me),g(5,de),g(6,K),g(7,Oe),g(8,fe),g(9,Pc),g(10,Qe)],ka);var Mi=class extends T{constructor(e,t,n,i,s,a,l,c,d){super();this.profile=e;this.collection=t;this.userDataSyncEnablementService=n;this.instantiationService=i;this.extensionGalleryService=s;this.userDataSyncStoreManagementService=a;this.telemetryService=l;this.logService=c;this.configurationService=d;this._enabled=[];this._status="idle";this._onDidChangeStatus=this._register(new w);this.onDidChangeStatus=this._onDidChangeStatus.event;this._onDidChangeLocal=this._register(new w);this.onDidChangeLocal=this._onDidChangeLocal.event;this._conflicts=[];this._onDidChangeConflicts=this._register(new w);this.onDidChangeConflicts=this._onDidChangeConflicts.event;this._register(n.onDidChangeResourceEnablement(([u,p])=>this.onDidChangeResourceEnablement(u,p))),this._register(oe(()=>this._enabled.splice(0,this._enabled.length).forEach(([,,u])=>u.dispose())));for(let u of Dn)n.isResourceEnabled(u)&&this.registerSynchronizer(u)}get enabled(){return this._enabled.sort((e,t)=>e[1]-t[1]).map(([e])=>e)}get disabled(){return Dn.filter(e=>!this.userDataSyncEnablementService.isResourceEnabled(e))}get status(){return this._status}get conflicts(){return this._conflicts}onDidChangeResourceEnablement(e,t){t?this.registerSynchronizer(e):this.deRegisterSynchronizer(e)}registerSynchronizer(e){if(this._enabled.some(([s])=>s.resource===e))return;if(e==="extensions"&&!this.extensionGalleryService.isEnabled()){this.logService.info("Skipping extensions sync because gallery is not configured");return}if(e==="profiles"&&!this.profile.isDefault||e==="workspaceState")return;if(e!=="profiles"&&this.profile.useDefaultFlags?.[e]){this.logService.debug(`Skipping syncing ${e} in ${this.profile.name} because it is already synced by default profile`);return}let t=new se,n=t.add(this.createSynchronizer(e));t.add(n.onDidChangeStatus(()=>this.updateStatus())),t.add(n.onDidChangeConflicts(()=>this.updateConflicts())),t.add(n.onDidChangeLocal(()=>this._onDidChangeLocal.fire(e)));let i=this.getOrder(e);this._enabled.push([n,i,t])}deRegisterSynchronizer(e){let t=this._enabled.findIndex(([n])=>n.resource===e);if(t!==-1){let[[n,,i]]=this._enabled.splice(t,1);i.dispose(),this.updateStatus(),n.stop().then(null,s=>this.logService.error(s))}}createSynchronizer(e){switch(e){case"settings":return this.instantiationService.createInstance(To,this.profile,this.collection);case"keybindings":return this.instantiationService.createInstance(wa,this.profile,this.collection);case"snippets":return this.instantiationService.createInstance(Ca,this.profile,this.collection);case"prompts":return this.instantiationService.createInstance(Pa,this.profile,this.collection);case"tasks":return this.instantiationService.createInstance(Da,this.profile,this.collection);case"mcp":return this.instantiationService.createInstance(_a,this.profile,this.collection);case"globalState":return this.instantiationService.createInstance(Ea,this.profile,this.collection);case"extensions":return this.instantiationService.createInstance(xa,this.profile,this.collection);case"profiles":return this.instantiationService.createInstance(Li,this.profile,this.collection)}}async sync(e,t,n,i){if(i.isCancellationRequested)return[];let s=this.enabled;if(!s.length)return[];try{let a=[],l=Pi(n),c=t?await this.getUserDataSyncConfiguration(e):this.getLocalUserDataSyncConfiguration();for(let d of s){if(i.isCancellationRequested)return[];if(!this.userDataSyncEnablementService.isResourceEnabled(d.resource))return[];try{let u=cv(e,this.collection,d.resource)??null;await d.sync(u,t,c,l)}catch(u){let p=xe.toUserDataSyncError(u);if(gf(p,n,this.userDataSyncStoreManagementService,this.telemetryService),zx(u))throw p;this.logService.error(u),this.logService.error(`${d.resource}: ${_t(u)}`),a.push([d.resource,p])}}return a}finally{this.updateStatus()}}async apply(e,t){let n=Pi(e);for(let i of this.enabled){if(t.isCancellationRequested)return;try{await i.apply(!1,n)}catch(s){let a=xe.toUserDataSyncError(s);if(gf(a,e,this.userDataSyncStoreManagementService,this.telemetryService),zx(s))throw a;this.logService.error(s),this.logService.error(`${i.resource}: ${_t(s)}`)}}}async stop(){for(let e of this.enabled)try{e.status!=="idle"&&await e.stop()}catch(t){this.logService.error(t)}}async resetLocal(){for(let e of this.enabled)try{await e.resetLocal()}catch(t){this.logService.error(`${e.resource}: ${_t(t)}`),this.logService.error(t)}}async getUserDataSyncConfiguration(e){if(!this.profile.isDefault)return{};let t=this.getLocalUserDataSyncConfiguration(),n=this.enabled.find(i=>i instanceof To);if(n){let i=await n.getRemoteUserDataSyncConfiguration(cv(e,this.collection,"settings")??null);return{...t,...i}}return t}getLocalUserDataSyncConfiguration(){return this.configurationService.getValue(ho)}setStatus(e){this._status!==e&&(this._status=e,this._onDidChangeStatus.fire(e))}updateStatus(){return this.updateConflicts(),this.enabled.some(e=>e.status==="hasConflicts")?this.setStatus("hasConflicts"):this.enabled.some(e=>e.status==="syncing")?this.setStatus("syncing"):this.setStatus("idle")}updateConflicts(){let e=this.enabled.filter(t=>t.status==="hasConflicts").filter(t=>t.conflicts.conflicts.length>0).map(t=>t.conflicts);Pt(this._conflicts,e,(t,n)=>t.syncResource===n.syncResource&&Pt(t.conflicts,n.conflicts,(i,s)=>_r(i.previewResource,s.previewResource)))||(this._conflicts=e,this._onDidChangeConflicts.fire(e))}getOrder(e){switch(e){case"settings":return 0;case"keybindings":return 1;case"snippets":return 2;case"tasks":return 3;case"mcp":return 4;case"globalState":return 5;case"extensions":return 6;case"prompts":return 7;case"profiles":return 8;case"workspaceState":return 9}}};Mi=b([g(2,Oe),g(3,bt),g(4,At),g(5,Pr),g(6,de),g(7,me),g(8,Q)],Mi);function zx(o){if(o instanceof xe)switch(o.code){case"MethodNotFound":case"TooLarge":case"RemoteTooManyRequests":case"TooManyRequestsAndRetryAfter":case"LocalTooManyRequests":case"LocalTooManyProfiles":case"Gone":case"UpgradeRequired":case"IncompatibleRemoteContent":case"IncompatibleLocalContent":return!0}return!1}function gf(o,r,e,t){t.publicLog2("sync/error",{code:o.code,serverCode:o instanceof Ae?String(o.serverCode):void 0,url:o instanceof Ae?o.url:void 0,resource:o.resource,executionId:r,service:e.userDataSyncStore.url.toString()})}function cv(o,r,e){return Lx(o)?r?o?.collections?.[r]?.latest?.[e]:o?.latest?.[e]:r?o?.collections?.[r]?.resources?.[e]:o?.resources?.[e]}function LR(o,r){return{...o,profile:nr(o.profile,r.profilesHome.scheme)}}function MR(o){return{created:o.created,uri:P.revive(o.uri)}}var vf=class{constructor(r,e,t){this.service=r;this.userDataProfilesService=e;this.logService=t;this.manualSyncTasks=new Map;this.onManualSynchronizeResources=new w}listen(r,e){switch(e){case"onDidChangeStatus":return this.service.onDidChangeStatus;case"onDidChangeConflicts":return this.service.onDidChangeConflicts;case"onDidChangeLocal":return this.service.onDidChangeLocal;case"onDidChangeLastSyncTime":return this.service.onDidChangeLastSyncTime;case"onSyncErrors":return this.service.onSyncErrors;case"onDidResetLocal":return this.service.onDidResetLocal;case"onDidResetRemote":return this.service.onDidResetRemote;case"manualSync/onSynchronizeResources":return this.onManualSynchronizeResources.event}throw new Error(`[UserDataSyncServiceChannel] Event not found: ${e}`)}async call(r,e,t){try{return await this._call(r,e,t)}catch(n){throw this.logService.error(n),n}}async _call(r,e,t){switch(e){case"_getInitialData":return Promise.resolve([this.service.status,this.service.conflicts,this.service.lastSyncTime]);case"reset":return this.service.reset();case"resetRemote":return this.service.resetRemote();case"resetLocal":return this.service.resetLocal();case"hasPreviouslySynced":return this.service.hasPreviouslySynced();case"hasLocalData":return this.service.hasLocalData();case"resolveContent":return this.service.resolveContent(P.revive(t[0]));case"accept":return this.service.accept(LR(t[0],this.userDataProfilesService),P.revive(t[1]),t[2],t[3]);case"replace":return this.service.replace(MR(t[0]));case"cleanUpRemoteData":return this.service.cleanUpRemoteData();case"getRemoteActivityData":return this.service.saveRemoteActivityData(P.revive(t[0]));case"extractActivityData":return this.service.extractActivityData(P.revive(t[0]),P.revive(t[1]));case"createManualSyncTask":return this.createManualSyncTask()}if(e.startsWith("manualSync/")){let n=e.substring(11),i=t[0],s=this.getManualSyncTask(i);switch(t=t.slice(1),n){case"merge":return s.merge();case"apply":return s.apply().then(()=>this.manualSyncTasks.delete(this.createKey(s.id)));case"stop":return s.stop().finally(()=>this.manualSyncTasks.delete(this.createKey(s.id)))}}throw new Error("Invalid call")}getManualSyncTask(r){let e=this.manualSyncTasks.get(this.createKey(r));if(!e)throw new Error(`Manual sync taks not found: ${r}`);return e}async createManualSyncTask(){let r=await this.service.createManualSyncTask();return this.manualSyncTasks.set(this.createKey(r.id),r),r.id}createKey(r){return`manualSyncTask-${r}`}},hf=class extends T{constructor(e,t){super();this.userDataProfilesService=t;this._status="uninitialized";this._onDidChangeStatus=this._register(new w);this.onDidChangeStatus=this._onDidChangeStatus.event;this._conflicts=[];this._onDidChangeConflicts=this._register(new w);this.onDidChangeConflicts=this._onDidChangeConflicts.event;this._lastSyncTime=void 0;this._onDidChangeLastSyncTime=this._register(new w);this.onDidChangeLastSyncTime=this._onDidChangeLastSyncTime.event;this._onSyncErrors=this._register(new w);this.onSyncErrors=this._onSyncErrors.event;this.channel={call(n,i,s){return e.call(n,i,s).then(null,a=>{throw xe.toUserDataSyncError(a)})},listen(n,i){return e.listen(n,i)}},this.channel.call("_getInitialData").then(([n,i,s])=>{this.updateStatus(n),this.updateConflicts(i),s&&this.updateLastSyncTime(s),this._register(this.channel.listen("onDidChangeStatus")(a=>this.updateStatus(a))),this._register(this.channel.listen("onDidChangeLastSyncTime")(a=>this.updateLastSyncTime(a)))}),this._register(this.channel.listen("onDidChangeConflicts")(n=>this.updateConflicts(n))),this._register(this.channel.listen("onSyncErrors")(n=>this._onSyncErrors.fire(n.map(i=>({...i,error:xe.toUserDataSyncError(i.error)})))))}get status(){return this._status}get onDidChangeLocal(){return this.channel.listen("onDidChangeLocal")}get conflicts(){return this._conflicts}get lastSyncTime(){return this._lastSyncTime}get onDidResetLocal(){return this.channel.listen("onDidResetLocal")}get onDidResetRemote(){return this.channel.listen("onDidResetRemote")}createSyncTask(){throw new Error("not supported")}async createManualSyncTask(){let e=await this.channel.call("createManualSyncTask"),t=this;return new dv(e,{async call(i,s,a){return t.channel.call(`manualSync/${i}`,[e,...Array.isArray(s)?s:[s]],a)},listen(){throw new Error("not supported")}})}reset(){return this.channel.call("reset")}resetRemote(){return this.channel.call("resetRemote")}resetLocal(){return this.channel.call("resetLocal")}hasPreviouslySynced(){return this.channel.call("hasPreviouslySynced")}hasLocalData(){return this.channel.call("hasLocalData")}accept(e,t,n,i){return this.channel.call("accept",[e,t,n,i])}resolveContent(e){return this.channel.call("resolveContent",[e])}cleanUpRemoteData(){return this.channel.call("cleanUpRemoteData")}replace(e){return this.channel.call("replace",[e])}saveRemoteActivityData(e){return this.channel.call("getRemoteActivityData",[e])}extractActivityData(e,t){return this.channel.call("extractActivityData",[e,t])}async updateStatus(e){this._status=e,this._onDidChangeStatus.fire(e)}async updateConflicts(e){this._conflicts=e.map(t=>({syncResource:t.syncResource,profile:nr(t.profile,this.userDataProfilesService.profilesHome.scheme),conflicts:t.conflicts.map(n=>({...n,baseResource:P.revive(n.baseResource),localResource:P.revive(n.localResource),remoteResource:P.revive(n.remoteResource),previewResource:P.revive(n.previewResource)}))})),this._onDidChangeConflicts.fire(this._conflicts)}updateLastSyncTime(e){this._lastSyncTime!==e&&(this._lastSyncTime=e,this._onDidChangeLastSyncTime.fire(e))}};hf=b([g(1,fe)],hf);var dv=class extends T{constructor(e,t){super();this.id=e;this.channel=t}async merge(){return this.channel.call("merge")}async apply(){return this.channel.call("apply")}stop(){return this.channel.call("stop")}dispose(){this.channel.call("dispose"),super.dispose()}};var Ua=class extends Kp{constructor(r,e,t,n){super(!0,r,e,t,n)}};Ua=b([g(0,Rn),g(1,fe),g(2,K),g(3,V)],Ua);var yf=class extends T{constructor({onDidOpenMainWindow:e,onDidFocusMainWindow:t,getActiveWindowId:n}){super();this.disposables=this._register(new se);k.latch(k.any(e,t))(this.setActiveWindow,this,this.disposables),this.firstActiveWindowIdPromise=Je(()=>n()),(async()=>{try{let s=await this.firstActiveWindowIdPromise;this.activeWindowId=typeof this.activeWindowId=="number"?this.activeWindowId:s}catch{}finally{this.firstActiveWindowIdPromise=void 0}})()}setActiveWindow(e){this.firstActiveWindowIdPromise&&(this.firstActiveWindowIdPromise.cancel(),this.firstActiveWindowIdPromise=void 0),this.activeWindowId=e}async getActiveClientId(){return`window:${this.firstActiveWindowIdPromise?await this.firstActiveWindowIdPromise:this.activeWindowId}`}};var AR="signService",La=L(AR);var Sf=class o{constructor(){this.validators=new Map}static{this._nextId=1}async createNewMessage(r){try{let e=await this.getValidator();if(e){let t=String(o._nextId++);return this.validators.set(t,e),{id:t,data:e.createNewMessage(r)}}}catch{}return{id:"",data:r}}async validate(r,e){if(!r.id)return!0;let t=this.validators.get(r.id);if(!t)return!1;this.validators.delete(r.id);try{return t.validate(e)==="ok"}catch{return!1}finally{t.dispose?.()}}async sign(r){try{return await this.signValue(r)}catch{}return r}};var If=class extends Sf{getValidator(){return this.vsda().then(r=>new r.validator)}signValue(r){return this.vsda().then(e=>new e.signer().sign(r))}async vsda(){let r="vsda",{default:e}=await import(r);return e}};var Xte=L("tunnelService"),xf=L("sharedTunnelsService");function Kx(o){return!!o.forwardPort}function FR(o){if(o.scheme!=="http"&&o.scheme!=="https")return;let r=/^(localhost|127\.0\.0\.1|0\.0\.0\.0):(\d+)$/.exec(o.authority);if(r)return{address:r[1],port:+r[2]}}var uv=["localhost","127.0.0.1","0:0:0:0:0:0:0:1","::1"];function bf(o){return uv.indexOf(o)>=0}var pv=["0.0.0.0","0:0:0:0:0:0:0:0","::"];function Aa(o){return pv.indexOf(o)>=0}function jx(o,r,e,t){if(e===1)return!1;if(e===2&&Aa(r)){let n=/(\d+)\.(\d+)\.(\d+)/g.exec(t);if(n?.length===4&&parseInt(n[1])>=18)return!1}return o<1024}var Ma=class extends T{constructor(e,t){super();this.logService=e;this.configurationService=t;this._onTunnelOpened=this._register(new w);this.onTunnelOpened=this._onTunnelOpened.event;this._onTunnelClosed=this._register(new w);this.onTunnelClosed=this._onTunnelClosed.event;this._onAddedTunnelProvider=this._register(new w);this.onAddedTunnelProvider=this._onAddedTunnelProvider.event;this._tunnels=new Map;this._canElevate=!1;this._canChangeProtocol=!0;this._privacyOptions=[];this._factoryInProgress=new Set}get hasTunnelProvider(){return!!this._tunnelProvider}get defaultTunnelHost(){let e=this.configurationService.getValue("remote.localPortHost");return!e||e==="localhost"?"127.0.0.1":"0.0.0.0"}setTunnelProvider(e){return this._tunnelProvider=e,e?(this._onAddedTunnelProvider.fire(),{dispose:()=>{this._tunnelProvider=void 0,this._canElevate=!1,this._privacyOptions=[]}}):(this._canElevate=!1,this._privacyOptions=[],this._onAddedTunnelProvider.fire(),{dispose:()=>{}})}setTunnelFeatures(e){this._canElevate=e.elevation,this._privacyOptions=e.privacyOptions,this._canChangeProtocol=e.protocol}get canChangeProtocol(){return this._canChangeProtocol}get canElevate(){return this._canElevate}get canChangePrivacy(){return this._privacyOptions.length>0}get privacyOptions(){return this._privacyOptions}get tunnels(){return this.getTunnels()}async getTunnels(){let e=[],t=Array.from(this._tunnels.values());for(let n of t){let i=Array.from(n.values());for(let s of i){let a=await s.value;a&&typeof a!="string"&&e.push(a)}}return e}async dispose(){super.dispose();for(let e of this._tunnels.values()){for(let{value:t}of e.values())await t.then(n=>typeof n!="string"?n?.dispose():void 0);e.clear()}this._tunnels.clear()}setEnvironmentTunnel(e,t,n,i,s){this.addTunnelToMap(e,t,Promise.resolve({tunnelRemoteHost:e,tunnelRemotePort:t,localAddress:n,privacy:i,protocol:s,dispose:()=>Promise.resolve()}))}async getExistingTunnel(e,t){(Aa(e)||bf(e))&&(e=uv[0]);let n=this.getTunnelFromMap(e,t);if(n)return++n.refcount,n.value}openTunnel(e,t,n,i,s,a=!1,l,c){this.logService.trace(`ForwardedPorts: (TunnelService) openTunnel request for ${t}:${n} on local port ${s}.`);let d=this._tunnelProvider??e;if(!d)return;if(t||(t="localhost"),i||(i=this.defaultTunnelHost),this._tunnelProvider&&this._factoryInProgress.has(n)){this.logService.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}let u=this.retainOrCreateTunnel(d,t,n,i,s,a,l,c);return u?u.then(p=>{if(p){if(typeof p=="string")return this.logService.trace("ForwardedPorts: (TunnelService) The tunnel provider returned an error when creating the tunnel."),this.removeEmptyOrErrorTunnelFromMap(t,n),p}else{this.logService.trace("ForwardedPorts: (TunnelService) New tunnel is undefined."),this.removeEmptyOrErrorTunnelFromMap(t,n);return}this.logService.trace("ForwardedPorts: (TunnelService) New tunnel established.");let m=this.makeTunnel(p);return(p.tunnelRemoteHost!==t||p.tunnelRemotePort!==n)&&this.logService.warn("ForwardedPorts: (TunnelService) Created tunnel does not match requirements of requested tunnel. Host or port mismatch."),l&&p.privacy!==l&&this.logService.warn("ForwardedPorts: (TunnelService) Created tunnel does not match requirements of requested tunnel. Privacy mismatch."),this._onTunnelOpened.fire(m),m}):(this.logService.trace("ForwardedPorts: (TunnelService) Tunnel was not created."),u)}makeTunnel(e){return{tunnelRemotePort:e.tunnelRemotePort,tunnelRemoteHost:e.tunnelRemoteHost,tunnelLocalPort:e.tunnelLocalPort,localAddress:e.localAddress,privacy:e.privacy,protocol:e.protocol,dispose:async()=>{this.logService.trace(`ForwardedPorts: (TunnelService) dispose request for ${e.tunnelRemoteHost}:${e.tunnelRemotePort} `);let t=this._tunnels.get(e.tunnelRemoteHost);if(t){let n=t.get(e.tunnelRemotePort);n&&(n.refcount--,await this.tryDisposeTunnel(e.tunnelRemoteHost,e.tunnelRemotePort,n))}}}}async tryDisposeTunnel(e,t,n){if(n.refcount<=0){this.logService.trace(`ForwardedPorts: (TunnelService) Tunnel is being disposed ${e}:${t}.`);let i=n.value.then(async s=>{s&&typeof s!="string"&&(await s.dispose(!0),this._onTunnelClosed.fire({host:s.tunnelRemoteHost,port:s.tunnelRemotePort}))});return this._tunnels.has(e)&&this._tunnels.get(e).delete(t),i}}async closeTunnel(e,t){this.logService.trace(`ForwardedPorts: (TunnelService) close request for ${e}:${t} `);let n=this._tunnels.get(e);if(n&&n.has(t)){let i=n.get(t);i.refcount=0,await this.tryDisposeTunnel(e,t,i)}}addTunnelToMap(e,t,n){this._tunnels.has(e)||this._tunnels.set(e,new Map),this._tunnels.get(e).set(t,{refcount:1,value:n})}async removeEmptyOrErrorTunnelFromMap(e,t){let n=this._tunnels.get(e);if(n){let i=n.get(t),s=i?await i.value:void 0;(!s||typeof s=="string")&&n.delete(t),n.size===0&&this._tunnels.delete(e)}}getTunnelFromMap(e,t){let n=[e];bf(e)?(n.push(...uv),n.push(...pv)):Aa(e)&&n.push(...pv);let i=n.map(s=>this._tunnels.get(s));for(let s of i){let a=s?.get(t);if(a)return a}}canTunnel(e){return!!FR(e)}createWithProvider(e,t,n,i,s,a,l){this.logService.trace(`ForwardedPorts: (TunnelService) Creating tunnel with provider ${t}:${n} on local port ${i}.`);let c=n;this._factoryInProgress.add(c);let d=i===void 0?n:i,u={elevationRequired:s?this.isPortPrivileged(d):!1},p={remoteAddress:{host:t,port:n},localAddressPort:i,privacy:a,public:a?a!=="private":void 0,protocol:l},m=e.forwardPort(p,u);return m?(this.addTunnelToMap(t,n,m),m.finally(()=>{this.logService.trace("ForwardedPorts: (TunnelService) Tunnel created by provider."),this._factoryInProgress.delete(c)})):this._factoryInProgress.delete(c),m}};Ma=b([g(0,V),g(1,Q)],Ma);import*as r1 from"net";import*as n1 from"os";import*as fv from"net";var mv={1:!0,7:!0,9:!0,11:!0,13:!0,15:!0,17:!0,19:!0,20:!0,21:!0,22:!0,23:!0,25:!0,37:!0,42:!0,43:!0,53:!0,69:!0,77:!0,79:!0,87:!0,95:!0,101:!0,102:!0,103:!0,104:!0,109:!0,110:!0,111:!0,113:!0,115:!0,117:!0,119:!0,123:!0,135:!0,137:!0,139:!0,143:!0,161:!0,179:!0,389:!0,427:!0,465:!0,512:!0,513:!0,514:!0,515:!0,526:!0,530:!0,531:!0,532:!0,540:!0,548:!0,554:!0,556:!0,563:!0,587:!0,601:!0,636:!0,989:!0,990:!0,993:!0,995:!0,1719:!0,1720:!0,1723:!0,2049:!0,3659:!0,4045:!0,5060:!0,5061:!0,6e3:!0,6566:!0,6665:!0,6666:!0,6667:!0,6668:!0,6669:!0,6697:!0,10080:!0};function Hx(o,r,e,t="127.0.0.1"){let n=!1,i,s=1,a=fv.createServer({pauseOnConnect:!0});function l(c,d){n||(n=!0,a.removeAllListeners(),a.close(),i&&clearTimeout(i),d(c))}return new Promise(c=>{i=setTimeout(()=>{l(0,c)},e),a.on("listening",()=>{l(o,c)}),a.on("error",d=>{d&&(d.code==="EADDRINUSE"||d.code==="EACCES")&&s<r?(o++,s++,a.listen(o,t)):l(0,c)}),a.on("close",()=>{l(0,c)}),a.listen(o,t)})}import{createHash as mre}from"crypto";import{createConnection as yre,createServer as Sre}from"net";import{tmpdir as bre}from"os";import{createDeflateRaw as Rre,createInflateRaw as Tre}from"zlib";var Tf;(s=>{s.enableDiagnostics=!1,s.records=[];let e=new WeakMap,t=0;function n(a,l){if(!e.has(a)){let c=String(++t);e.set(a,c)}return e.get(a)}function i(a,l,c,d){}s.traceSocketEvent=i})(Tf||={});var gv=null;function Ai(){return gv||(gv=U.alloc(0)),gv}var Ef=class{get byteLength(){return this._totalLength}constructor(){this._chunks=[],this._totalLength=0}acceptChunk(r){this._chunks.push(r),this._totalLength+=r.byteLength}read(r){return this._read(r,!0)}peek(r){return this._read(r,!1)}_read(r,e){if(r===0)return Ai();if(r>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===r){let s=this._chunks[0];return e&&(this._chunks.shift(),this._totalLength-=r),s}if(this._chunks[0].byteLength>r){let s=this._chunks[0].slice(0,r);return e&&(this._chunks[0]=this._chunks[0].slice(r),this._totalLength-=r),s}let t=U.alloc(r),n=0,i=0;for(;r>0;){let s=this._chunks[i];if(s.byteLength>r){let a=s.slice(0,r);t.set(a,n),n+=r,e&&(this._chunks[i]=s.slice(r),this._totalLength-=r),r-=r}else t.set(s,n),n+=s.byteLength,e?(this._chunks.shift(),this._totalLength-=s.byteLength):i++,r-=s.byteLength}return t}};function Jx(o){switch(o){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 Yr=class{constructor(r,e,t,n){this.type=r;this.id=e;this.ack=t;this.data=n;this.writtenTime=0}get size(){return this.data.byteLength}},wf=class extends T{constructor(e){super();this._onMessage=this._register(new w);this.onMessage=this._onMessage.event;this._state={readHead:!0,readLen:13,messageType:0,id:0,ack:0};this._socket=e,this._isDisposed=!1,this._incomingData=new Ef,this._register(this._socket.onData(t=>this.acceptChunk(t))),this.lastReadTime=Date.now()}acceptChunk(e){if(!(!e||e.byteLength===0))for(this.lastReadTime=Date.now(),this._incomingData.acceptChunk(e);this._incomingData.byteLength>=this._state.readLen;){let t=this._incomingData.read(this._state.readLen);if(this._state.readHead)this._state.readHead=!1,this._state.readLen=t.readUInt32BE(9),this._state.messageType=t.readUInt8(0),this._state.id=t.readUInt32BE(1),this._state.ack=t.readUInt32BE(5),this._socket.traceSocketEvent("protocolHeaderRead",{messageType:Jx(this._state.messageType),id:this._state.id,ack:this._state.ack,messageSize:this._state.readLen});else{let n=this._state.messageType,i=this._state.id,s=this._state.ack;if(this._state.readHead=!0,this._state.readLen=13,this._state.messageType=0,this._state.id=0,this._state.ack=0,this._socket.traceSocketEvent("protocolMessageRead",t),this._onMessage.fire(new Yr(n,i,s,t)),this._isDisposed)break}}}readEntireBuffer(){return this._incomingData.read(this._incomingData.byteLength)}dispose(){this._isDisposed=!0,super.dispose()}},Pf=class{constructor(r){this._writeNowTimeout=null;this._isDisposed=!1,this._isPaused=!1,this._socket=r,this._data=[],this._totalLength=0,this.lastWriteTime=0}dispose(){try{this.flush()}catch{}this._isDisposed=!0}drain(){return this.flush(),this._socket.drain()}flush(){this._writeNow()}pause(){this._isPaused=!0}resume(){this._isPaused=!1,this._scheduleWriting()}write(r){if(this._isDisposed)return;r.writtenTime=Date.now(),this.lastWriteTime=Date.now();let e=U.alloc(13);e.writeUInt8(r.type,0),e.writeUInt32BE(r.id,1),e.writeUInt32BE(r.ack,5),e.writeUInt32BE(r.data.byteLength,9),this._socket.traceSocketEvent("protocolHeaderWrite",{messageType:Jx(r.type),id:r.id,ack:r.ack,messageSize:r.data.byteLength}),this._socket.traceSocketEvent("protocolMessageWrite",r.data),this._writeSoon(e,r.data)}_bufferAdd(r,e){let t=this._totalLength===0;return this._data.push(r,e),this._totalLength+=r.byteLength+e.byteLength,t}_bufferTake(){let r=U.concat(this._data,this._totalLength);return this._data.length=0,this._totalLength=0,r}_writeSoon(r,e){this._bufferAdd(r,e)&&this._scheduleWriting()}_scheduleWriting(){this._writeNowTimeout||(this._writeNowTimeout=setTimeout(()=>{this._writeNowTimeout=null,this._writeNow()}))}_writeNow(){if(this._totalLength===0||this._isPaused)return;let r=this._bufferTake();this._socket.traceSocketEvent("protocolWrite",{byteLength:r.byteLength}),this._socket.write(r)}};var Co=class{constructor(){this._hasListeners=!1;this._isDeliveringMessages=!1;this._bufferedMessages=[];this._emitter=new w({onWillAddFirstListener:()=>{this._hasListeners=!0,queueMicrotask(()=>this._deliverMessages())},onDidRemoveLastListener:()=>{this._hasListeners=!1}}),this.event=this._emitter.event}_deliverMessages(){if(!this._isDeliveringMessages){for(this._isDeliveringMessages=!0;this._hasListeners&&this._bufferedMessages.length>0;)this._emitter.fire(this._bufferedMessages.shift());this._isDeliveringMessages=!1}}fire(r){this._hasListeners?this._bufferedMessages.length>0?this._bufferedMessages.push(r):this._emitter.fire(r):this._bufferedMessages.push(r)}flushBuffer(){this._bufferedMessages=[]}},hv=class{constructor(r){this.data=r,this.next=null}},vv=class{constructor(){this._first=null,this._last=null}length(){let r=0,e=this._first;for(;e;)e=e.next,r++;return r}peek(){return this._first?this._first.data:null}toArray(){let r=[],e=0,t=this._first;for(;t;)r[e++]=t.data,t=t.next;return r}pop(){if(this._first){if(this._first===this._last){this._first=null,this._last=null;return}this._first=this._first.next}}push(r){let e=new hv(r);if(!this._first){this._first=e,this._last=e;return}this._last.next=e,this._last=e}},yv=class o{static{this._HISTORY_LENGTH=10}static{this._INSTANCE=null}static getInstance(){return o._INSTANCE||(o._INSTANCE=new o),o._INSTANCE}constructor(){this.lastRuns=[];let r=Date.now();for(let e=0;e<o._HISTORY_LENGTH;e++)this.lastRuns[e]=r-1e3*e;setInterval(()=>{for(let e=o._HISTORY_LENGTH;e>=1;e--)this.lastRuns[e]=this.lastRuns[e-1];this.lastRuns[0]=Date.now()},1e3)}load(){let r=Date.now(),e=(1+o._HISTORY_LENGTH)*1e3,t=0;for(let n=0;n<o._HISTORY_LENGTH;n++)r-this.lastRuns[n]<=e&&t++;return 1-t/o._HISTORY_LENGTH}hasHighLoad(){return this.load()>=.5}},Rf=class{constructor(r){this._onControlMessage=new Co;this.onControlMessage=this._onControlMessage.event;this._onMessage=new Co;this.onMessage=this._onMessage.event;this._onDidDispose=new Co;this.onDidDispose=this._onDidDispose.event;this._onSocketClose=new Co;this.onSocketClose=this._onSocketClose.event;this._onSocketTimeout=new Co;this.onSocketTimeout=this._onSocketTimeout.event;this._loadEstimator=r.loadEstimator??yv.getInstance(),this._shouldSendKeepAlive=r.sendKeepAlive??!0,this._isReconnecting=!1,this._outgoingUnackMsg=new vv,this._outgoingMsgId=0,this._outgoingAckId=0,this._outgoingAckTimeout=null,this._incomingMsgId=0,this._incomingAckId=0,this._incomingMsgLastTime=0,this._incomingAckTimeout=null,this._lastReplayRequestTime=0,this._lastSocketTimeoutTime=Date.now(),this._socketDisposables=new se,this._socket=r.socket,this._socketWriter=this._socketDisposables.add(new Pf(this._socket)),this._socketReader=this._socketDisposables.add(new wf(this._socket)),this._socketDisposables.add(this._socketReader.onMessage(e=>this._receiveMessage(e))),this._socketDisposables.add(this._socket.onClose(e=>this._onSocketClose.fire(e))),r.initialChunk&&this._socketReader.acceptChunk(r.initialChunk),this._shouldSendKeepAlive?this._keepAliveInterval=setInterval(()=>{this._sendKeepAlive()},5e3):this._keepAliveInterval=null}get unacknowledgedCount(){return this._outgoingMsgId-this._outgoingAckId}dispose(){this._outgoingAckTimeout&&(clearTimeout(this._outgoingAckTimeout),this._outgoingAckTimeout=null),this._incomingAckTimeout&&(clearTimeout(this._incomingAckTimeout),this._incomingAckTimeout=null),this._keepAliveInterval&&(clearInterval(this._keepAliveInterval),this._keepAliveInterval=null),this._socketDisposables.dispose()}drain(){return this._socketWriter.drain()}sendDisconnect(){if(!this._didSendDisconnect){this._didSendDisconnect=!0;let r=new Yr(5,0,0,Ai());this._socketWriter.write(r),this._socketWriter.flush()}}sendPause(){let r=new Yr(7,0,0,Ai());this._socketWriter.write(r)}sendResume(){let r=new Yr(8,0,0,Ai());this._socketWriter.write(r)}pauseSocketWriting(){this._socketWriter.pause()}getSocket(){return this._socket}getMillisSinceLastIncomingData(){return Date.now()-this._socketReader.lastReadTime}beginAcceptReconnection(r,e){this._isReconnecting=!0,this._socketDisposables.dispose(),this._socketDisposables=new se,this._onControlMessage.flushBuffer(),this._onSocketClose.flushBuffer(),this._onSocketTimeout.flushBuffer(),this._socket.dispose(),this._lastReplayRequestTime=0,this._lastSocketTimeoutTime=Date.now(),this._socket=r,this._socketWriter=this._socketDisposables.add(new Pf(this._socket)),this._socketReader=this._socketDisposables.add(new wf(this._socket)),this._socketDisposables.add(this._socketReader.onMessage(t=>this._receiveMessage(t))),this._socketDisposables.add(this._socket.onClose(t=>this._onSocketClose.fire(t))),this._socketReader.acceptChunk(e)}endAcceptReconnection(){this._isReconnecting=!1,this._incomingAckId=this._incomingMsgId;let r=new Yr(3,0,this._incomingAckId,Ai());this._socketWriter.write(r);let e=this._outgoingUnackMsg.toArray();for(let t=0,n=e.length;t<n;t++)this._socketWriter.write(e[t]);this._recvAckCheck()}acceptDisconnect(){this._onDidDispose.fire()}_receiveMessage(r){if(r.ack>this._outgoingAckId){this._outgoingAckId=r.ack;do{let e=this._outgoingUnackMsg.peek();if(e&&e.id<=r.ack)this._outgoingUnackMsg.pop();else break}while(!0)}switch(r.type){case 0:break;case 1:{if(r.id>this._incomingMsgId)if(r.id!==this._incomingMsgId+1){let e=Date.now();e-this._lastReplayRequestTime>1e4&&(this._lastReplayRequestTime=e,this._socketWriter.write(new Yr(6,0,0,Ai())))}else this._incomingMsgId=r.id,this._incomingMsgLastTime=Date.now(),this._sendAckCheck(),this._onMessage.fire(r.data);break}case 2:{this._onControlMessage.fire(r.data);break}case 3:break;case 5:{this._onDidDispose.fire();break}case 6:{let e=this._outgoingUnackMsg.toArray();for(let t=0,n=e.length;t<n;t++)this._socketWriter.write(e[t]);this._recvAckCheck();break}case 7:{this._socketWriter.pause();break}case 8:{this._socketWriter.resume();break}case 9:break}}readEntireBuffer(){return this._socketReader.readEntireBuffer()}flush(){this._socketWriter.flush()}send(r){let e=++this._outgoingMsgId;this._incomingAckId=this._incomingMsgId;let t=new Yr(1,e,this._incomingAckId,r);this._outgoingUnackMsg.push(t),this._isReconnecting||(this._socketWriter.write(t),this._recvAckCheck())}sendControl(r){let e=new Yr(2,0,0,r);this._socketWriter.write(e)}_sendAckCheck(){if(this._incomingMsgId<=this._incomingAckId||this._incomingAckTimeout)return;let r=Date.now()-this._incomingMsgLastTime;if(r>=2e3){this._sendAck();return}this._incomingAckTimeout=setTimeout(()=>{this._incomingAckTimeout=null,this._sendAckCheck()},2e3-r+5)}_recvAckCheck(){if(this._outgoingMsgId<=this._outgoingAckId||this._outgoingAckTimeout||this._isReconnecting)return;let r=this._outgoingUnackMsg.peek(),e=Date.now()-r.writtenTime,t=Date.now()-this._socketReader.lastReadTime,n=Date.now()-this._lastSocketTimeoutTime;if(e>=2e4&&t>=2e4&&n>=2e4&&!this._loadEstimator.hasHighLoad()){this._lastSocketTimeoutTime=Date.now(),this._onSocketTimeout.fire({unacknowledgedMsgCount:this._outgoingUnackMsg.length(),timeSinceOldestUnacknowledgedMsg:e,timeSinceLastReceivedSomeData:t});return}let i=Math.max(2e4-e,2e4-t,2e4-n,500);this._outgoingAckTimeout=setTimeout(()=>{this._outgoingAckTimeout=null,this._recvAckCheck()},i)}_sendAck(){if(this._incomingMsgId<=this._incomingAckId)return;this._incomingAckId=this._incomingMsgId;let r=new Yr(3,0,this._incomingAckId,Ai());this._socketWriter.write(r)}_sendKeepAlive(){this._incomingAckId=this._incomingMsgId;let r=new Yr(9,0,this._incomingAckId,Ai());this._socketWriter.write(r)}};var VR=3e4,Do=class{constructor(r,e=""){this._canWrite=!0;this.debugLabel=e,this.socket=r,this.traceSocketEvent("created",{type:"NodeSocket"}),this._errorListener=n=>{if(this.traceSocketEvent("error",{code:n?.code,message:n?.message}),n){if(n.code==="EPIPE")return;Me(n)}},this.socket.on("error",this._errorListener);let t;this._closeListener=n=>{this.traceSocketEvent("close",{hadError:n}),this._canWrite=!1,t&&clearTimeout(t)},this.socket.on("close",this._closeListener),this._endListener=()=>{this.traceSocketEvent("nodeEndReceived"),this._canWrite=!1,t=setTimeout(()=>r.destroy(),VR)},this.socket.on("end",this._endListener)}traceSocketEvent(r,e){Tf.traceSocketEvent(this.socket,this.debugLabel,r,e)}dispose(){this.socket.off("error",this._errorListener),this.socket.off("close",this._closeListener),this.socket.off("end",this._endListener),this.socket.destroy()}onData(r){let e=t=>{this.traceSocketEvent("read",t),r(U.wrap(t))};return this.socket.on("data",e),{dispose:()=>this.socket.off("data",e)}}onClose(r){let e=t=>{r({type:0,hadError:t,error:void 0})};return this.socket.on("close",e),{dispose:()=>this.socket.off("close",e)}}onEnd(r){let e=()=>{r()};return this.socket.on("end",e),{dispose:()=>this.socket.off("end",e)}}write(r){if(!(this.socket.destroyed||!this._canWrite))try{this.traceSocketEvent("write",r),this.socket.write(r.buffer,e=>{if(e){if(e.code==="EPIPE")return;Me(e)}})}catch(e){if(e.code==="EPIPE")return;Me(e)}}end(){this.traceSocketEvent("nodeEndSent"),this.socket.end()}drain(){return this.traceSocketEvent("nodeDrainBegin"),new Promise((r,e)=>{if(this.socket.bufferSize===0){this.traceSocketEvent("nodeDrainEnd"),r();return}let t=()=>{this.socket.off("close",t),this.socket.off("end",t),this.socket.off("error",t),this.socket.off("timeout",t),this.socket.off("drain",t),this.traceSocketEvent("nodeDrainEnd"),r()};this.socket.on("close",t),this.socket.on("end",t),this.socket.on("error",t),this.socket.on("timeout",t),this.socket.on("drain",t)})}};var Bre=process.env.XDG_RUNTIME_DIR,$re={2:107,1:103};var Kre=L("remoteAuthorityResolverService");var Fa=class o extends $r{static isNotAvailable(r){return r instanceof o&&r._code==="NotAvailable"}static isTemporarilyNotAvailable(r){return r instanceof o&&r._code==="TemporarilyNotAvailable"}static isNoResolverFound(r){return r instanceof o&&r._code==="NoResolverFound"}static isInvalidAuthority(r){return r instanceof o&&r._code==="InvalidAuthority"}static isHandled(r){return r instanceof o&&r.isHandled}constructor(r,e="Unknown",t){super(r),this._message=r,this._code=e,this._detail=t,this.isHandled=e==="NotAvailable"&&t===!0,Object.setPrototypeOf(this,o.prototype)}};var WR=30*1e3;function Iv(o){switch(o){case 1:return"Management";case 2:return"ExtensionHost";case 3:return"Tunnel"}}function Xx(o){let r=new mt;return setTimeout(()=>r.cancel(),o),r.token}function BR(o,r){if(o.isCancellationRequested||r.isCancellationRequested)return Y.Cancelled;let e=new mt;return o.onCancellationRequested(()=>e.cancel()),r.onCancellationRequested(()=>e.cancel()),e.token}var Fc=class{get didTimeout(){return this._state==="timedout"}constructor(r){this._state="pending",this._disposables=new se,{promise:this.promise,resolve:this._resolvePromise,reject:this._rejectPromise}=FS(),r.isCancellationRequested?this._timeout():this._disposables.add(r.onCancellationRequested(()=>this._timeout()))}registerDisposable(r){this._state==="pending"?this._disposables.add(r):r.dispose()}_timeout(){this._state==="pending"&&(this._disposables.dispose(),this._state="timedout",this._rejectPromise(this._createTimeoutError()))}_createTimeoutError(){let r=new Error("Time limit reached");return r.code="ETIMEDOUT",r.syscall="connect",r}resolve(r){this._state==="pending"&&(this._disposables.dispose(),this._state="resolved",this._resolvePromise(r))}reject(r){this._state==="pending"&&(this._disposables.dispose(),this._state="rejected",this._rejectPromise(r))}};function $R(o,r){let e=new Fc(r);return e.registerDisposable(o.onControlMessage(t=>{let n=JSON.parse(t.toString()),i=jR(n);i?e.reject(i):e.resolve(n)})),e.promise}function GR(o,r,e,t,n,i,s,a){let l=new Fc(a),c=qr.create(!1);return o.info(`Creating a socket (${s})...`),Tn(`code/willCreateSocket/${i}`),r.connect(e,t,n,s).then(d=>{l.didTimeout?(Tn(`code/didCreateSocketError/${i}`),o.info(`Creating a socket (${s}) finished after ${c.elapsed()} ms, but this is too late and has timed out already.`),d?.dispose()):(Tn(`code/didCreateSocketOK/${i}`),o.info(`Creating a socket (${s}) was successful after ${c.elapsed()} ms.`),l.resolve(d))},d=>{Tn(`code/didCreateSocketError/${i}`),o.info(`Creating a socket (${s}) returned an error after ${c.elapsed()} ms.`),o.error(d),l.reject(d)}),l.promise}function Sv(o,r){let e=new Fc(r);return o.then(t=>{e.didTimeout||e.resolve(t)},t=>{e.didTimeout||e.reject(t)}),e.promise}async function qR(o,r,e,t){let n=t1(o,r);o.logService.trace(`${n} 1/6. invoking socketFactory.connect().`);let i;try{i=await GR(o.logService,o.remoteSocketFactoryService,o.connectTo,Wm.getServerRootPath(),`reconnectionToken=${o.reconnectionToken}&reconnection=${o.reconnectionProtocol?"true":"false"}`,Iv(r),`renderer-${Iv(r)}-${o.reconnectionToken}`,t)}catch(d){throw o.logService.error(`${n} socketFactory.connect() failed or timed out. Error:`),o.logService.error(d),d}o.logService.trace(`${n} 2/6. socketFactory.connect() was successful.`);let s,a;o.reconnectionProtocol?(o.reconnectionProtocol.beginAcceptReconnection(i,null),s=o.reconnectionProtocol,a=!1):(s=new Rf({socket:i}),a=!0),o.logService.trace(`${n} 3/6. sending AuthRequest control message.`);let l=await Sv(o.signService.createNewMessage(Le()),t),c={type:"auth",auth:o.connectionToken||"00000000000000000000",data:l.data};s.sendControl(U.fromString(JSON.stringify(c)));try{let d=await $R(s,BR(t,Xx(1e4)));if(d.type!=="sign"||typeof d.data!="string"){let h=new Error("Unexpected handshake message");throw h.code="VSCODE_CONNECTION_ERROR",h}if(o.logService.trace(`${n} 4/6. received SignRequest control message.`),!await Sv(o.signService.validate(l,d.signedData),t)){let h=new Error("Refused to connect to unsupported server");throw h.code="VSCODE_CONNECTION_ERROR",h}let p=await Sv(o.signService.sign(d.data),t),m={type:"connectionType",commit:o.commit,signedData:p,desiredConnectionType:r};return e&&(m.args=e),o.logService.trace(`${n} 5/6. sending ConnectionTypeRequest control message.`),s.sendControl(U.fromString(JSON.stringify(m))),{protocol:s,ownsProtocol:a}}catch(d){throw d&&d.code==="ETIMEDOUT"&&(o.logService.error(`${n} the handshake timed out. Error:`),o.logService.error(d)),d&&d.code==="VSCODE_CONNECTION_ERROR"&&(o.logService.error(`${n} received error control message when negotiating connection. Error:`),o.logService.error(d)),a&&e1(s),d}}async function zR(o,r,e){let t=Date.now(),n=t1(o,3),{protocol:i}=await qR(o,3,r,e);return o.logService.trace(`${n} 6/6. handshake finished, connection is up and running after ${XR(t)}!`),i}async function Yx(o,r,e){let{connectTo:t,connectionToken:n}=await o.addressProvider.getAddress();return{commit:o.commit,quality:o.quality,connectTo:t,connectionToken:n,reconnectionToken:r,reconnectionProtocol:e,remoteSocketFactoryService:o.remoteSocketFactoryService,signService:o.signService,logService:o.logService}}async function Zx(o,r,e){let t=await Yx(o,Le(),null);return await zR(t,{host:r,port:e},Y.None)}function KR(o){return Je(r=>new Promise((e,t)=>{let n=setTimeout(e,o*1e3);r.onCancellationRequested(()=>{clearTimeout(n),e()})}))}var bv=class{constructor(r,e){this.reconnectionToken=r;this.millisSinceLastIncomingData=e;this.type=0}},xv=class{constructor(r,e,t,n){this.reconnectionToken=r;this.millisSinceLastIncomingData=e;this.durationSeconds=t;this.cancellableTimer=n;this.type=1}skipWait(){this.cancellableTimer.cancel()}},Ev=class{constructor(r,e,t){this.reconnectionToken=r;this.millisSinceLastIncomingData=e;this.attempt=t;this.type=2}},Cf=class{constructor(r,e,t){this.reconnectionToken=r;this.millisSinceLastIncomingData=e;this.attempt=t;this.type=4}},wv=class{constructor(r,e,t,n){this.reconnectionToken=r;this.millisSinceLastIncomingData=e;this.attempt=t;this.handled=n;this.type=3}},Qx=class o extends T{constructor(e,t,n,i,s){super();this._connectionType=e;this._options=t;this.reconnectionToken=n;this.protocol=i;this._reconnectionFailureIsFatal=s;this._onDidStateChange=this._register(new w);this.onDidStateChange=this._onDidStateChange.event;this._permanentFailure=!1;this._isReconnecting=!1;this._isDisposed=!1;this._reconnectionGraceTime=108e5;this._onDidStateChange.fire(new Cf(this.reconnectionToken,0,0)),this._register(i.onSocketClose(a=>{let l=Ac(this._connectionType,this.reconnectionToken,!0);a?a.type===0?(this._options.logService.info(`${l} received socket close event (hadError: ${a.hadError}).`),a.error&&this._options.logService.error(a.error)):(this._options.logService.info(`${l} received socket close event (wasClean: ${a.wasClean}, code: ${a.code}, reason: ${a.reason}).`),a.event&&this._options.logService.error(a.event)):this._options.logService.info(`${l} received socket close event.`),this._beginReconnecting()})),this._register(i.onSocketTimeout(a=>{let l=Ac(this._connectionType,this.reconnectionToken,!0);this._options.logService.info(`${l} received socket timeout event (unacknowledgedMsgCount: ${a.unacknowledgedMsgCount}, timeSinceOldestUnacknowledgedMsg: ${a.timeSinceOldestUnacknowledgedMsg}, timeSinceLastReceivedSomeData: ${a.timeSinceLastReceivedSomeData}).`),this._beginReconnecting()})),o._instances.push(this),this._register(oe(()=>{let a=o._instances.indexOf(this);a>=0&&o._instances.splice(a,1)})),this._isPermanentFailure&&this._gotoPermanentFailure(o._permanentFailureMillisSinceLastIncomingData,o._permanentFailureAttempt,o._permanentFailureHandled)}static triggerPermanentFailure(e,t,n){this._permanentFailure=!0,this._permanentFailureMillisSinceLastIncomingData=e,this._permanentFailureAttempt=t,this._permanentFailureHandled=n,this._instances.forEach(i=>i._gotoPermanentFailure(this._permanentFailureMillisSinceLastIncomingData,this._permanentFailureAttempt,this._permanentFailureHandled))}static debugTriggerReconnection(){this._instances.forEach(e=>e._beginReconnecting())}static debugPauseSocketWriting(){this._instances.forEach(e=>e._pauseSocketWriting())}static{this._permanentFailure=!1}static{this._permanentFailureMillisSinceLastIncomingData=0}static{this._permanentFailureAttempt=0}static{this._permanentFailureHandled=!1}static{this._instances=[]}get _isPermanentFailure(){return this._permanentFailure||o._permanentFailure}updateGraceTime(e){let t=HR(e,108e5),n=Ac(this._connectionType,this.reconnectionToken,!1);this._options.logService.trace(`${n} Applying reconnection grace time: ${t}ms (${Math.floor(t/1e3)}s)`),this._reconnectionGraceTime=t}dispose(){super.dispose(),this._isDisposed=!0}async _beginReconnecting(){if(!this._isReconnecting)try{this._isReconnecting=!0,await this._runReconnectingLoop()}finally{this._isReconnecting=!1}}async _runReconnectingLoop(){if(this._isPermanentFailure||this._isDisposed)return;let e=Ac(this._connectionType,this.reconnectionToken,!0);this._options.logService.info(`${e} starting reconnecting loop. You can get more information with the trace log level.`),this._onDidStateChange.fire(new bv(this.reconnectionToken,this.protocol.getMillisSinceLastIncomingData()));let t=[0,5,5,10,10,10,10,10,30],n=this._reconnectionGraceTime;if(this._options.logService.info(`${e} starting reconnection with grace time: ${n}ms (${Math.floor(n/1e3)}s)`),n<=0){this._options.logService.error(`${e} reconnection grace time is set to 0ms, will not attempt to reconnect.`),this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(),0,!1);return}let i=Date.now(),s=-1;do{s++;let a=s<t.length?t[s]:t[t.length-1];try{if(a>0){let c=KR(a);this._onDidStateChange.fire(new xv(this.reconnectionToken,this.protocol.getMillisSinceLastIncomingData(),a,c)),this._options.logService.info(`${e} waiting for ${a} seconds before reconnecting...`);try{await c}catch{}}if(this._isPermanentFailure){this._options.logService.error(`${e} permanent failure occurred while running the reconnecting loop.`);break}this._onDidStateChange.fire(new Ev(this.reconnectionToken,this.protocol.getMillisSinceLastIncomingData(),s+1)),this._options.logService.info(`${e} resolving connection...`);let l=await Yx(this._options,this.reconnectionToken,this.protocol);this._options.logService.info(`${e} connecting to ${l.connectTo}...`),await this._reconnect(l,Xx(WR)),this._options.logService.info(`${e} reconnected!`),this._onDidStateChange.fire(new Cf(this.reconnectionToken,this.protocol.getMillisSinceLastIncomingData(),s+1));break}catch(l){if(l.code==="VSCODE_CONNECTION_ERROR"){this._options.logService.error(`${e} A permanent error occurred in the reconnecting loop! Will give up now! Error:`),this._options.logService.error(l),this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(),s+1,!1);break}if(Date.now()-i>=n){let c=Math.round(n/1e3);this._options.logService.error(`${e} An error occurred while reconnecting, but it will be treated as a permanent error because the reconnection grace time (${c}s) has expired! Will give up now! Error:`),this._options.logService.error(l),this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(),s+1,!1);break}if(Fa.isTemporarilyNotAvailable(l)){this._options.logService.info(`${e} A temporarily not available error occurred while trying to reconnect, will try again...`),this._options.logService.trace(l);continue}if((l.code==="ETIMEDOUT"||l.code==="ENETUNREACH"||l.code==="ECONNREFUSED"||l.code==="ECONNRESET")&&l.syscall==="connect"){this._options.logService.info(`${e} A network error occurred while trying to reconnect, will try again...`),this._options.logService.trace(l);continue}if(lr(l)){this._options.logService.info(`${e} A promise cancelation error occurred while trying to reconnect, will try again...`),this._options.logService.trace(l);continue}if(l instanceof Fa){this._options.logService.error(`${e} A RemoteAuthorityResolverError occurred while trying to reconnect. Will give up now! Error:`),this._options.logService.error(l),this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(),s+1,Fa.isHandled(l));break}this._options.logService.error(`${e} 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._options.logService.error(l),this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(),s+1,!1);break}}while(!this._isPermanentFailure&&!this._isDisposed)}_onReconnectionPermanentFailure(e,t,n){this._reconnectionFailureIsFatal?o.triggerPermanentFailure(e,t,n):this._gotoPermanentFailure(e,t,n)}_gotoPermanentFailure(e,t,n){this._onDidStateChange.fire(new wv(this.reconnectionToken,e,t,n)),e1(this.protocol)}_pauseSocketWriting(){this.protocol.pauseSocketWriting()}};function e1(o){try{o.acceptDisconnect();let r=o.getSocket();o.dispose(),r.dispose()}catch(r){Me(r)}}function jR(o){if(o&&o.type==="error"){let r=new Error(`Connection error: ${o.reason}`);return r.code="VSCODE_CONNECTION_ERROR",r}return null}function HR(o,r){return typeof o!="number"||!isFinite(o)||o<0?r:o>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Math.floor(o)}function JR(o,r){for(;o.length<r;)o+=" ";return o}function QR(o,r){return`[remote-connection][${JR(Iv(o),13)}][${r.substr(0,5)}\u2026]`}function Ac(o,r,e){return`${QR(o,r)}[${e?"reconnect":"initial"}]`}function t1(o,r){return`${Ac(r,o.reconnectionToken,!!o.reconnectionProtocol)}[${o.connectTo}]`}function XR(o){return`${Date.now()-o} ms`}var Oa=L("remoteSocketFactoryService"),Df=class{constructor(){this.factories={}}register(r,e){return this.factories[r]??=[],this.factories[r].push(e),oe(()=>{let t=this.factories[r]?.indexOf(e);typeof t=="number"&&t>=0&&this.factories[r]?.splice(t,1)})}getSocketFactory(r){return(this.factories[r.type]||[]).find(t=>t.supports(r))}connect(r,e,t,n){let i=this.getSocketFactory(r);if(!i)throw new Error(`No socket factory found for ${r}`);return i.connect(r,e,t,n)}};async function YR(o,r,e,t,n){let i;for(let s=3;s&&(i?.dispose(),i=await new Pv(o,r,e,t,n).waitForReady(),!(n&&mv[n]||!mv[i.tunnelLocalPort]));s--);return i}var Pv=class extends T{constructor(e,t,n,i,s){super();this.defaultTunnelHost=t;this.suggestedLocalPort=s;this.privacy="private";this._socketsDispose=new Map;this._options=e,this._server=r1.createServer(),this._barrier=new Kr,this._listeningListener=()=>this._barrier.open(),this._server.on("listening",this._listeningListener),this._connectionListener=a=>this._onConnection(a),this._server.on("connection",this._connectionListener),this._errorListener=()=>{},this._server.on("error",this._errorListener),this.tunnelRemotePort=i,this.tunnelRemoteHost=n}async dispose(){super.dispose(),this._server.removeListener("listening",this._listeningListener),this._server.removeListener("connection",this._connectionListener),this._server.removeListener("error",this._errorListener),this._server.close(),Array.from(this._socketsDispose.values()).forEach(t=>{t()})}async waitForReady(){let e=this.suggestedLocalPort??this.tunnelRemotePort,t=Aa(this.defaultTunnelHost)?"0.0.0.0":"127.0.0.1",n=await Hx(e,2,1e3,t),i=null;return this._server.listen(n,this.defaultTunnelHost),await this._barrier.wait(),i=this._server.address(),i||(n=0,this._server.listen(n,this.defaultTunnelHost),await this._barrier.wait(),i=this._server.address()),this.tunnelLocalPort=i.port,this.localAddress=`${this.tunnelRemoteHost==="127.0.0.1"?"127.0.0.1":"localhost"}:${i.port}`,this}async _onConnection(e){e.pause();let t=bf(this.tunnelRemoteHost)||Aa(this.tunnelRemoteHost)?"localhost":this.tunnelRemoteHost,n=await Zx(this._options,t,this.tunnelRemotePort),i=n.getSocket(),s=n.readEntireBuffer();n.dispose(),s.byteLength>0&&e.write(s.buffer),e.on("end",()=>{e.localAddress&&this._socketsDispose.delete(e.localAddress),i.end()}),e.on("close",()=>i.end()),e.on("error",()=>{e.localAddress&&this._socketsDispose.delete(e.localAddress),i instanceof Do?i.socket.destroy():i.end()}),i instanceof Do?this._mirrorNodeSocket(e,i):this._mirrorGenericSocket(e,i),e.localAddress&&this._socketsDispose.set(e.localAddress,()=>{e.end(),i.end()})}_mirrorGenericSocket(e,t){t.onClose(()=>e.destroy()),t.onEnd(()=>e.end()),t.onData(n=>e.write(n.buffer)),e.on("data",n=>t.write(U.wrap(n))),e.resume()}_mirrorNodeSocket(e,t){let n=t.socket;n.on("end",()=>e.end()),n.on("close",()=>e.end()),n.on("error",()=>{e.destroy()}),n.pipe(e),e.pipe(n)}},Oc=class extends Ma{constructor(e,t,n,i,s){super(t,s);this.remoteSocketFactoryService=e;this.signService=n;this.productService=i}isPortPrivileged(e){return jx(e,this.defaultTunnelHost,bn,n1.release())}retainOrCreateTunnel(e,t,n,i,s,a,l,c){let d=this.getTunnelFromMap(t,n);if(d)return++d.refcount,d.value;if(Kx(e))return this.createWithProvider(e,t,n,s,a,l,c);{this.logService.trace(`ForwardedPorts: (TunnelService) Creating tunnel without provider ${t}:${n} on local port ${s}.`);let u={commit:this.productService.commit,quality:this.productService.quality,addressProvider:e,remoteSocketFactoryService:this.remoteSocketFactoryService,signService:this.signService,logService:this.logService,ipcLogger:null},p=YR(u,i,t,n,s);return this.logService.trace("ForwardedPorts: (TunnelService) Tunnel created without provider."),this.addTunnelToMap(t,n,p),p}}};Oc=b([g(0,Oa),g(1,V),g(2,La),g(3,ne),g(4,Q)],Oc);var Nc=class extends Oc{constructor(r,e,t,n,i){super(r,e,t,n,i)}};Nc=b([g(0,Oa),g(1,V),g(2,La),g(3,ne),g(4,Q)],Nc);var Na=class extends T{constructor(e,t,n,i,s){super();this.remoteSocketFactoryService=e;this.logService=t;this.productService=n;this.signService=i;this.configurationService=s;this._tunnelServices=new Map}async openTunnel(e,t,n,i,s,a,l,c,d){if(this.logService.trace(`ForwardedPorts: (SharedTunnelService) openTunnel request for ${n}:${i} on local port ${a}.`),!this._tunnelServices.has(e)){let u=new Nc(this.remoteSocketFactoryService,this.logService,this.signService,this.productService,this.configurationService);this._register(u),this._tunnelServices.set(e,u),u.onTunnelClosed(async()=>{(await u.tunnels).length===0&&(u.dispose(),this._tunnelServices.delete(e))})}return this._tunnelServices.get(e).openTunnel(t,n,i,s,a,l,c,d)}};Na=b([g(0,Oa),g(1,V),g(2,ne),g(3,La),g(4,Q)],Na);var Rv=L("sharedProcessTunnelService"),i1="sharedProcessTunnel";var Tv=class extends T{constructor(){super(),this._address=null,this._addressPromise=null}async getAddress(){return this._address?this._address:(this._addressPromise||(this._addressPromise=new Ur),this._addressPromise.p)}setAddress(r){this._address=r,this._addressPromise&&(this._addressPromise.complete(r),this._addressPromise=null)}setTunnel(r){this._register(r)}},Fi=class extends T{constructor(e,t){super();this._tunnelService=e;this._logService=t;this._tunnels=new Map;this._disposedTunnels=new Set}static{this._lastId=0}dispose(){super.dispose(),this._tunnels.forEach(e=>e.dispose())}async createTunnel(){return{id:String(++Fi._lastId)}}async startTunnel(e,t,n,i,s,a,l){let c=new Tv,d=await Promise.resolve(this._tunnelService.openTunnel(e,c,n,i,s,a,l));if(!d||typeof d=="string")throw this._logService.info(`[SharedProcessTunnelService] Could not create a tunnel to ${n}:${i} (remote).`),c.dispose(),new Error("Could not create tunnel");if(this._disposedTunnels.delete(t))throw c.dispose(),await d.dispose(),Yn();return c.setTunnel(d),this._tunnels.set(t,c),this._logService.info(`[SharedProcessTunnelService] Created tunnel ${t}: ${d.localAddress} (local) to ${n}:${i} (remote).`),{tunnelLocalPort:d.tunnelLocalPort,localAddress:d.localAddress}}async setAddress(e,t){let n=this._tunnels.get(e);n&&n.setAddress(t)}async destroyTunnel(e){let t=this._tunnels.get(e);if(t){this._logService.info(`[SharedProcessTunnelService] Disposing tunnel ${e}.`),this._tunnels.delete(e),await t.dispose();return}this._disposedTunnels.add(e)}};Fi=b([g(0,xf),g(1,V)],Fi);var ZR=[];function _f(o,r,e){r instanceof Se||(r=new Se(r,[],!!e)),ZR.push([o,r])}var kf=class o{constructor(r){this.uri=r;this.time=o._clock++}static{this._clock=0}touch(){return this.time=o._clock++,this}},_o=class{constructor(r){this._fileService=r;this._dispooables=new se;this._limit=2**16;let e=new Map,t=n=>{let i=e.get(n.scheme);return i===void 0&&(i=r.hasProvider(n)&&!this._fileService.hasCapability(n,1024),e.set(n.scheme,i)),i};this._dispooables.add(k.any(r.onDidChangeFileSystemProviderRegistrations,r.onDidChangeFileSystemProviderCapabilities)(n=>{if(e.get(n.scheme)===void 0)return;e.delete(n.scheme);let s=t(P.from({scheme:n.scheme}));if(s!==s)for(let[a,l]of this._canonicalUris.entries())l.uri.scheme===n.scheme&&this._canonicalUris.delete(a)})),this.extUri=new Qi(t),this._canonicalUris=new Map}dispose(){this._dispooables.dispose(),this._canonicalUris.clear()}asCanonicalUri(r){this._fileService.hasProvider(r)&&(r=DS(r));let e=this.extUri.getComparisonKey(r,!0),t=this._canonicalUris.get(e);return t?t.touch().uri.with({fragment:r.fragment}):(this._canonicalUris.set(e,new kf(r)),this._checkTrim(),r)}_checkTrim(){if(this._canonicalUris.size<this._limit)return;kf._clock=1;let r=[...this._canonicalUris.values()].map(t=>t.time),e=ed(Math.floor(r.length/2),r,(t,n)=>t-n);for(let[t,n]of this._canonicalUris.entries())n.time<=e?this._canonicalUris.delete(t):n.time=0}};_o=b([g(0,W)],_o);_f(te,_o,1);var Uf=class extends T{constructor(e,t,n,i,s,a){super();this.fileSystemScheme=e;this.fileSystemProvider=t;this.userDataScheme=n;this.userDataProfilesService=i;this.uriIdentityService=s;this.logService=a;this.capabilities=this.fileSystemProvider.capabilities,this.onDidChangeCapabilities=this.fileSystemProvider.onDidChangeCapabilities,this._onDidChangeFile=this._register(new w),this.onDidChangeFile=this._onDidChangeFile.event,this.watchResources=Mr.forUris(()=>!(this.capabilities&1024)),this.atomicReadWriteResources=new ei(l=>this.uriIdentityService.extUri.getComparisonKey(this.toFileSystemResource(l))),this.updateAtomicReadWritesResources(),this._register(i.onDidChangeProfiles(()=>this.updateAtomicReadWritesResources())),this._register(this.fileSystemProvider.onDidChangeFile(l=>this.handleFileChanges(l)))}updateAtomicReadWritesResources(){this.atomicReadWriteResources.clear();for(let e of this.userDataProfilesService.profiles)this.atomicReadWriteResources.add(e.settingsResource),this.atomicReadWriteResources.add(e.keybindingsResource),this.atomicReadWriteResources.add(e.tasksResource),this.atomicReadWriteResources.add(e.extensionsResource)}open(e,t){return this.fileSystemProvider.open(this.toFileSystemResource(e),t)}close(e){return this.fileSystemProvider.close(e)}read(e,t,n,i,s){return this.fileSystemProvider.read(e,t,n,i,s)}write(e,t,n,i,s){return this.fileSystemProvider.write(e,t,n,i,s)}watch(e,t){this.watchResources.set(e,e);let n=this.fileSystemProvider.watch(this.toFileSystemResource(e),t);return oe(()=>{this.watchResources.delete(e),n.dispose()})}stat(e){return this.fileSystemProvider.stat(this.toFileSystemResource(e))}mkdir(e){return this.fileSystemProvider.mkdir(this.toFileSystemResource(e))}rename(e,t,n){return this.fileSystemProvider.rename(this.toFileSystemResource(e),this.toFileSystemResource(t),n)}readFile(e,t){return this.fileSystemProvider.readFile(this.toFileSystemResource(e),t)}readFileStream(e,t,n){return this.fileSystemProvider.readFileStream(this.toFileSystemResource(e),t,n)}readdir(e){return this.fileSystemProvider.readdir(this.toFileSystemResource(e))}enforceAtomicReadFile(e){return this.atomicReadWriteResources.has(e)}writeFile(e,t,n){return this.fileSystemProvider.writeFile(this.toFileSystemResource(e),t,n)}enforceAtomicWriteFile(e){return this.atomicReadWriteResources.has(e)?{postfix:".vsctmp"}:!1}delete(e,t){return this.fileSystemProvider.delete(this.toFileSystemResource(e),t)}copy(e,t,n){if(Xl(this.fileSystemProvider))return this.fileSystemProvider.copy(this.toFileSystemResource(e),this.toFileSystemResource(t),n);throw new Error("copy not supported")}cloneFile(e,t){if(cu(this.fileSystemProvider))return this.fileSystemProvider.cloneFile(this.toFileSystemResource(e),this.toFileSystemResource(t));throw new Error("clone not supported")}handleFileChanges(e){let t=[];for(let n of e){if(n.resource.scheme!==this.fileSystemScheme)continue;let i=this.toUserDataResource(n.resource);this.watchResources.findSubstr(i)&&t.push({resource:i,type:n.type,cId:n.cId})}t.length&&(this.logService.debug("User data changed"),this._onDidChangeFile.fire(t))}toFileSystemResource(e){return e.with({scheme:this.fileSystemScheme})}toUserDataResource(e){return e.with({scheme:this.userDataScheme})}};var o1="localFilesystem",Lf=class extends T{constructor(e,t){super();this.channel=e;this.extraCapabilities=t;this.onDidChangeCapabilities=k.None;this._onDidChange=this._register(new w);this.onDidChangeFile=this._onDidChange.event;this._onDidWatchError=this._register(new w);this.onDidWatchError=this._onDidWatchError.event;this.sessionId=Le();this.registerFileChangeListeners()}get capabilities(){return this._capabilities||(this._capabilities=1040414,this.extraCapabilities.pathCaseSensitive&&(this._capabilities|=1024),this.extraCapabilities.trash&&(this._capabilities|=4096)),this._capabilities}stat(e){return this.channel.call("stat",[e])}realpath(e){return this.channel.call("realpath",[e])}readdir(e){return this.channel.call("readdir",[e])}async readFile(e,t){let{buffer:n}=await this.channel.call("readFile",[e,t]);return n}readFileStream(e,t,n){let i=Vn(a=>U.concat(a.map(l=>U.wrap(l))).buffer),s=new se;return s.add(this.channel.listen("readFileStream",[e,t])(a=>{if(a instanceof U)i.write(a.buffer);else{if(a==="end")i.end();else{let l;if(a instanceof Error)l=a;else{let c=a;l=Fr(c.message??_t(c),c.code??"Unknown")}i.error(l),i.end()}s.dispose()}})),s.add(n.onCancellationRequested(()=>{i.error(Yn()),i.end(),s.dispose()})),i}writeFile(e,t,n){return this.channel.call("writeFile",[e,U.wrap(t),n])}open(e,t){return this.channel.call("open",[e,t])}close(e){return this.channel.call("close",[e])}async read(e,t,n,i,s){let[a,l]=await this.channel.call("read",[e,t,s]);return n.set(a.buffer.slice(0,l),i),l}write(e,t,n,i,s){return this.channel.call("write",[e,t,U.wrap(n),i,s])}mkdir(e){return this.channel.call("mkdir",[e])}delete(e,t){return this.channel.call("delete",[e,t])}rename(e,t,n){return this.channel.call("rename",[e,t,n])}copy(e,t,n){return this.channel.call("copy",[e,t,n])}cloneFile(e,t){return this.channel.call("cloneFile",[e,t])}registerFileChangeListeners(){this._register(this.channel.listen("fileChange",[this.sessionId])(e=>{if(Array.isArray(e)){let t=e;this._onDidChange.fire(Ic(t))}else{let t=e;this._onDidWatchError.fire(t)}}))}watch(e,t){let n=Le();return this.channel.call("watch",[this.sessionId,n,e,t]),oe(()=>this.channel.call("unwatch",[this.sessionId,n]))}};var Mf=class{constructor(){this._sessions=new Map}async startProfiling(r){let t=await(await import("v8-inspect-profiler")).startProfiling({host:r.host,port:r.port,checkForPaused:!0}),n=Le();return this._sessions.set(n,t),n}async stopProfiling(r){let e=this._sessions.get(r);if(!e)throw new Error(`UNKNOWN session '${r}'`);let t=await e.stop();return this._sessions.delete(r),t.profile}};var Cv=L("IV8InspectProfilingService"),tT;(e=>{function o(t){return!!(t.samples&&t.timeDeltas)}e.isValidProfile=o;function r(t,n="noAbsolutePaths"){for(let i of t.nodes)i.callFrame&&i.callFrame.url&&(Zo(i.callFrame.url)||/^\w[\w\d+.-]*:\/\/\/?/.test(i.callFrame.url))&&(i.callFrame.url=G(n,lt(i.callFrame.url)));return t}e.rewriteAbsolutePaths=r})(tT||={});var Va=class extends fp{constructor(r,e,t,n,i,s,a,l){super(P.file(i.builtinExtensionsPath),P.file(i.extensionsPath),i.userHome,r.defaultProfile,r,e,t,n,i,s,a,l)}};Va=b([g(0,fe),g(1,Qr),g(2,W),g(3,V),g(4,nt),g(5,ne),g(6,te),g(7,bt)],Va);var Af=class extends Cu{constructor(e,t){super();this.channel=t;for(let n in e){let{definition:i,value:s}=e[n];this.policyDefinitions[n]=i,s!==void 0&&this.policies.set(n,s)}this.channel.listen("onDidChange")(n=>{for(let i in n){let s=n[i];s===null?this.policies.delete(i):this.policies.set(i,s)}this._onDidChange.fire(Object.keys(n))})}async _updatePolicyDefinitions(e){let t=await this.channel.call("updatePolicyDefinitions",e);for(let n in t)this.policies.set(n,t[n])}};var Ff=class extends T{constructor(e,t,n){super();this.profilesHome=t;this.channel=n;this._profiles=[];this._onDidChangeProfiles=this._register(new w);this.onDidChangeProfiles=this._onDidChangeProfiles.event;this._profiles=e.map(i=>nr(i,this.profilesHome.scheme)),this._register(this.channel.listen("onDidChangeProfiles")(i=>{let s=i.added.map(c=>nr(c,this.profilesHome.scheme)),a=i.removed.map(c=>nr(c,this.profilesHome.scheme)),l=i.updated.map(c=>nr(c,this.profilesHome.scheme));this._profiles=i.all.map(c=>nr(c,this.profilesHome.scheme)),this._onDidChangeProfiles.fire({added:s,removed:a,updated:l,all:this.profiles})})),this.onDidResetWorkspaces=this.channel.listen("onDidResetWorkspaces")}get defaultProfile(){return this.profiles[0]}get profiles(){return this._profiles}async createNamedProfile(e,t,n){let i=await this.channel.call("createNamedProfile",[e,t,n]);return nr(i,this.profilesHome.scheme)}async createProfile(e,t,n,i){let s=await this.channel.call("createProfile",[e,t,n,i]);return nr(s,this.profilesHome.scheme)}async createTransientProfile(e){let t=await this.channel.call("createTransientProfile",[e]);return nr(t,this.profilesHome.scheme)}async setProfileForWorkspace(e,t){await this.channel.call("setProfileForWorkspace",[e,t])}removeProfile(e){return this.channel.call("removeProfile",[e])}async updateProfile(e,t){let n=await this.channel.call("updateProfile",[e,t]);return nr(n,this.profilesHome.scheme)}resetWorkspaces(){return this.channel.call("resetWorkspaces")}cleanUp(){return this.channel.call("cleanUp")}cleanUpTransientProfiles(){return this.channel.call("cleanUpTransientProfiles")}};import*as sT from"@microsoft/1ds-core-js";import*as aT from"@microsoft/1ds-post-js";var rT=!1,_v=class{constructor(r,e,t){this.id=r;this.dependencies=e;this.callback=t}};var kv=class o{constructor(){this._isWebWorker=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope";this._isRenderer=typeof document=="object";this._defineCalls=[];this._state=1}static{this.INSTANCE=new o}_initialize(){if(this._state===1){if(globalThis.define){this._state=3;return}}else return;this._state=2,globalThis.define=(r,e,t)=>{typeof r!="string"&&(t=e,e=r,r=null),(typeof e!="object"||!Array.isArray(e))&&(t=e,e=null),this._defineCalls.push(new _v(r,e,t))},globalThis.define.amd=!0,this._isRenderer?this._amdPolicy=globalThis._VSCODE_WEB_PACKAGE_TTP??window.trustedTypes?.createPolicy("amdLoader",{createScriptURL(r){if(r.startsWith(window.location.origin)||r.startsWith(`${re.vscodeFileResource}://${Bm}`))return r;throw new Error(`[trusted_script_src] Invalid script url: ${r}`)}}):this._isWebWorker&&(this._amdPolicy=globalThis._VSCODE_WEB_PACKAGE_TTP??globalThis.trustedTypes?.createPolicy("amdLoader",{createScriptURL(r){return r}}))}async load(r){if(this._initialize(),this._state===3)return new Promise(s=>{let a=Le();globalThis.define(a,[r],function(l){s(l)})});let e=await(this._isWebWorker?this._workerLoadScript(r):this._isRenderer?this._rendererLoadScript(r):this._nodeJSLoadScript(r));if(!e){console.warn(`Did not receive a define call from script ${r}`);return}let t={},n=[],i=[];if(Array.isArray(e.dependencies))for(let s of e.dependencies)s==="exports"?n.push(t):i.push(s);if(i.length>0)throw new Error(`Cannot resolve dependencies for script ${r}. The dependencies are: ${i.join(", ")}`);return typeof e.callback=="function"?e.callback(...n)??t:e.callback}_rendererLoadScript(r){return new Promise((e,t)=>{let n=document.createElement("script");n.setAttribute("async","async"),n.setAttribute("type","text/javascript");let i=()=>{n.removeEventListener("load",s),n.removeEventListener("error",a)},s=l=>{i(),e(this._defineCalls.pop())},a=l=>{i(),t(l)};n.addEventListener("load",s),n.addEventListener("error",a),this._amdPolicy&&(r=this._amdPolicy.createScriptURL(r)),n.setAttribute("src",r),window.document.getElementsByTagName("head")[0].appendChild(n)})}async _workerLoadScript(r){return this._amdPolicy&&(r=this._amdPolicy.createScriptURL(r)),await import(r),this._defineCalls.pop()}async _nodeJSLoadScript(r){try{let e=(await import("fs")).default,t=(await import("vm")).default,n=(await import("module")).default,i=P.parse(r).fsPath,s=e.readFileSync(i).toString(),a=n.wrap(s.replace(/^#!.*/,""));return new t.Script(a).runInThisContext().apply(),this._defineCalls.pop()}catch(e){throw e}}},Dv=new Map;async function Uv(o,r,e){e===void 0&&(e=!!(globalThis._VSCODE_PRODUCT_JSON??globalThis.vscode?.context?.configuration()?.product)?.commit);let t=r?`${o}/${r}`:o;if(Dv.has(t))return Dv.get(t);let n;if(/^\w[\w\d+.-]*:\/\//.test(t))n=t;else{let l=`${rT&&e&&!ze?bS:IS}/${t}`;n=dr.asBrowserUri(l).toString(!0)}let i=kv.INSTANCE.load(n);return Dv.set(t,i),i}async function nT(){let o=ze?await Uv("@microsoft/1ds-core-js","bundle/ms.core.min.js"):await import("@microsoft/1ds-core-js"),r=ze?await Uv("@microsoft/1ds-post-js","bundle/ms.post.min.js"):await import("@microsoft/1ds-post-js");return{oneDs:o,postPlugin:r}}var s1="https://windsurf-telemetry.codeium.com/telemetry",iT="https://windsurf-telemetry.codeium.com/ping";async function oT(o,r,e,t){let n=new o.oneDs.AppInsightsCore,i=new o.postPlugin.PostChannel,s={instrumentationKey:r,endpointUrl:s1,loggingLevelTelemetry:0,loggingLevelConsole:0,disableCookiesUsage:!0,disableDbgExt:!0,disableInstrumentationKeyValidation:!0,channels:[[i]]};if(t){s.extensionConfig={};let a={alwaysUseXhrOverride:!0,ignoreMc1Ms0CookieProcessing:!0,httpXHROverride:t};s.extensionConfig[i.identifier]=a}return n.initialize(s,[]),n.addTelemetryInitializer(a=>{a.ext=a.ext??{},a.ext.web=a.ext.web??{},a.ext.web.consentDetails='{"GPC_DataSharingOptIn":false}',e&&(a.ext.utc=a.ext.utc??{},a.ext.utc.flags=8462029)}),n}var Of=class{constructor(r,e,t,n,i,s=nT){this._isInternalTelemetry=r;this._eventPrefix=e;this._defaultData=t;this._xhrOverride=i;this._loadModules=s;this.endPointUrl=s1;this.endPointHealthUrl=iT;this._defaultData||(this._defaultData={}),typeof n=="function"?this._aiCoreOrKey=n():this._aiCoreOrKey=n,this._asyncAiCore=null}_withAIClient(r){if(this._aiCoreOrKey){if(typeof this._aiCoreOrKey!="string"){r(this._aiCoreOrKey);return}if(!this._asyncAiCore){let e=this._aiCoreOrKey;this._asyncAiCore=this._loadModules().then(t=>oT(t,e,this._isInternalTelemetry,this._xhrOverride))}this._asyncAiCore.then(e=>{r(e)},e=>{Me(e),console.error(e)})}}log(r,e){if(!this._aiCoreOrKey)return;e=ks(e,this._defaultData);let t=$u(e),n=this._eventPrefix+"/"+r;try{this._withAIClient(i=>{i.pluginVersionString=t?.properties.version??"Unknown",i.track({name:n,baseData:{name:n,properties:t?.properties,measurements:t?.measurements}})})}catch{}}flush(){return this._aiCoreOrKey?new Promise(r=>{this._withAIClient(e=>{e.unload(!0,()=>{this._aiCoreOrKey=void 0,r(void 0)})})}):Promise.resolve(void 0)}};var lT={oneDs:sT,postPlugin:aT},cT=Promise.resolve(lT);async function dT(o,r){let e=await r.request(o,Y.None),t=(await En(e.stream)).toString(),n=e.res.statusCode??200;return{headers:e.res.headers,statusCode:n,responseData:t}}async function uT(o){let r=await import("https"),e={method:o.type,headers:o.headers};return new Promise((n,i)=>{let s=r.request(o.url??"",e,a=>{a.on("data",function(l){n({headers:a.headers,statusCode:a.statusCode??200,responseData:l.toString()})}),a.on("error",function(l){i(l)})});s.write(o.data,a=>{a&&i(a)}),s.end()})}async function pT(o,r,e){let t=typeof r.data=="string"?r.data:new TextDecoder().decode(r.data),n={type:"POST",headers:{...r.headers,"Content-Type":"application/json","Content-Length":Buffer.byteLength(r.data).toString()},url:r.urlString,data:t};try{let i=o?await dT(n,o):await uT(n);e(i.statusCode,i.headers,i.responseData)}catch{e(0,{})}}var Nf=class extends Of{constructor(r,e,t,n,i){let s={sendPOST:(a,l)=>{pT(r,a,l)}};super(e,t,n,i,s,()=>cT)}};var Wa=class extends T{constructor(r){super(),this._register(new It(()=>{r.cleanUp()},10*1e3)).schedule()}};Wa=b([g(0,fe)],Wa);var Lv=L("IRemoteTunnelService"),Vc={active:!1},or;(n=>(n.disconnected=i=>({type:"disconnected",onTokenFailed:i}),n.connected=(i,s)=>({type:"connected",info:i,serviceInstallFailed:s}),n.connecting=i=>({type:"connecting",progress:i}),n.uninitialized={type:"uninitialized"}))(or||={});var a1="remote.tunnels.access",Mv=a1+".hostNameOverride",Av=a1+".preventSleep",Fv="remoteTunnelService",l1=S(2268,null);var Nt=class{constructor(r,e,t,n,i,s,a,l,c,d){this.userDataSyncStoreService=r;this.userDataSyncLocalStoreService=e;this.logService=t;this.environmentService=i;this.storageService=s;this.fileService=a;this.userDataProfilesService=l;this.configurationService=c;this.instantiationService=d;this.extUri=n.extUri}static{this.NOT_EXISTING_RESOURCE="not-existing-resource"}static{this.REMOTE_BACKUP_AUTHORITY="remote-backup"}static{this.LOCAL_BACKUP_AUTHORITY="local-backup"}async getRemoteSyncedProfiles(){let r=await this.userDataSyncStoreService.readResource("profiles",null,void 0);if(r.content){let e=this.parseSyncData(r.content,"profiles");return Ui(e)}return[]}async getLocalSyncedProfiles(r){let e=await this.userDataSyncLocalStoreService.getAllResourceRefs("profiles",void 0,r);if(e.length){let t=await this.userDataSyncLocalStoreService.resolveResourceContent("profiles",e[0].ref,void 0,r);if(t){let n=this.parseSyncData(t,"profiles");return Ui(n)}}return[]}async getLocalSyncedMachines(r){let e=await this.userDataSyncLocalStoreService.getAllResourceRefs("machines",void 0,r);if(e.length){let t=await this.userDataSyncLocalStoreService.resolveResourceContent("machines",e[0].ref,void 0,r);if(t)return JSON.parse(t).machines.map(i=>({...i,isCurrent:!1}))}return[]}async getRemoteSyncResourceHandles(r,e){return(await this.userDataSyncStoreService.getAllResourceRefs(r,e?.collection)).map(({created:n,ref:i})=>({created:n,uri:this.toUri({remote:!0,syncResource:r,profile:e?.id??this.userDataProfilesService.defaultProfile.id,location:void 0,collection:e?.collection,ref:i,node:void 0})}))}async getLocalSyncResourceHandles(r,e,t){return(await this.userDataSyncLocalStoreService.getAllResourceRefs(r,e?.collection,t)).map(({created:i,ref:s})=>({created:i,uri:this.toUri({remote:!1,syncResource:r,profile:e?.id??this.userDataProfilesService.defaultProfile.id,collection:e?.collection,ref:s,node:void 0,location:t})}))}resolveUserDataSyncResource({uri:r}){let e=this.resolveUri(r),t=e?this.userDataProfilesService.profiles.find(n=>n.id===e.profile):void 0;return e&&t?{profile:t,syncResource:e?.syncResource}:void 0}async getAssociatedResources({uri:r}){let e=this.resolveUri(r);if(!e)return[];let t=this.userDataProfilesService.profiles.find(n=>n.id===e.profile);switch(e.syncResource){case"settings":return this.getSettingsAssociatedResources(r,t);case"keybindings":return this.getKeybindingsAssociatedResources(r,t);case"tasks":return this.getTasksAssociatedResources(r,t);case"mcp":return this.getMcpAssociatedResources(r,t);case"snippets":return this.getSnippetsAssociatedResources(r,t);case"prompts":return this.getPromptsAssociatedResources(r,t);case"globalState":return this.getGlobalStateAssociatedResources(r,t);case"extensions":return this.getExtensionsAssociatedResources(r,t);case"profiles":return this.getProfilesAssociatedResources(r,t);case"workspaceState":return[]}}async getMachineId({uri:r}){let e=this.resolveUri(r);if(e){if(e.remote){if(e.ref){let{content:t}=await this.getUserData(e.syncResource,e.ref,e.collection);if(t)return this.parseSyncData(t,e.syncResource)?.machineId}return}if(e.location){if(e.ref){let t=await this.userDataSyncLocalStoreService.resolveResourceContent(e.syncResource,e.ref,e.collection,e.location);if(t)return this.parseSyncData(t,e.syncResource)?.machineId}return}return Hr(this.environmentService,this.fileService,this.storageService)}}async resolveContent(r){let e=this.resolveUri(r);if(!e||e.node===Nt.NOT_EXISTING_RESOURCE)return null;if(e.ref){let t=await this.getContentFromStore(e.remote,e.syncResource,e.collection,e.ref,e.location);return e.node&&t?this.resolveNodeContent(e.syncResource,t,e.node):t}return!e.remote&&!e.node?this.resolveLatestContent(e.syncResource,e.profile):null}async getContentFromStore(r,e,t,n,i){if(r){let{content:s}=await this.getUserData(e,n,t);return s}return this.userDataSyncLocalStoreService.resolveResourceContent(e,n,t,i)}resolveNodeContent(r,e,t){let n=this.parseSyncData(e,r);switch(r){case"settings":return this.resolveSettingsNodeContent(n,t);case"keybindings":return this.resolveKeybindingsNodeContent(n,t);case"tasks":return this.resolveTasksNodeContent(n,t);case"mcp":return this.resolveMcpNodeContent(n,t);case"snippets":return this.resolveSnippetsNodeContent(n,t);case"prompts":return this.resolvePromptsNodeContent(n,t);case"globalState":return this.resolveGlobalStateNodeContent(n,t);case"extensions":return this.resolveExtensionsNodeContent(n,t);case"profiles":return this.resolveProfileNodeContent(n,t);case"workspaceState":return null}}async resolveLatestContent(r,e){let t=this.userDataProfilesService.profiles.find(n=>n.id===e);if(!t)return null;switch(r){case"globalState":return this.resolveLatestGlobalStateContent(t);case"extensions":return this.resolveLatestExtensionsContent(t);case"profiles":return this.resolveLatestProfilesContent(t);case"settings":return null;case"keybindings":return null;case"tasks":return null;case"mcp":return null;case"snippets":return null;case"prompts":return null;case"workspaceState":return null}}getSettingsAssociatedResources(r,e){let t=this.extUri.joinPath(r,"settings.json"),n=e?e.settingsResource:this.extUri.joinPath(r,Nt.NOT_EXISTING_RESOURCE);return[{resource:t,comparableResource:n}]}resolveSettingsNodeContent(r,e){return e==="settings.json"?lf(r.content).settings:null}getKeybindingsAssociatedResources(r,e){let t=this.extUri.joinPath(r,"keybindings.json"),n=e?e.keybindingsResource:this.extUri.joinPath(r,Nt.NOT_EXISTING_RESOURCE);return[{resource:t,comparableResource:n}]}resolveKeybindingsNodeContent(r,e){return e==="keybindings.json"?Uc(r.content,!!this.configurationService.getValue(wc),this.logService):null}getTasksAssociatedResources(r,e){let t=this.extUri.joinPath(r,"tasks.json"),n=e?e.tasksResource:this.extUri.joinPath(r,Nt.NOT_EXISTING_RESOURCE);return[{resource:t,comparableResource:n}]}resolveTasksNodeContent(r,e){return e==="tasks.json"?ff(r.content,this.logService):null}async getSnippetsAssociatedResources(r,e){let t=await this.resolveContent(r);if(t){let n=this.parseSyncData(t,"snippets");if(n){let i=uf(n),s=[];for(let a of Object.keys(i)){let l=this.extUri.joinPath(r,a),c=e?this.extUri.joinPath(e.snippetsHome,a):this.extUri.joinPath(r,Nt.NOT_EXISTING_RESOURCE);s.push({resource:l,comparableResource:c})}return s}}return[]}resolveSnippetsNodeContent(r,e){return uf(r)[e]||null}async getPromptsAssociatedResources(r,e){let t=await this.resolveContent(r);if(t){let n=this.parseSyncData(t,"prompts");if(n){let i=tf(n),s=[];for(let a of Object.keys(i)){let l=this.extUri.joinPath(r,a),c=e?this.extUri.joinPath(e.promptsHome,a):this.extUri.joinPath(r,Nt.NOT_EXISTING_RESOURCE);s.push({resource:l,comparableResource:c})}return s}}return[]}resolvePromptsNodeContent(r,e){return tf(r)[e]||null}getExtensionsAssociatedResources(r,e){let t=this.extUri.joinPath(r,"extensions.json"),n=e?this.toUri({remote:!1,syncResource:"extensions",profile:e.id,location:void 0,collection:void 0,ref:void 0,node:void 0}):this.extUri.joinPath(r,Nt.NOT_EXISTING_RESOURCE);return[{resource:t,comparableResource:n}]}resolveExtensionsNodeContent(r,e){return e==="extensions.json"?Jp(Vx(r),!0):null}async resolveLatestExtensionsContent(r){let{localExtensions:e}=await this.instantiationService.createInstance(wo).getLocalExtensions(r);return Jp(e,!0)}getGlobalStateAssociatedResources(r,e){let t=this.extUri.joinPath(r,"globalState.json"),n=e?this.toUri({remote:!1,syncResource:"globalState",profile:e.id,location:void 0,collection:void 0,ref:void 0,node:void 0}):this.extUri.joinPath(r,Nt.NOT_EXISTING_RESOURCE);return[{resource:t,comparableResource:n}]}resolveGlobalStateNodeContent(r,e){return e==="globalState.json"?_i(JSON.parse(r.content),!0):null}async resolveLatestGlobalStateContent(r){let e=await this.instantiationService.createInstance(Po).getLocalGlobalState(r);return _i(e,!0)}getProfilesAssociatedResources(r,e){let t=this.extUri.joinPath(r,"profiles.json"),n=this.toUri({remote:!1,syncResource:"profiles",profile:this.userDataProfilesService.defaultProfile.id,location:void 0,collection:void 0,ref:void 0,node:void 0});return[{resource:t,comparableResource:n}]}resolveProfileNodeContent(r,e){return e==="profiles.json"?zn(JSON.parse(r.content),{}):null}async resolveLatestProfilesContent(r){return mf(this.userDataProfilesService.profiles.filter(e=>!e.isDefault&&!e.isTransient),!0)}toUri(r){let e=r.remote?Nt.REMOTE_BACKUP_AUTHORITY:Nt.LOCAL_BACKUP_AUTHORITY,t=[];return r.location&&(t.push(`scheme:${r.location.scheme}`),t.push(`authority:${r.location.authority}`),t.push(lS(r.location.path,"/"))),t.push(`syncResource:${r.syncResource}`),t.push(`profile:${r.profile}`),r.collection&&t.push(`collection:${r.collection}`),r.ref&&t.push(`ref:${r.ref}`),r.node&&t.push(r.node),this.extUri.joinPath(P.from({scheme:M,authority:e,path:"/",query:r.location?.query,fragment:r.location?.fragment}),...t)}resolveUri(r){if(r.scheme!==M)return;let e=[];for(;r.path!=="/";)e.unshift(this.extUri.basename(r)),r=this.extUri.dirname(r);if(e.length<2)return;let t=r.authority===Nt.REMOTE_BACKUP_AUTHORITY,n,i,s=[],a,l,c,d,u;for(;e.length;){let p=e.shift();p.startsWith("scheme:")?n=p.substring(7):p.startsWith("authority:")?i=p.substring(10):p.startsWith("syncResource:")?a=p.substring(13):p.startsWith("profile:")?l=p.substring(8):p.startsWith("collection:")?c=p.substring(11):p.startsWith("ref:")?d=p.substring(4):a?u=p:s.push(p)}return{remote:t,syncResource:a,profile:l,collection:c,ref:d,node:u,location:n&&i!==void 0?this.extUri.joinPath(P.from({scheme:n,authority:i,query:r.query,fragment:r.fragment,path:"/"}),...s):void 0}}parseSyncData(r,e){try{let t=JSON.parse(r);if(Eo(t))return t}catch(t){this.logService.error(t)}throw new xe(S(2724,null),"IncompatibleRemoteContent",e)}async getUserData(r,e,t){let n=await this.userDataSyncStoreService.resolveResourceContent(r,e,t);return{ref:e,content:n}}getMcpAssociatedResources(r,e){let t=this.extUri.joinPath(r,"mcp.json"),n=e?e.mcpResource:this.extUri.joinPath(r,Nt.NOT_EXISTING_RESOURCE);return[{resource:t,comparableResource:n}]}resolveMcpNodeContent(r,e){return e==="mcp.json"?sv(r.content,this.logService):null}};Nt=b([g(0,Ce),g(1,Qe),g(2,me),g(3,te),g(4,X),g(5,K),g(6,W),g(7,fe),g(8,Q),g(9,bt)],Nt);async function c1(o,r,e,t,n,i){try{let s=await r.getExtensionsControlManifest();if(!s.deprecated)return;let a=await r.getInstalled(1,o?.extensionsResource);for(let[l,c]of Object.entries(s.deprecated)){if(!c?.extension)continue;let{id:d,autoMigrate:u,preRelease:p}=c.extension;if(!u)continue;let m=a.find(v=>j(v.identifier,{id:l}));if(!m)continue;let h=(await e.getExtensions([{id:d,preRelease:p}],{targetPlatform:await r.getTargetPlatform(),compatible:!0},Y.None))[0];if(!h){i.info(`Skipping migrating '${m.identifier.id}' extension because, the comaptible target '${d}' extension is not found`);continue}try{i.info(`Migrating '${m.identifier.id}' extension to '${d}' extension...`);let v=!n.getDisabledExtensions().some(x=>j(x,m.identifier));await r.uninstall(m,{profileLocation:o?.extensionsResource}),i.info(`Uninstalled the unsupported extension '${m.identifier.id}'`);let y=a.find(x=>j(x.identifier,{id:d}));(!y||y.isPreReleaseVersion!==!!p&&v)&&(y=await r.installFromGallery(h,{installPreReleaseVersion:p,isMachineScoped:m.isMachineScoped,operation:4,profileLocation:o?.extensionsResource,context:{[ec]:!0}}),i.info(`Installed the pre-release extension '${y.identifier.id}'`),!u.donotDisable&&!v&&(await n.disableExtension(y.identifier),i.info(`Disabled the pre-release extension '${y.identifier.id}' because the unsupported extension '${m.identifier.id}' is disabled`)),u.storage&&(t.addToMigrationList(so(m.manifest.publisher,m.manifest.name),so(y.manifest.publisher,y.manifest.name)),i.info("Added pre-release extension to the storage migration list"))),i.info(`Migrated '${m.identifier.id}' extension to '${d}' extension.`)}catch(v){i.error(v)}}if(s.autoUpdate)for(let[l,c]of Object.entries(s.autoUpdate))try{let d=a.find(p=>j(p.identifier,{id:l})&&Rb(p.manifest.version,c));if(!d)continue;let u=(await e.getExtensions([{id:l,preRelease:d.preRelease}],{targetPlatform:await r.getTargetPlatform(),compatible:!0},Y.None))[0];if(!u){i.info(`Skipping updating '${d.identifier.id}' extension because, the compatible target '${l}' extension is not found`);continue}await r.installFromGallery(u,{installPreReleaseVersion:d.preRelease,isMachineScoped:d.isMachineScoped,operation:3,profileLocation:o?.extensionsResource,context:{[ec]:!0}}),i.info(`Autoupdated '${d.identifier.id}' extension to '${u.version}' extension.`)}catch(d){i.error(d)}}catch(s){i.error(s)}}var Ba=class extends T{constructor(e,t,n,i,s,a,l){super();this.extensionManagementService=e;this.extensionGalleryService=t;this.extensionStorageService=n;this.extensionEnablementService=i;this.userDataProfilesService=s;this.logService=l;e.cleanUp(),this.migrateUnsupportedExtensions(),Ot.removeOutdatedExtensionVersions(e,a)}async migrateUnsupportedExtensions(){for(let e of this.userDataProfilesService.profiles)await c1(e,this.extensionManagementService,this.extensionGalleryService,this.extensionStorageService,this.extensionEnablementService,this.logService)}};Ba=b([g(0,oa),g(1,At),g(2,ua),g(3,gu),g(4,fe),g(5,K),g(6,V)],Ba);var Wc=class extends T{constructor(r,e=[]){super(),this.logger=new Kd([r,...e]),this._register(r.onDidChangeLogLevel(t=>this.setLevel(t)))}get onDidChangeLogLevel(){return this.logger.onDidChangeLogLevel}setLevel(r){this.logger.setLevel(r)}getLevel(){return this.logger.getLevel()}trace(r,...e){this.logger.trace(r,...e)}debug(r,...e){this.logger.debug(r,...e)}info(r,...e){this.logger.info(r,...e)}warn(r,...e){this.logger.warn(r,...e)}error(r,...e){this.logger.error(r,...e)}flush(){this.logger.flush()}};var Vf=L("sharedProcessLifecycleService"),$a=class extends T{constructor(e){super();this.logService=e;this._onWillShutdown=this._register(new w);this.onWillShutdown=this._onWillShutdown.event}fireOnWillShutdown(){this.logService.trace("Lifecycle#onWillShutdown.fire()"),this._onWillShutdown.fire()}};$a=b([g(0,V)],$a);import{spawn as d1}from"child_process";import{hostname as mT,homedir as gT}from"os";import{Transform as fT}from"stream";var Bc=class extends fT{constructor(r){if(super(),typeof r=="number")this.splitter=r,this.spitterLen=1;else{let e=Buffer.isBuffer(r)?r:Buffer.from(r);this.splitter=e.length===1?e[0]:e,this.spitterLen=e.length}}_transform(r,e,t){this.buffer?this.buffer=Buffer.concat([this.buffer,r]):this.buffer=r;let n=0;for(;n<this.buffer.length;){let i=typeof this.splitter=="number"?this.buffer.indexOf(this.splitter,n):Zm(this.buffer,this.splitter,n);if(i===-1)break;this.push(this.buffer.slice(n,i+this.spitterLen)),n=i+this.spitterLen}this.buffer=n===this.buffer.length?void 0:this.buffer.slice(n),t()}_flush(r){this.buffer&&this.push(this.buffer),r()}};var hT=[Mv,Av],Ov="remoteTunnelSession",Nv="remoteTunnelIsService",Ga=class extends T{constructor(e,t,n,i,s,a,l){super();this.telemetryService=e;this.productService=t;this.environmentService=n;this.configurationService=a;this.storageService=l;this._onDidTokenFailedEmitter=this._register(new w);this.onDidTokenFailed=this._onDidTokenFailedEmitter.event;this._onDidChangeTunnelStatusEmitter=this._register(new w);this.onDidChangeTunnelStatus=this._onDidChangeTunnelStatusEmitter.event;this._onDidChangeModeEmitter=this._register(new w);this.onDidChangeMode=this._onDidChangeModeEmitter.event;this._mode=Vc;this._initialized=!1;this.defaultOnOutput=(e,t)=>{t?this._logger.error(e):this._logger.info(e)};this._logger=this._register(i.createLogger($(n.logsHome,`${Fv}.log`),{id:Fv,name:l1})),this._startTunnelProcessDelayer=this._register(new Yi(100)),this._register(this._logger.onDidChangeLogLevel(c=>this._logger.info("Log level changed to "+Kl(c)))),this._register(s.onWillShutdown(()=>{this._tunnelProcess?.cancel(),this._tunnelProcess=void 0,this.dispose()})),this._register(a.onDidChangeConfiguration(c=>{hT.some(d=>c.affectsConfiguration(d))&&this._startTunnelProcessDelayer.trigger(()=>this.updateTunnelProcess())})),this._mode=this._restoreMode(),this._tunnelStatus=or.uninitialized}async getTunnelStatus(){return this._tunnelStatus}setTunnelStatus(e){this._tunnelStatus=e,this._onDidChangeTunnelStatusEmitter.fire(e)}setMode(e){u1(this._mode,e)||(this._mode=e,this._storeMode(e),this._onDidChangeModeEmitter.fire(this._mode),e.active?(this._logger.info(`Session updated: ${e.session.accountLabel} (${e.session.providerId}) (service=${e.asService})`),e.session.token&&this._logger.info(`Session token updated: ${e.session.accountLabel} (${e.session.providerId})`)):this._logger.info("Session reset"))}getMode(){return Promise.resolve(this._mode)}async initialize(e){if(this._initialized)return this._tunnelStatus;this._initialized=!0,this.setMode(e);try{await this._startTunnelProcessDelayer.trigger(()=>this.updateTunnelProcess())}catch(t){this._logger.error(t)}return this._tunnelStatus}getTunnelCommandLocation(){if(!this._tunnelCommand){let e;Gt?e=this.environmentService.appRoot:he?this.productService.win32VersionedUpdate?e=$e($e($e(this.environmentService.appRoot))):e=$e($e(this.environmentService.appRoot)):e=$e($e(this.environmentService.appRoot)),this._tunnelCommand=G(e,"bin",`${this.productService.tunnelApplicationName}${he?".exe":""}`)}return this._tunnelCommand}async startTunnel(e){if(u1(this._mode,e)&&this._tunnelStatus.type!=="disconnected")return this._tunnelStatus;this.setMode(e);try{await this._startTunnelProcessDelayer.trigger(()=>this.updateTunnelProcess())}catch(t){this._logger.error(t)}return this._tunnelStatus}async stopTunnel(){if(this._tunnelProcess&&(this._tunnelProcess.cancel(),this._tunnelProcess=void 0),this._mode.active){let e=this._mode.asService;this.setMode(Vc);try{e&&this.runCodeTunnelCommand("uninstallService",["service","uninstall"])}catch(t){this._logger.error(t)}}try{await this.runCodeTunnelCommand("stop",["kill"])}catch(e){this._logger.error(e)}this.setTunnelStatus(or.disconnected())}async updateTunnelProcess(){let e=this._getTunnelName();this.telemetryService.publicLog2("remoteTunnel.enablement",{enabled:this._mode.active,service:this._mode.active&&this._mode.asService,tunnelName:e}),this._tunnelProcess&&(this._tunnelProcess.cancel(),this._tunnelProcess=void 0);let t="",n=!1,i=(u,p)=>{p?this._logger.error(u):t+=u,!this.environmentService.isBuilt&&u.startsWith("   Compiling")&&this.setTunnelStatus(or.connecting(S(2270,null)))},s=this.runCodeTunnelCommand("status",["status"],i);this._tunnelProcess=s;try{if(await s,this._tunnelProcess!==s)return;let u;try{u=JSON.parse(t.trim().split(`
`).find(p=>p.startsWith("{")))}catch{this._logger.error(`Could not parse status output: ${JSON.stringify(t.trim())}`),this.setTunnelStatus(or.disconnected());return}if(n=u.service_installed,this._logger.info(u.tunnel?"Other tunnel running, attaching...":"No other tunnel running"),!u.tunnel&&!this._mode.active){this.setTunnelStatus(or.disconnected());return}}catch(u){this._logger.error(u),this.setTunnelStatus(or.disconnected());return}finally{this._tunnelProcess===s&&(this._tunnelProcess=void 0)}let a=this._mode.active?this._mode.session:void 0;if(a&&a.token){let u=a.token;this.setTunnelStatus(or.connecting(S(2269,null,a.accountLabel,a.providerId)));let p=(h,v)=>{h=h.replaceAll(u,"*".repeat(4)),i(h,v)},m=this.runCodeTunnelCommand("login",["user","login","--provider",a.providerId,"--log",Kl(this._logger.getLevel())],p,{VSCODE_CLI_ACCESS_TOKEN:u});this._tunnelProcess=m;try{if(await m,this._tunnelProcess!==m)return}catch(h){this._logger.error(h),this._tunnelProcess=void 0,this._onDidTokenFailedEmitter.fire(a),this.setTunnelStatus(or.disconnected(a));return}}let l=this._getTunnelName();l?this.setTunnelStatus(or.connecting(S(2272,null,l))):this.setTunnelStatus(or.connecting(S(2271,null)));let c=["--accept-server-license-terms","--log",Kl(this._logger.getLevel())];l?c.push("--name",l):c.push("--random-name");let d=!1;return this._mode.active&&this._mode.asService&&!n&&(d=await this.installTunnelService(c)===!1),this.serverOrAttachTunnel(a,c,d)}async installTunnelService(e){let t;try{t=await this.runCodeTunnelCommand("serviceInstall",["service","install",...e])}catch(n){this._logger.error(n),t=1}if(t!==0){let n=S(2273,null);return this._logger.warn(n),this.setTunnelStatus(or.connecting(n)),!1}return!0}async serverOrAttachTunnel(e,t,n){t.push("--parent-process-id",String(process.pid)),this._preventSleep()&&t.push("--no-sleep");let i=!1,s=this.runCodeTunnelCommand("tunnel",t,(a,l)=>{l?this._logger.error(a):this._logger.info(a),a.includes("Connected to an existing tunnel process")&&(i=!0);let c=a.match(/Open this link in your browser (https:\/\/([^\/\s]+)\/([^\/\s]+)\/([^\/\s]+))/);if(c){let d={link:c[1],domain:c[2],tunnelName:c[4],isAttached:i};this.telemetryService.publicLog2("remoteTunnel.connected",{tunnelName:d.tunnelName,isAttached:d.isAttached}),this.setTunnelStatus(or.connected(d,n))}else a.match(/error refreshing token/)&&(s.cancel(),this._onDidTokenFailedEmitter.fire(e),this.setTunnelStatus(or.disconnected(e)))});this._tunnelProcess=s,s.finally(()=>{s===this._tunnelProcess&&(this._logger.info("tunnel process terminated"),this._tunnelProcess=void 0,this._mode=Vc,this.setTunnelStatus(or.disconnected()))})}runCodeTunnelCommand(e,t,n=this.defaultOnOutput,i){return Je(s=>new Promise((a,l)=>{s.isCancellationRequested&&a(-1);let c,d=["ignore","pipe","pipe"];if(s.onCancellationRequested(()=>{c&&(this._logger.info(`${e} terminating(${c.pid})`),c.kill())}),!this.environmentService.isBuilt)n(`Building tunnel CLI from sources and run
`,!1),n(`${e} Spawning: cargo run -- tunnel ${t.join(" ")}
`,!1),c=d1("cargo",["run","--","tunnel",...t],{cwd:G(this.environmentService.appRoot,"cli"),stdio:d,env:{...process.env,RUST_BACKTRACE:"1",...i}});else{n(`Running tunnel CLI
`,!1);let u=this.getTunnelCommandLocation();n(`${e} Spawning: ${u} tunnel ${t.join(" ")}
`,!1),c=d1(u,["tunnel",...t],{cwd:gT(),stdio:d,env:{...process.env,...i}})}c.stdout.pipe(new Bc(`
`)).on("data",u=>{if(c){let p=u.toString();n(p,!1)}}),c.stderr.pipe(new Bc(`
`)).on("data",u=>{if(c){let p=u.toString();n(p,!0)}}),c.on("exit",u=>{c&&(n(`${e} exit(${c.pid}): + ${u} `,!1),c=void 0,a(u||0))}),c.on("error",u=>{c&&(n(`${e} error(${c.pid}): + ${u} `,!0),c=void 0,l())})}))}async getTunnelName(){return this._getTunnelName()}_preventSleep(){return!!this.configurationService.getValue(Av)}_getTunnelName(){let e=this.configurationService.getValue(Mv)||mT();return e=e.replace(/^-+/g,"").replace(/[^\w-]/g,"").substring(0,20),e||void 0}_restoreMode(){try{let e=this.storageService.get(Ov,-1),t=this.storageService.getBoolean(Nv,-1,!1);if(e){let n=JSON.parse(e);if(n&&ue(n.accountLabel)&&ue(n.sessionId)&&ue(n.providerId))return{active:!0,session:n,asService:t};this._logger.error("Problems restoring session from storage, invalid format",n)}}catch(e){this._logger.error("Problems restoring session from storage",e)}return Vc}_storeMode(e){if(e.active){let t={providerId:e.session.providerId,sessionId:e.session.sessionId,accountLabel:e.session.accountLabel};this.storageService.store(Ov,JSON.stringify(t),-1,1),this.storageService.store(Nv,e.asService,-1,1)}else this.storageService.remove(Ov,-1),this.storageService.remove(Nv,-1)}};Ga=b([g(0,de),g(1,ne),g(2,nt),g(3,wn),g(4,Vf),g(5,Q),g(6,K)],Ga);function vT(o,r){return o&&r?o.sessionId===r.sessionId&&o.providerId===r.providerId&&o.token===r.token:o===r}var u1=(o,r)=>o.active!==r.active?!1:o.active&&r.active?o.asService===r.asService&&vT(o.session,r.session):!0;var qa=class extends Zs{constructor(r,e,t,n,i){super(P.file(r.extensionsPath),e,t,n,i)}};qa=b([g(0,nt),g(1,W),g(2,fe),g(3,te),g(4,V)],qa);var Wf=class{constructor(r){this.channel=r}get ignoredRecommendations(){throw new Error("not supported")}promptImportantExtensionsInstallNotification(r){return this.channel.call("promptImportantExtensionsInstallNotification",[r])}promptWorkspaceRecommendations(r){throw new Error("not supported")}hasToIgnoreRecommendationNotifications(){throw new Error("not supported")}};var za=class{constructor(r,e){this.windowId=r;return Rt.toService(e.getChannel("nativeHost"),{context:r,properties:(()=>{let t=new Map;return t.set("windowId",r),t})()})}};za=b([g(1,Rn)],za);var Ka=L("meteredConnectionService");var Vv="sync.disableMachineEventually",$v="sync.sessionId",Wv="sync.storeUrl",Bv="sync.productQuality",ja=class extends T{constructor(e,t,n,i,s,a,l,c,d,u,p){super();this.userDataSyncStoreManagementService=t;this.userDataSyncStoreService=n;this.userDataSyncEnablementService=i;this.userDataSyncService=s;this.logService=a;this.userDataSyncAccountService=l;this.telemetryService=c;this.userDataSyncMachinesService=d;this.storageService=u;this.meteredConnectionService=p;this.autoSync=this._register(new kt);this.successiveFailures=0;this.lastSyncTriggerTime=void 0;this.suspendUntilRestart=!1;this._onError=this._register(new w);this.onError=this._onError.event;this.sources=[];this.syncTriggerDelayer=this._register(new ur(this.getSyncTriggerDelayTime())),this.lastSyncUrl=this.syncUrl,this.syncUrl=t.userDataSyncStore?.url,this.previousProductQuality=this.productQuality,this.productQuality=e.quality,this.syncUrl&&(this.logService.info("[AutoSync] Using settings sync service",this.syncUrl.toString()),this._register(t.onDidChangeUserDataSyncStore(()=>{_r(this.syncUrl,t.userDataSyncStore?.url)||(this.lastSyncUrl=this.syncUrl,this.syncUrl=t.userDataSyncStore?.url,this.syncUrl&&this.logService.info("[AutoSync] Using settings sync service",this.syncUrl.toString()))})),this.userDataSyncEnablementService.isEnabled()?this.logService.info("[AutoSync] Enabled."):this.logService.info("[AutoSync] Disabled."),this.updateAutoSync(),this.hasToDisableMachineEventually()&&this.disableMachineEventually(),this._register(l.onDidChangeAccount(()=>this.updateAutoSync())),this._register(n.onDidChangeDonotMakeRequestsUntil(()=>this.updateAutoSync())),this._register(s.onDidChangeLocal(m=>this.triggerSync([m]))),this._register(k.filter(this.userDataSyncEnablementService.onDidChangeResourceEnablement,([,m])=>m)(()=>this.triggerSync(["resourceEnablement"]))),this._register(this.userDataSyncStoreManagementService.onDidChangeUserDataSyncStore(()=>this.triggerSync(["userDataSyncStoreChanged"]))),this._register(p.onDidChangeIsConnectionMetered(()=>this.updateAutoSync())))}get syncUrl(){let e=this.storageService.get(Wv,-1);return e?P.parse(e):void 0}set syncUrl(e){e?this.storageService.store(Wv,e.toString(),-1,1):this.storageService.remove(Wv,-1)}get productQuality(){return this.storageService.get(Bv,-1)}set productQuality(e){e?this.storageService.store(Bv,e,-1,1):this.storageService.remove(Bv,-1)}updateAutoSync(){let{enabled:e,message:t}=this.isAutoSyncEnabled();e?this.autoSync.value===void 0&&(this.autoSync.value=new Gv(this.lastSyncUrl,1e3*60*5,this.userDataSyncStoreManagementService,this.userDataSyncStoreService,this.userDataSyncService,this.userDataSyncMachinesService,this.logService,this.telemetryService,this.storageService),this.autoSync.value.register(this.autoSync.value.onDidStartSync(()=>this.lastSyncTriggerTime=new Date().getTime())),this.autoSync.value.register(this.autoSync.value.onDidFinishSync(n=>this.onDidFinishSync(n))),this.startAutoSync()&&this.autoSync.value.start()):(this.syncTriggerDelayer.cancel(),this.autoSync.value!==void 0?(t&&this.logService.info(t),this.autoSync.clear()):t&&this.userDataSyncEnablementService.isEnabled()&&this.logService.info(t))}startAutoSync(){return!0}isAutoSyncEnabled(){return this.userDataSyncEnablementService.isEnabled()?this.userDataSyncAccountService.account?this.userDataSyncStoreService.donotMakeRequestsUntil?{enabled:!1,message:`[AutoSync] Suspended until ${ga(this.userDataSyncStoreService.donotMakeRequestsUntil)} because server is not accepting requests until then.`}:this.suspendUntilRestart?{enabled:!1,message:"[AutoSync] Suspended until restart."}:this.meteredConnectionService.isConnectionMetered?{enabled:!1,message:"[AutoSync] Suspended because connection is metered."}:{enabled:!0}:{enabled:!1,message:"[AutoSync] Suspended until auth token is available."}:{enabled:!1,message:"[AutoSync] Disabled."}}async turnOn(){this.stopDisableMachineEventually(),this.lastSyncUrl=this.syncUrl,this.updateEnablement(!0)}async turnOff(e,t,n){try{this.userDataSyncAccountService.account&&!n&&await this.userDataSyncMachinesService.removeCurrentMachine(),this.updateEnablement(!1),this.storageService.remove($v,-1),e?await this.userDataSyncService.reset():await this.userDataSyncService.resetLocal()}catch(i){if(this.logService.error(i),t)this.updateEnablement(!1);else throw i}}updateEnablement(e){this.userDataSyncEnablementService.isEnabled()!==e&&(this.userDataSyncEnablementService.setEnablement(e),this.updateAutoSync())}hasProductQualityChanged(){return!!this.previousProductQuality&&!!this.productQuality&&this.previousProductQuality!==this.productQuality}async onDidFinishSync(e){if(this.logService.debug("[AutoSync] Sync Finished"),!e){this.successiveFailures=0;return}let t=xe.toUserDataSyncError(e);t.code==="SessionExpired"?(await this.turnOff(!1,!0),this.logService.info("[AutoSync] Turned off sync because current session is expired")):t.code==="TurnedOff"?(await this.turnOff(!1,!0),this.logService.info("[AutoSync] Turned off sync because sync is turned off in the cloud")):t.code==="LocalTooManyRequests"?(this.suspendUntilRestart=!0,this.logService.info("[AutoSync] Suspended sync because of making too many requests to server"),this.updateAutoSync()):t.code==="RemoteTooManyRequests"?(await this.turnOff(!1,!0,!0),this.disableMachineEventually(),this.logService.info("[AutoSync] Turned off sync because of making too many requests to server")):t.code==="MethodNotFound"?(await this.turnOff(!1,!0),this.logService.info("[AutoSync] Turned off sync because current client is making requests to server that are not supported")):t.code==="UpgradeRequired"||t.code==="Gone"?(await this.turnOff(!1,!0,!0),this.disableMachineEventually(),this.logService.info("[AutoSync] Turned off sync because current client is not compatible with server. Requires client upgrade.")):t.code==="IncompatibleLocalContent"?(await this.turnOff(!1,!0),this.logService.info(`[AutoSync] Turned off sync because server has ${t.resource} content with newer version than of client. Requires client upgrade.`)):t.code==="IncompatibleRemoteContent"?(await this.turnOff(!1,!0),this.logService.info(`[AutoSync] Turned off sync because server has ${t.resource} content with older version than of client. Requires server reset.`)):t.code==="ServiceChanged"||t.code==="DefaultServiceChanged"?ze&&t.code==="DefaultServiceChanged"&&!this.hasProductQualityChanged()?(await this.turnOff(!1,!0),this.logService.info("[AutoSync] Turned off sync because default sync service is changed.")):(await this.turnOff(!1,!0,!0),await this.turnOn(),this.logService.info("[AutoSync] Sync Service changed. Turned off auto sync, reset local state and turned on auto sync.")):(this.logService.error(t),this.successiveFailures++),this._onError.fire(t)}async disableMachineEventually(){this.storageService.store(Vv,!0,-1,1),await Lr(1e3*60*10),this.hasToDisableMachineEventually()&&(this.stopDisableMachineEventually(),!this.userDataSyncEnablementService.isEnabled()&&this.userDataSyncAccountService.account&&await this.userDataSyncMachinesService.removeCurrentMachine())}hasToDisableMachineEventually(){return this.storageService.getBoolean(Vv,-1,!1)}stopDisableMachineEventually(){this.storageService.remove(Vv,-1)}async triggerSync(e,t){if(this.autoSync.value===void 0)return this.syncTriggerDelayer.cancel();if(t?.skipIfSyncedRecently&&this.lastSyncTriggerTime&&new Date().getTime()-this.lastSyncTriggerTime<1e4){this.logService.debug("[AutoSync] Skipping because sync was triggered recently.",e);return}return this.sources.push(...e),this.syncTriggerDelayer.trigger(async()=>{this.logService.trace("[AutoSync] Activity sources",...this.sources),this.sources=[],this.autoSync.value&&await this.autoSync.value.sync("Activity",!!t?.disableCache)},this.successiveFailures?Math.min(this.getSyncTriggerDelayTime()*this.successiveFailures,6e4):t?.immediately?0:this.getSyncTriggerDelayTime())}getSyncTriggerDelayTime(){return this.lastSyncTriggerTime&&new Date().getTime()-this.lastSyncTriggerTime>1e4?(this.logService.debug("[AutoSync] Sync immediately because last sync was triggered more than 10 seconds ago."),0):3e3}};ja=b([g(0,ne),g(1,Pr),g(2,Ce),g(3,Oe),g(4,yo),g(5,me),g(6,So),g(7,de),g(8,bo),g(9,K),g(10,Ka)],ja);var Gv=class o extends T{constructor(e,t,n,i,s,a,l,c,d){super();this.lastSyncUrl=e;this.interval=t;this.userDataSyncStoreManagementService=n;this.userDataSyncStoreService=i;this.userDataSyncService=s;this.userDataSyncMachinesService=a;this.logService=l;this.telemetryService=c;this.storageService=d;this.intervalHandler=this._register(new kt);this._onDidStartSync=this._register(new w);this.onDidStartSync=this._onDidStartSync.event;this._onDidFinishSync=this._register(new w);this.onDidFinishSync=this._onDidFinishSync.event;this.manifest=null}static{this.INTERVAL_SYNCING="Interval"}start(){this._register(this.onDidFinishSync(()=>this.waitUntilNextIntervalAndSync())),this._register(oe(()=>{this.syncPromise&&(this.syncPromise.cancel(),this.logService.info("[AutoSync] Cancelled sync that is in progress"),this.syncPromise=void 0),this.syncTask?.stop(),this.logService.info("[AutoSync] Stopped")})),this.sync(o.INTERVAL_SYNCING,!1)}waitUntilNextIntervalAndSync(){this.intervalHandler.value=ai(()=>{this.sync(o.INTERVAL_SYNCING,!1),this.intervalHandler.value=void 0},this.interval)}sync(e,t){let n=Je(async i=>{if(this.syncPromise)try{this.logService.debug("[AutoSync] Waiting until sync is finished."),await this.syncPromise}catch(s){if(lr(s))return}return this.doSync(e,t,i)});return this.syncPromise=n,this.syncPromise.finally(()=>this.syncPromise=void 0),this.syncPromise}hasSyncServiceChanged(){return this.lastSyncUrl!==void 0&&!_r(this.lastSyncUrl,this.userDataSyncStoreManagementService.userDataSyncStore?.url)}async hasDefaultServiceChanged(){let e=await this.userDataSyncStoreManagementService.getPreviousUserDataSyncStore(),t=this.userDataSyncStoreManagementService.userDataSyncStore;return!!t&&!!e&&(!_r(t.defaultUrl,e.defaultUrl)||!_r(t.insidersUrl,e.insidersUrl)||!_r(t.stableUrl,e.stableUrl))}async doSync(e,t,n){this.logService.info(`[AutoSync] Triggered by ${e}`),this._onDidStartSync.fire();let i;try{await this.createAndRunSyncTask(t,n)}catch(s){if(this.logService.error(s),i=s,xe.toUserDataSyncError(s).code==="MethodNotFound")try{this.logService.info("[AutoSync] Client is making invalid requests. Cleaning up data..."),await this.userDataSyncService.cleanUpRemoteData(),this.logService.info("[AutoSync] Retrying sync..."),await this.createAndRunSyncTask(t,n),i=void 0}catch(a){this.logService.error(a),i=a}}this._onDidFinishSync.fire(i)}async createAndRunSyncTask(e,t){if(this.syncTask=await this.userDataSyncService.createSyncTask(this.manifest,e),t.isCancellationRequested)return;if(this.manifest=this.syncTask.manifest,this.manifest===null&&await this.userDataSyncService.hasPreviouslySynced())throw this.hasSyncServiceChanged()?await this.hasDefaultServiceChanged()?new dn(S(2712,null),"DefaultServiceChanged"):new dn(S(2713,null),"ServiceChanged"):new dn(S(2715,null),"TurnedOff");let n=this.storageService.get($v,-1);if(n&&this.manifest&&n!==this.manifest.session)throw this.hasSyncServiceChanged()?await this.hasDefaultServiceChanged()?new dn(S(2712,null),"DefaultServiceChanged"):new dn(S(2713,null),"ServiceChanged"):new dn(S(2714,null),"SessionExpired");let i=await this.userDataSyncMachinesService.getMachines(this.manifest||void 0);if(t.isCancellationRequested)return;let s=i.find(l=>l.isCurrent);if(s?.disabled)throw new dn(S(2716,null),"TurnedOff");let a=new Date().getTime();if(await this.syncTask.run(),this.telemetryService.publicLog2("settingsSync:sync",{duration:new Date().getTime()-a}),this.manifest===null)try{this.manifest=await this.userDataSyncStoreService.manifest(null)}catch(l){throw new dn(_t(l),l instanceof xe?l.code:"Unknown")}this.manifest&&this.manifest.session!==n&&this.storageService.store($v,this.manifest.session,-1,1),!t.isCancellationRequested&&(s||await this.userDataSyncMachinesService.addCurrentMachine(this.manifest||void 0))}register(e){return super._register(e)}};var Ha=class extends ja{constructor(r,e,t,n,i,s,a,l,c,d,u,p){super(r,e,t,n,i,a,l,c,d,u,p),this._register(k.debounce(k.any(k.map(s.onDidFocusMainWindow,()=>"windowFocus"),k.map(s.onDidOpenMainWindow,()=>"windowOpen")),(m,h)=>m?[...m,h]:[h],1e3)(m=>this.triggerSync(m,{skipIfSyncedRecently:!0})))}};Ha=b([g(0,ne),g(1,Pr),g(2,Ce),g(3,Oe),g(4,yo),g(5,mi),g(6,me),g(7,So),g(8,de),g(9,bo),g(10,K),g(11,Ka)],Ha);var $c=class extends T{constructor(e,t){super();this.fileService=e;this.productService=t;this.allConfigBasedTips=new Map;this.productService.configBasedExtensionTips&&Object.entries(this.productService.configBasedExtensionTips).forEach(([,n])=>this.allConfigBasedTips.set(n.configPath,n))}getConfigBasedTips(e){return this.getValidConfigBasedTips(e)}async getImportantExecutableBasedTips(){return[]}async getOtherExecutableBasedTips(){return[]}async getValidConfigBasedTips(e){let t=[];for(let[n,i]of this.allConfigBasedTips)if(!(i.configScheme&&i.configScheme!==e.scheme))try{let s=(await this.fileService.readFile($(e,n))).value.toString();for(let[a,l]of Object.entries(i.recommendations))(!l.contentPattern||new RegExp(l.contentPattern,"mig").test(s))&&t.push({extensionId:a,extensionName:l.name,configName:i.configName,important:!!l.important,isExtensionPack:!!l.isExtensionPack,whenNotInstalled:l.whenNotInstalled})}catch{}return t}};$c=b([g(0,W),g(1,ne)],$c);var p1="extensionTips/promptedExecutableTips",f1="extensionTips/lastPromptedMediumImpExeTime",Bf=class extends $c{constructor(e,t,n,i,s,a,l,c){super(l,c);this.userHome=e;this.windowEvents=t;this.telemetryService=n;this.extensionManagementService=i;this.storageService=s;this.extensionRecommendationNotificationService=a;this.highImportanceExecutableTips=new Map;this.mediumImportanceExecutableTips=new Map;this.allOtherExecutableTips=new Map;this.highImportanceTipsByExe=new Map;this.mediumImportanceTipsByExe=new Map;c.exeBasedExtensionTips&&Object.entries(c.exeBasedExtensionTips).forEach(([d,u])=>{let p=[],m=[],h=[];Object.entries(u.recommendations).forEach(([v,y])=>{y.important?u.important?p.push({extensionId:v,extensionName:y.name,isExtensionPack:!!y.isExtensionPack}):m.push({extensionId:v,extensionName:y.name,isExtensionPack:!!y.isExtensionPack}):h.push({extensionId:v,extensionName:y.name,isExtensionPack:!!y.isExtensionPack})}),p.length&&this.highImportanceExecutableTips.set(d,{exeFriendlyName:u.friendlyName,windowsPath:u.windowsPath,recommendations:p}),m.length&&this.mediumImportanceExecutableTips.set(d,{exeFriendlyName:u.friendlyName,windowsPath:u.windowsPath,recommendations:m}),h.length&&this.allOtherExecutableTips.set(d,{exeFriendlyName:u.friendlyName,windowsPath:u.windowsPath,recommendations:h})}),ai(async()=>{await this.collectTips(),this.promptHighImportanceExeBasedTip(),this.promptMediumImportanceExeBasedTip()},3e3,this._store)}async getImportantExecutableBasedTips(){let e=await this.getValidExecutableBasedExtensionTips(this.highImportanceExecutableTips),t=await this.getValidExecutableBasedExtensionTips(this.mediumImportanceExecutableTips);return[...e,...t]}getOtherExecutableBasedTips(){return this.getValidExecutableBasedExtensionTips(this.allOtherExecutableTips)}async collectTips(){let e=await this.getValidExecutableBasedExtensionTips(this.highImportanceExecutableTips),t=await this.getValidExecutableBasedExtensionTips(this.mediumImportanceExecutableTips),n=await this.extensionManagementService.getInstalled();this.highImportanceTipsByExe=this.groupImportantTipsByExe(e,n),this.mediumImportanceTipsByExe=this.groupImportantTipsByExe(t,n)}groupImportantTipsByExe(e,t){let n=new Map;e.forEach(c=>n.set(c.extensionId.toLowerCase(),c));let{installed:i,uninstalled:s}=this.groupByInstalled([...n.keys()],t);for(let c of i){let d=n.get(c);d&&this.telemetryService.publicLog2("exeExtensionRecommendations:alreadyInstalled",{extensionId:c,exeName:d.exeName})}for(let c of s){let d=n.get(c);d&&this.telemetryService.publicLog2("exeExtensionRecommendations:notInstalled",{extensionId:c,exeName:d.exeName})}let a=this.getPromptedExecutableTips(),l=new Map;for(let c of s){let d=n.get(c);if(d&&(!a[d.exeName]||!a[d.exeName].includes(d.extensionId))){let u=l.get(d.exeName);u||(u=[],l.set(d.exeName,u)),u.push(d)}}return l}promptHighImportanceExeBasedTip(){if(this.highImportanceTipsByExe.size===0)return;let[e,t]=[...this.highImportanceTipsByExe.entries()][0];this.promptExeRecommendations(t).then(n=>{switch(n){case"reacted":this.addToRecommendedExecutables(t[0].exeName,t);break;case"ignored":this.highImportanceTipsByExe.delete(e);break;case"incompatibleWindow":{let i=k.once(k.latch(k.any(this.windowEvents.onDidOpenMainWindow,this.windowEvents.onDidFocusMainWindow)));this._register(i(()=>this.promptHighImportanceExeBasedTip()));break}case"toomany":{let i=this._register(new kt);i.value=ai(()=>{i.dispose(),this.promptHighImportanceExeBasedTip()},3600*1e3);break}}})}promptMediumImportanceExeBasedTip(){if(this.mediumImportanceTipsByExe.size===0)return;let e=this.getLastPromptedMediumExeTime(),t=Date.now()-e,n=10080*60*1e3;if(t<n){let a=this._register(new kt);a.value=ai(()=>{a.dispose(),this.promptMediumImportanceExeBasedTip()},n-t);return}let[i,s]=[...this.mediumImportanceTipsByExe.entries()][0];this.promptExeRecommendations(s).then(a=>{switch(a){case"reacted":{this.updateLastPromptedMediumExeTime(Date.now()),this.mediumImportanceTipsByExe.delete(i),this.addToRecommendedExecutables(s[0].exeName,s);let l=this._register(new kt);l.value=ai(()=>{l.dispose(),this.promptMediumImportanceExeBasedTip()},n);break}case"ignored":this.mediumImportanceTipsByExe.delete(i),this.promptMediumImportanceExeBasedTip();break;case"incompatibleWindow":{let l=k.once(k.latch(k.any(this.windowEvents.onDidOpenMainWindow,this.windowEvents.onDidFocusMainWindow)));this._register(l(()=>this.promptMediumImportanceExeBasedTip()));break}case"toomany":{let l=this._register(new kt);l.value=ai(()=>{l.dispose(),this.promptMediumImportanceExeBasedTip()},3600*1e3);break}}})}async promptExeRecommendations(e){let t=await this.extensionManagementService.getInstalled(1),n=e.filter(i=>!i.whenNotInstalled||i.whenNotInstalled.every(s=>t.every(a=>!j(a.identifier,{id:s})))).map(({extensionId:i})=>i.toLowerCase());return this.extensionRecommendationNotificationService.promptImportantExtensionsInstallNotification({extensions:n,source:3,name:e[0].exeFriendlyName,searchValue:`@exe:"${e[0].exeName}"`})}getLastPromptedMediumExeTime(){let e=this.storageService.getNumber(f1,-1);return e||(e=Date.now(),this.updateLastPromptedMediumExeTime(e)),e}updateLastPromptedMediumExeTime(e){this.storageService.store(f1,e,-1,1)}getPromptedExecutableTips(){return JSON.parse(this.storageService.get(p1,-1,"{}"))}addToRecommendedExecutables(e,t){let n=this.getPromptedExecutableTips();n[e]=t.map(({extensionId:i})=>i.toLowerCase()),this.storageService.store(p1,JSON.stringify(n),-1,0)}groupByInstalled(e,t){let n=[],i=[],s=t.reduce((a,l)=>(a.add(l.identifier.id.toLowerCase()),a),new Set);return e.forEach(a=>{s.has(a.toLowerCase())?n.push(a):i.push(a)}),{installed:n,uninstalled:i}}async getValidExecutableBasedExtensionTips(e){let t=[],n=new Map;for(let i of e.keys()){let s=e.get(i);if(!s||!Zn(s.recommendations))continue;let a=[];he?s.windowsPath&&a.push(s.windowsPath.replace("%USERPROFILE%",()=>Fe.USERPROFILE).replace("%ProgramFiles(x86)%",()=>Fe["ProgramFiles(x86)"]).replace("%ProgramFiles%",()=>Fe.ProgramFiles).replace("%APPDATA%",()=>Fe.APPDATA).replace("%WINDIR%",()=>Fe.WINDIR)):(a.push(G("/usr/local/bin",i)),a.push(G("/usr/bin",i)),a.push(G(this.userHome.fsPath,i)));for(let l of a){let c=n.get(l);if(c===void 0&&(c=await this.fileService.exists(P.file(l)),n.set(l,c)),c)for(let{extensionId:d,extensionName:u,isExtensionPack:p,whenNotInstalled:m}of s.recommendations)t.push({extensionId:d,extensionName:u,isExtensionPack:p,exeName:i,exeFriendlyName:s.exeFriendlyName,windowsPath:s.windowsPath,whenNotInstalled:m})}}return t}};var Ja=class extends Bf{constructor(r,e,t,n,i,s,a,l){super(r.userHome,i,e,t,n,s,a,l)}};Ja=b([g(0,nt),g(1,de),g(2,rr),g(3,K),g(4,mi),g(5,Sp),g(6,W),g(7,ne)],Ja);var $f=class extends Vs{constructor(e,t,n,i){super();this.remoteService=n;this.environmentService=i;this.profileStorageDisposables=this._register(new se);this.workspaceStorageDisposables=this._register(new se);this.applicationStorageProfile=t.defaultProfile,this.applicationStorage=this.createApplicationStorage(),this.profileStorageProfile=t.currentProfile,this.profileStorage=this.createProfileStorage(this.profileStorageProfile),this.workspaceStorageId=e?.id,this.workspaceStorage=this.createWorkspaceStorage(e)}createApplicationStorage(){let e=this._register(new ws(this.remoteService.getChannel("storage"))),t=this._register(new jn(e));return this._register(t.onDidChangeStorage(n=>this.emitDidChangeValue(-1,n))),t}createProfileStorage(e){this.profileStorageDisposables.clear(),this.profileStorageProfile=e;let t;if(Ws(e))t=this.applicationStorage;else{let n=this.profileStorageDisposables.add(new Ps(this.remoteService.getChannel("storage"),e));t=this.profileStorageDisposables.add(new jn(n))}return this.profileStorageDisposables.add(t.onDidChangeStorage(n=>this.emitDidChangeValue(0,n))),t}createWorkspaceStorage(e){this.workspaceStorageDisposables.clear(),this.workspaceStorageId=e?.id;let t;if(e){let n=this.workspaceStorageDisposables.add(new Iu(this.remoteService.getChannel("storage"),e));t=this.workspaceStorageDisposables.add(new jn(n)),this.workspaceStorageDisposables.add(t.onDidChangeStorage(i=>this.emitDidChangeValue(1,i)))}return t}async doInitialize(){await Ke.settled([this.applicationStorage.init(),this.profileStorage.init(),this.workspaceStorage?.init()??Promise.resolve()])}getStorage(e){switch(e){case-1:return this.applicationStorage;case 0:return this.profileStorage;default:return this.workspaceStorage}}getLogDetails(e){switch(e){case-1:return this.applicationStorageProfile.globalStorageHome.with({scheme:re.file}).fsPath;case 0:return this.profileStorageProfile?.globalStorageHome.with({scheme:re.file}).fsPath;default:return this.workspaceStorageId?`${$(this.environmentService.workspaceStorageHome,this.workspaceStorageId,"state.vscdb").with({scheme:re.file}).fsPath}`:void 0}}async close(){this.stopFlushWhenIdle(),this.emitWillSaveState(1),await Ke.settled([this.applicationStorage.close(),this.profileStorage.close(),this.workspaceStorage?.close()??Promise.resolve()])}async switchToProfile(e){if(!this.canSwitchProfile(this.profileStorageProfile,e))return;let t=this.profileStorage,n=t.items;t!==this.applicationStorage&&await t.close(),this.profileStorage=this.createProfileStorage(e),await this.profileStorage.init(),this.switchData(n,this.profileStorage,0)}async switchToWorkspace(e,t){let n=this.workspaceStorage,i=n?.items??new Map;await n?.close(),this.workspaceStorage=this.createWorkspaceStorage(e),await this.workspaceStorage.init(),this.switchData(i,this.workspaceStorage,1)}hasScope(e){return ju(e)?this.profileStorageProfile.id===e.id:this.workspaceStorageId===e.id}};import*as g1 from"net";var m1=(o,r,e)=>{let t=new Uint8Array(16);for(let s=0;s<16;s++)t[s]=Math.round(Math.random()*256);let n=HS(U.wrap(t));return[`GET ws://localhost${o}?${r}&skipWebSocketFrames=true HTTP/1.1`,"Connection: Upgrade","Upgrade: websocket",`Sec-WebSocket-Key: ${n}`].join(`\r
`)+`\r
\r
`},ude=U.fromString(`\r
\r
`);var h1=new class{supports(o){return!0}connect({host:o,port:r},e,t,n){return new Promise((i,s)=>{let a=g1.createConnection({host:o,port:r},()=>{a.removeListener("error",s),a.write(m1(e,t,n));let l=c=>{c.toString().indexOf(`\r
\r
`)>=0&&(a.off("data",l),i(new Do(a,n)))};a.on("data",l)});a.setNoDelay(!0),a.once("error",s)})}};import{homedir as $T,tmpdir as GT}from"os";var v1=/^([^.]+\..+)[:=](.+)$/,ke=class{constructor(r,e,t){this._args=r;this.paths=e;this.productService=t}get appRoot(){return $e(dr.asFileUri("").fsPath)}get userHome(){return P.file(this.paths.homeDir)}get userDataPath(){return this.paths.userDataDir}get appSettingsHome(){return P.file(G(this.userDataPath,"User"))}get tmpDir(){return P.file(this.paths.tmpDir)}get cacheHome(){return P.file(this.userDataPath)}get stateResource(){return $(this.appSettingsHome,"globalStorage","storage.json")}get userRoamingDataHome(){return this.appSettingsHome.with({scheme:re.vscodeUserData})}get userDataSyncHome(){return $(this.appSettingsHome,"sync")}get logsHome(){if(!this.args.logsPath){let r=ga(new Date).replace(/-|:|\.\d+Z$/g,"");this.args.logsPath=G(this.userDataPath,"logs",r)}return P.file(this.args.logsPath)}get sync(){return this.args.sync}get workspaceStorageHome(){return $(this.appSettingsHome,"workspaceStorage")}get localHistoryHome(){return $(this.appSettingsHome,"History")}get keyboardLayoutResource(){return $(this.userRoamingDataHome,"keyboardLayout.json")}get argvResource(){let r=Fe.VSCODE_PORTABLE;return r?P.file(G(r,"argv.json")):$(this.userHome,this.productService.dataFolderName,"argv.json")}get isExtensionDevelopment(){return!!this.args.extensionDevelopmentPath}get untitledWorkspacesHome(){return P.file(G(this.userDataPath,"Workspaces"))}get builtinWorkbenchModesHome(){return $(P.file(this.appRoot),"resources","workbenchModes")}get builtinExtensionsPath(){let r=this.args["builtin-extensions-dir"];return r?en(r):br(G(dr.asFileUri("").fsPath,"..","extensions"))}get extensionsDownloadLocation(){let r=this.args["extensions-download-dir"];return r?P.file(en(r)):P.file(G(this.userDataPath,"CachedExtensionVSIXs"))}get extensionsPath(){let r=this.args["extensions-dir"];if(r)return en(r);let e=Fe.VSCODE_EXTENSIONS;if(e)return e;let t=Fe.VSCODE_PORTABLE;return t?G(t,"extensions"):$(this.userHome,this.productService.dataFolderName,"extensions").fsPath}get extensionDevelopmentLocationURI(){let r=this.args.extensionDevelopmentPath;if(Array.isArray(r))return r.map(e=>/^[^:/?#]+?:\/\//.test(e)?P.parse(e):P.file(br(e)))}get extensionDevelopmentKind(){return this.args.extensionDevelopmentKind?.map(r=>r==="ui"||r==="workspace"||r==="web"?r:"workspace")}get extensionTestsLocationURI(){let r=this.args.extensionTestsPath;if(r)return/^[^:/?#]+?:\/\//.test(r)?P.parse(r):P.file(br(r))}get disableExtensions(){if(this.args["disable-extensions"])return!0;let r=this.args["disable-extension"];if(r){if(typeof r=="string")return[r];if(Array.isArray(r)&&r.length>0)return r}return!1}get debugExtensionHost(){return yT(this.args,this.isBuilt)}get debugRenderer(){return!!this.args.debugRenderer}get isBuilt(){return!Fe.VSCODE_DEV}get verbose(){return!!this.args.verbose}get logLevel(){return this.args.log?.find(r=>!v1.test(r))}get extensionLogLevel(){let r=[];for(let e of this.args.log||[]){let t=v1.exec(e);t?.[1]&&t[2]&&r.push([t[1],t[2]])}return r.length?r:void 0}get serviceMachineIdResource(){return $(P.file(this.userDataPath),"machineid")}get crashReporterId(){return this.args["crash-reporter-id"]}get crashReporterDirectory(){return this.args["crash-reporter-directory"]}get disableTelemetry(){return!!this.args["disable-telemetry"]}get disableExperiments(){return!!this.args["disable-experiments"]}get disableWorkspaceTrust(){return!!this.args["disable-workspace-trust"]}get useInMemorySecretStorage(){return!!this.args["use-inmemory-secretstorage"]}get policyFile(){if(this.args["__enable-file-policy"]){let r=Fe.VSCODE_PORTABLE;return r?P.file(G(r,"policy.json")):$(this.userHome,this.productService.dataFolderName,"policy.json")}}get agentSessionsWorkspace(){return $(this.appSettingsHome,"agent-sessions.code-workspace")}get editSessionId(){return this.args.editSessionId}get exportPolicyData(){return this.args["export-policy-data"]}get continueOn(){return this.args.continueOn}set continueOn(r){this.args.continueOn=r}get args(){return this._args}};b([Ue],ke.prototype,"appRoot",1),b([Ue],ke.prototype,"userHome",1),b([Ue],ke.prototype,"userDataPath",1),b([Ue],ke.prototype,"appSettingsHome",1),b([Ue],ke.prototype,"tmpDir",1),b([Ue],ke.prototype,"cacheHome",1),b([Ue],ke.prototype,"stateResource",1),b([Ue],ke.prototype,"userRoamingDataHome",1),b([Ue],ke.prototype,"userDataSyncHome",1),b([Ue],ke.prototype,"sync",1),b([Ue],ke.prototype,"workspaceStorageHome",1),b([Ue],ke.prototype,"localHistoryHome",1),b([Ue],ke.prototype,"keyboardLayoutResource",1),b([Ue],ke.prototype,"argvResource",1),b([Ue],ke.prototype,"isExtensionDevelopment",1),b([Ue],ke.prototype,"untitledWorkspacesHome",1),b([Ue],ke.prototype,"builtinWorkbenchModesHome",1),b([Ue],ke.prototype,"builtinExtensionsPath",1),b([Ue],ke.prototype,"extensionsDownloadLocation",1),b([Ue],ke.prototype,"extensionsPath",1),b([Ue],ke.prototype,"extensionDevelopmentLocationURI",1),b([Ue],ke.prototype,"extensionDevelopmentKind",1),b([Ue],ke.prototype,"extensionTestsLocationURI",1),b([Ue],ke.prototype,"debugExtensionHost",1),b([Ue],ke.prototype,"logLevel",1),b([Ue],ke.prototype,"extensionLogLevel",1),b([Ue],ke.prototype,"serviceMachineIdResource",1),b([Ue],ke.prototype,"disableTelemetry",1),b([Ue],ke.prototype,"disableExperiments",1),b([Ue],ke.prototype,"disableWorkspaceTrust",1),b([Ue],ke.prototype,"useInMemorySecretStorage",1),b([Ue],ke.prototype,"policyFile",1),b([Ue],ke.prototype,"agentSessionsWorkspace",1);function yT(o,r){return y1(o["inspect-extensions"],o["inspect-brk-extensions"],5870,r,o.debugId,o.extensionEnvironment)}function y1(o,r,e,t,n,i){let a=Number(r||o)||(t?null:e),l=a?!!r:!1,c;if(i)try{c=JSON.parse(i)}catch{}return{port:a,break:l,debugId:n,env:c}}import{homedir as Hf}from"os";import{execFileSync as Dde}from"child_process";import{existsSync as ht,readFileSync as zv,writeFileSync as zf,mkdirSync as qf,renameSync as ST,unlinkSync as Xa,rmSync as Oi,cpSync as kde,readdirSync as E1,statSync as w1,statfsSync as IT,linkSync as bT,promises as Ude}from"fs";import{homedir as Kf}from"os";import{join as Vt,dirname as xT,relative as ET}from"path";function wT(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let r=o;return typeof r.migratedAt=="string"&&typeof r.version=="string"}function PT(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let r=o;return r.reason==="insufficient_disk"&&typeof r.requiredBytes=="number"&&typeof r.availableBytes=="number"&&typeof r.checkedAt=="string"&&typeof r.schemaVersion=="number"}function RT(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let r=o;return typeof r.pid=="number"&&typeof r.startedAt=="string"}var TT=".devin-migration-complete",Gc=".devin-migration-in-progress",CT=".devin-migration-failed",DT=".devin-migration-insufficient-disk",S1=5,_T=".devin-argv-precopy",kT=".devin-migration.lock",UT=".failed",LT=1.1,P1=3600*1e3;function MT(o){return ht(o)&&E1(o).some(r=>r!==Gc)}var AT=new Set(["Cache","CachedConfigurations","CachedData","CachedExtensionVSIXs","CachedProfilesData","Code Cache","GPUCache","DawnGraphiteCache","DawnWebGPUCache","GrShaderCache","ShaderCache","blob_storage","logs","crashpad","Crashpad"]),FT=new Set(["User/History","Partitions/vscode-browser/Cache"]);function OT(){switch(process.platform){case"win32":{let o=process.env.APPDATA;if(o)return o;let r=process.env.USERPROFILE;if(typeof r!="string")throw new Error("Windows: Unexpected undefined %USERPROFILE% environment variable");return Vt(r,"AppData","Roaming")}case"darwin":return Vt(Kf(),"Library","Application Support");case"linux":return process.env.XDG_CONFIG_HOME||Vt(Kf(),".config");default:throw new Error("Platform not supported")}}function Gf(o,r){let e=o+".tmp";zf(e,JSON.stringify(r,null,"	")),ST(e,o)}function R1(o){if(ht(o))try{let r=JSON.parse(zv(o,"utf8"));return wT(r)?r:void 0}catch{return}}function I1(o){return R1(o)!==void 0}function qv(o,r,e,t){let n=0,i=t??o;try{let s=E1(o,{withFileTypes:!0});for(let a of s){let l=Vt(o,a.name),c=ET(i,l).replace(/\\/g,"/");if(!(t===void 0&&r?.has(a.name))&&!e?.has(c)){if(a.isDirectory())n+=qv(l,void 0,e,i);else if(a.isFile())try{n+=w1(l).size}catch{}}}}catch{}return n}function b1(o){try{let r=ht(o)?o:xT(o),e=IT(r);return e.bavail*e.bsize}catch{return-1}}function NT(o){if(!o||o===process.pid)return!1;try{return process.kill(o,0),!0}catch(r){return r?.code==="EPERM"}}function VT(o,r){try{qf(o,{recursive:!0})}catch{return}let e=Vt(o,`${kT}-${r}`),t=`${e}.tmp.${process.pid}`,n={pid:process.pid,startedAt:new Date().toISOString()},i=()=>{try{zf(t,JSON.stringify(n))}catch{return!1}try{return bT(t,e),!0}catch{return!1}finally{try{Xa(t)}catch{}}};if(i())return{lockPath:e};let s=!1;try{let a=JSON.parse(zv(e,"utf8"));if(RT(a)){let l=Date.now()-new Date(a.startedAt).getTime(),c=isNaN(l)||l>P1,d=NT(a.pid);s=c||!d}else s=x1(e)}catch{s=x1(e)}if(s){try{Xa(e)}catch{}return i()?{lockPath:e}:void 0}}function x1(o){try{return Date.now()-w1(o).mtimeMs>P1}catch{return!1}}function Qa(o){try{Xa(o.lockPath)}catch{}}function T1(o){let{nameShort:r,dataFolderName:e,oldDataFolderName:t,oldNameShort:n,version:i}=o;if(!t||!n)return{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!1}};if(n===r&&t===e)return{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!1}};let s=OT(),a=Vt(s,n),l=Vt(s,r),c=Vt(Kf(),t),d=Vt(Kf(),e),u=Vt(c,"extensions"),p=Vt(d,"extensions"),m=Vt(l,TT),h=R1(m);if(h)return{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!1,migratedAt:h.migratedAt}};let v=Vt(s,`${DT}-${r}`);if(ht(v))try{let x=JSON.parse(zv(v,"utf8"));if(PT(x)&&x.schemaVersion===S1){let E=x,R=b1(s);if(R>=0&&R<E.requiredBytes)return E.checkedAt=new Date().toISOString(),E.availableBytes=R,Gf(v,E),{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!0}};Xa(v)}else try{Xa(v)}catch{}}catch{try{Xa(v)}catch{}}let y=VT(s,r);if(!y)return{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!1,skippedConcurrent:!0}};try{if(I1(m))return Qa(y),{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!1}};if(!ht(a)){qf(l,{recursive:!0});let J={migratedAt:new Date().toISOString(),freshInstall:!0,version:i};return Gf(m,J),Qa(y),{migrationResult:{migrated:!1,freshInstall:!0,skippedExistingData:!1,skippedDiskSpace:!1}}}let x=Vt(l,Gc),E=l+UT,R=Vt(p,Gc),F=Vt(s,`${CT}-${r}`);if(ht(F)){if(console.log(`[migration] Skipped: previous migration attempt failed (marker at ${F})`),ht(E))try{Oi(E,{recursive:!0,force:!0})}catch{}return Qa(y),{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!1,error:`Previous migration attempt failed (marker at ${F})`}}}ht(E)&&(Oi(E,{recursive:!0,force:!0}),ht(l)&&ht(x)&&Oi(l,{recursive:!0,force:!0}),ht(R)&&Oi(p,{recursive:!0,force:!0}));let H=ht(Vt(d,_T)),qe=ht(l)&&!ht(x),B=MT(p)&&!ht(R)&&!H;if(qe){let J={migratedAt:new Date().toISOString(),skippedExistingDevinData:!0,version:i};return Gf(m,J),Qa(y),{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!0,skippedDiskSpace:!1}}}let C=qv(a,AT,FT);ht(u)&&!B&&(C+=qv(u));let A=Math.ceil(C*LT),ae=b1(s);if(ae>=0&&ae<A){let J={reason:"insufficient_disk",requiredBytes:A,availableBytes:ae,checkedAt:new Date().toISOString(),schemaVersion:S1};return Gf(v,J),Qa(y),{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!0}}}return ht(l)&&Oi(l,{recursive:!0,force:!0}),ht(p)&&ht(R)&&Oi(p,{recursive:!0,force:!0}),B||(qf(p,{recursive:!0}),zf(R,new Date().toISOString())),qf(l,{recursive:!0}),zf(x,new Date().toISOString()),{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!1},pendingMigration:{oldDataDir:a,newDataDir:l,oldExtensionsDir:u,newExtensionsDir:p,newDataFolderDir:d,oldDataFolderName:t,dataFolderName:e,nameShort:r,nameLong:o.nameLong,oldNameLong:o.nameLong.replace(r,n),oldNameShort:n,version:i,hasExistingNewExtData:B,isArgvPrecopy:H,lockHandle:y,totalBytes:C}}}catch(x){try{let E=Vt(l,Gc);ht(l)&&ht(E)&&!I1(m)&&Oi(l,{recursive:!0,force:!0});let R=Vt(p,Gc);ht(p)&&ht(R)&&Oi(p,{recursive:!0,force:!0})}catch{}return Qa(y),console.error(`[migration] prepareMigration failed: ${x}`),{migrationResult:{migrated:!1,freshInstall:!1,skippedExistingData:!1,skippedDiskSpace:!1,error:String(x)}}}}import{resolve as Kv,isAbsolute as jv,join as Ni}from"path";var Hv=process.env.VSCODE_CWD||process.cwd(),jf,ko,WT;function C1(o,r,e){if(!e&&ko!==void 0)return ko;let t=Jv(o,r),n=[t];jv(t)||n.unshift(Hv);let i=Kv(...n);if(e&&!BT(o)){try{let s=T1(e);if(jf=s.migrationResult,s.pendingMigration)WT=s.pendingMigration;else if((jf.skippedDiskSpace||jf.error||jf.skippedConcurrent)&&e.oldNameShort){e.oldDataFolderName&&!process.env.VSCODE_EXTENSIONS&&(process.env.VSCODE_EXTENSIONS=Ni(Hf(),e.oldDataFolderName,"extensions"));let a=Jv(o,e.oldNameShort),l=[a];return jv(a)||l.unshift(Hv),ko=Kv(...l),ko}}catch(s){if(console.error(`[migration] Unexpected error during migration: ${s}`),e.oldNameShort){e.oldDataFolderName&&!process.env.VSCODE_EXTENSIONS&&(process.env.VSCODE_EXTENSIONS=Ni(Hf(),e.oldDataFolderName,"extensions"));let a=Jv(o,e.oldNameShort),l=[a];return jv(a)||l.unshift(Hv),ko=Kv(...l),ko}}ko=i}return i}function BT(o){return!!(process.env.VSCODE_DEV||process.env.VSCODE_PORTABLE||process.env.VSCODE_APPDATA||o["user-data-dir"])}function Jv(o,r){process.env.VSCODE_DEV&&(process.isEmbeddedApp?r="sessions-oss-dev":r="code-oss-dev");let e=process.env.VSCODE_PORTABLE;if(e)return Ni(e,"user-data");let t=process.env.VSCODE_APPDATA;if(t)return Ni(t,r);let n=o["user-data-dir"];if(n)return n;switch(process.platform){case"win32":if(t=process.env.APPDATA,!t){let i=process.env.USERPROFILE;if(typeof i!="string")throw new Error("Windows: Unexpected undefined %USERPROFILE% environment variable");t=Ni(i,"AppData","Roaming")}break;case"darwin":t=Ni(Hf(),"Library","Application Support");break;case"linux":t=process.env.XDG_CONFIG_HOME||Ni(Hf(),".config");break;default:throw new Error("Platform not supported")}return Ni(t,r)}var Jf=class extends ke{constructor(r,e){super(r,{homeDir:$T(),tmpDir:GT(),userDataDir:C1(r,e.nameShort)},e)}};var Qf={exit:"vscode:electron-main->shared-process=exit",ipcReady:"vscode:shared-process->electron-main=ipc-ready",initDone:"vscode:shared-process->electron-main=init-done"};var D1={request:"vscode:createSharedProcessRawConnection",response:"vscode:createSharedProcessRawConnectionResult"};import{constants as qT,promises as zT}from"fs";import{createInterface as KT}from"readline";async function _1(o){if(Gt||he)return;let r;for(let e of["/etc/os-release","/usr/lib/os-release","/etc/lsb-release"])try{r=await zT.open(e,qT.R_OK);break}catch{}if(!r){o("Unable to retrieve release information from known identifier paths.");return}try{let e=new Set(["ID","DISTRIB_ID","ID_LIKE","VERSION_ID","DISTRIB_RELEASE"]),t={id:"unknown"};for await(let n of KT({input:r.createReadStream(),crlfDelay:1/0})){if(!n.includes("="))continue;let i=n.split("=")[0].toUpperCase().trim();if(e.has(i)){let s=n.split("=")[1].replace(/"/g,"").toLowerCase().trim();i==="ID"||i==="DISTRIB_ID"?t.id=s:i==="ID_LIKE"?t.id_like=s:(i==="VERSION_ID"||i==="DISTRIB_RELEASE")&&(t.version_id=s)}}return t}catch(e){o(e)}finally{await r.close()}}var jT="XDG_CURRENT_DESKTOP",Qv="KDE_SESSION_VERSION";function k1(){let o=Fe[jT];if(o){let e=o.split(":").map(t=>t.trim()).filter(t=>t.length>0);for(let t of e)switch(t){case"Unity":{let n=Fe.DESKTOP_SESSION;return n&&n.includes("gnome-fallback")?"GNOME":"UNITY"}case"Deepin":return"DEEPIN";case"GNOME":return"GNOME";case"X-Cinnamon":return"CINNAMON";case"KDE":{let n=Fe[Qv];return n==="5"?"KDE5":n==="6"?"KDE6":"KDE4"}case"Pantheon":return"PANTHEON";case"XFCE":return"XFCE";case"UKUI":return"UKUI";case"LXQt":return"LXQT"}}let r=Fe.DESKTOP_SESSION;if(r)switch(r){case"deepin":return"DEEPIN";case"gnome":case"mate":return"GNOME";case"kde4":case"kde-plasma":return"KDE4";case"kde":return Qv in Fe?"KDE4":"KDE3";case"xfce":case"xubuntu":return"XFCE";case"ukui":return"UKUI"}return"GNOME_DESKTOP_SESSION_ID"in Fe?"GNOME":"KDE_FULL_SESSION"in Fe?Qv in Fe?"KDE4":"KDE3":"UNKNOWN"}import{constants as HT,promises as JT}from"fs";var QT="XDG_SESSION_TYPE",XT="WAYLAND_DISPLAY",YT="XDG_RUNTIME_DIR";async function U1(o){let r=Fe[QT];if(r)return r==="wayland"||r==="x11"?r:"unknown";if(Fe[XT]){let t=Fe[YT];if(t){let n=G(t,"wayland-0");try{return await JT.access(n,HT.R_OK),"wayland"}catch(i){return o(i),"unknown"}}else return"unknown"}else return"x11"}function L1(o,r){if(r)switch(r){case"auto":return o;case"x11":return o==="wayland"?"xwayland":"x11";case"wayland":return"wayland";default:return"unknown"}else return o==="wayland"?"xwayland":"x11"}import{net as bC}from"electron";import{parse as $1}from"url";import{spawn as uC}from"child_process";import{userInfo as aC}from"os";import*as Xv from"os";var M1=/^\d+$/,ZT=/^Microsoft.PowerShell_.*/,eC=/^Microsoft.PowerShellPreview_.*/;var qc;switch(process.arch){case"ia32":qc=1;break;case"arm":case"arm64":qc=2;break;default:qc=0;break}var Ya;process.env.PROCESSOR_ARCHITEW6432?Ya=process.env.PROCESSOR_ARCHITEW6432==="ARM64"?2:0:process.env.PROCESSOR_ARCHITECTURE==="ARM64"?Ya=2:process.env.PROCESSOR_ARCHITECTURE==="X86"?Ya=1:Ya=0;var Uo=class{constructor(r,e,t){this.exePath=r;this.displayName=e;this.knownToExist=t}async exists(){return this.knownToExist===void 0&&(this.knownToExist=await pr.existsFile(this.exePath)),this.knownToExist}};function tC({useAlternateBitness:o=!1}={}){return o?qc===0?process.env["ProgramFiles(x86)"]||null:Ya===0&&process.env.ProgramW6432||null:process.env.ProgramFiles||null}async function Xf({useAlternateBitness:o=!1,findPreview:r=!1}={}){let e=tC({useAlternateBitness:o});if(!e)return null;let t=G(e,"PowerShell");if(!await pr.existsDirectory(t))return null;let n=-1,i=null;for(let l of await ce.readdir(t)){let c=-1;if(r){let u=l.indexOf("-");if(u<0)continue;let p=l.substring(0,u);if(!M1.test(p)||l.substring(u+1)!=="preview")continue;c=parseInt(p,10)}else{if(!M1.test(l))continue;c=parseInt(l,10)}if(c<=n)continue;let d=G(t,l,"pwsh.exe");await pr.existsFile(d)&&(i=d,n=c)}if(!i)return null;let s=e.includes("x86")?" (x86)":"",a=r?" Preview":"";return new Uo(i,`PowerShell${a}${s}`,!0)}async function A1({findPreview:o}={}){if(!process.env.LOCALAPPDATA)return null;let r=G(process.env.LOCALAPPDATA,"Microsoft","WindowsApps");if(!await pr.existsDirectory(r))return null;let{pwshMsixDirRegex:e,pwshMsixName:t}=o?{pwshMsixDirRegex:eC,pwshMsixName:"PowerShell Preview (Store)"}:{pwshMsixDirRegex:ZT,pwshMsixName:"PowerShell (Store)"};for(let n of await ce.readdir(r))if(e.test(n)){let i=G(r,n,"pwsh.exe");return new Uo(i,t)}return null}function rC(){let o=G(Xv.homedir(),".dotnet","tools","pwsh.exe");return new Uo(o,".NET Core PowerShell Global Tool")}function nC(){let o=G(Xv.homedir(),"scoop","apps"),r=G(o,"pwsh","current","pwsh.exe");return new Uo(r,"PowerShell (Scoop)")}function iC(){let o=G(process.env.windir,qc===1&&Ya!==1?"SysNative":"System32","WindowsPowerShell","v1.0","powershell.exe");return new Uo(o,"Windows PowerShell",!0)}async function*oC(){let o=await Xf();o&&(yield o),o=await Xf({useAlternateBitness:!0}),o&&(yield o),o=await A1(),o&&(yield o),o=rC(),o&&(yield o),o=await Xf({findPreview:!0}),o&&(yield o),o=await A1({findPreview:!0}),o&&(yield o),o=await Xf({useAlternateBitness:!0,findPreview:!0}),o&&(yield o),o=await nC(),o&&(yield o),o=iC(),o&&(yield o)}async function*sC(){for await(let o of oC())await o.exists()&&(yield o)}async function F1(){for await(let o of sC())return o;return null}async function O1(o,r){return o===1?he?cC():Tx(r):lC(o,r)}var Yv=null;function lC(o,r){if(Be&&o===2||Gt&&o===3)return"/bin/bash";if(!Yv){let e;if(he)e="/bin/bash";else{if(e=r.SHELL,!e)try{e=aC().shell}catch{}e||(e="sh"),e==="/bin/false"&&(e="/bin/bash")}Yv=e}return Yv}var Zv=null;async function cC(){return Zv||(Zv=(await F1()).exePath),Zv}import mue from"assert";import sue from"minimist";var cue={o:S(1920,null),e:S(1905,null),t:S(1933,null),m:S(1916,null)};var dC={"serve-web":{type:"subcommand",description:"Run a server that displays the editor UI in browsers.",options:{"cli-data-dir":{type:"string",args:"dir",description:S(1895,null)},"disable-telemetry":{type:"boolean"},"telemetry-level":{type:"string"}}},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:S(1895,null)},"disable-telemetry":{type:"boolean"},"telemetry-level":{type:"string"},user:{type:"subcommand",options:{login:{type:"subcommand",options:{provider:{type:"string"},"access-token":{type:"string"}}}}}}},diff:{type:"boolean",cat:"o",alias:"d",args:["file","file"],description:S(1897,null)},merge:{type:"boolean",cat:"o",alias:"m",args:["path1","path2","base","result"],description:S(1917,null)},add:{type:"boolean",cat:"o",alias:"a",args:"folder",description:S(1892,null)},remove:{type:"boolean",cat:"o",args:"folder",description:S(1924,null)},goto:{type:"boolean",cat:"o",alias:"g",args:"file:line[:character]",description:S(1906,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:S(1918,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:S(1925,null)},sessions:{type:"boolean",cat:"o",description:S(1926,null)},wait:{type:"boolean",cat:"o",alias:"w",description:S(1943,null)},waitMarkerFilePath:{type:"string"},locale:{type:"string",cat:"o",args:"locale",description:S(1913,null)},"user-data-dir":{type:"string",cat:"o",args:"dir",description:S(1940,null)},profile:{type:"string",cat:"o",args:"profileName",description:S(1923,null)},help:{type:"boolean",cat:"o",alias:"h",description:S(1907,null)},"extensions-dir":{type:"string",deprecates:["extensionHomePath"],cat:"e",args:"dir",description:S(1904,null)},"extensions-download-dir":{type:"string"},"builtin-extensions-dir":{type:"string"},"list-extensions":{type:"boolean",cat:"e",description:S(1912,null)},"show-versions":{type:"boolean",cat:"e",description:S(1927,null)},category:{type:"string",allowEmptyValue:!0,cat:"e",description:S(1894,null),args:"category"},"install-extension":{type:"string[]",cat:"e",args:"ext-id | path",description:S(1911,null)},"pre-release":{type:"boolean",cat:"e",description:S(1910,null)},"uninstall-extension":{type:"string[]",cat:"e",args:"ext-id",description:S(1935,null)},"update-extensions":{type:"boolean",cat:"e",description:S(1938,null)},"enable-proposed-api":{type:"string[]",allowEmptyValue:!0,cat:"e",args:"ext-id",description:S(1903,null)},"add-mcp":{type:"string[]",cat:"m",args:"json",description:S(1893,null)},version:{type:"boolean",cat:"t",alias:"v",description:S(1942,null)},verbose:{type:"boolean",cat:"t",global:!0,description:S(1941,null)},log:{type:"string[]",cat:"t",args:"level",global:!0,description:S(1915,null)},status:{type:"boolean",alias:"s",cat:"t",description:S(1928,null)},"prof-startup":{type:"boolean",cat:"t",description:S(1922,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:S(1900,null)},"disable-extension":{type:"string[]",cat:"t",args:"ext-id",description:S(1899,null)},sync:{type:"string",cat:"t",description:S(1934,null),args:["on | off"]},"inspect-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugPluginHost"],args:"port",cat:"t",description:S(1909,null)},"inspect-brk-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugBrkPluginHost"],args:"port",cat:"t",description:S(1908,null)},"disable-lcd-text":{type:"boolean",cat:"t",description:S(1902,null)},"disable-gpu":{type:"boolean",cat:"t",description:S(1901,null)},"disable-chromium-sandbox":{type:"boolean",cat:"t",description:S(1898,null)},sandbox:{type:"boolean"},"locate-shell-integration-path":{type:"string",cat:"t",args:["shell"],description:S(1914,null)},telemetry:{type:"boolean",cat:"t",description:S(1931,null)},remote:{type:"string",allowEmptyValue:!0},"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:!0},"inspect-brk-ptyhost":{type:"string",allowEmptyValue:!0},"inspect-search":{type:"string",deprecates:["debugSearch"],allowEmptyValue:!0},"inspect-brk-search":{type:"string",deprecates:["debugBrkSearch"],allowEmptyValue:!0},"inspect-sharedprocess":{type:"string",allowEmptyValue:!0},"inspect-brk-sharedprocess":{type:"string",allowEmptyValue:!0},"export-default-configuration":{type:"string"},"export-policy-data":{type:"string",allowEmptyValue:!0},"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"},transient:{type:"boolean",cat:"t",description:S(1932,null)},"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"},"do-not-include-pack-dependencies":{type:"boolean"},trace:{type:"boolean"},"trace-memory-infra":{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"},"enable-coi":{type:"boolean"},"unresponsive-sample-interval":{type:"string"},"unresponsive-sample-period":{type:"string"},"enable-rdp-display-tracking":{type:"boolean"},"disable-layout-restore":{type:"boolean"},"disable-experiments":{type:"boolean"},"no-proxy-server":{type:"boolean"},"no-sandbox":{type:"boolean",alias:"sandbox"},"proxy-server":{type:"string"},"proxy-bypass-list":{type:"string"},"proxy-pac-url":{type:"string"},"js-flags":{type:"string"},inspect:{type:"string",allowEmptyValue:!0},"inspect-brk":{type:"string",allowEmptyValue:!0},nolazy:{type:"boolean"},"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"},"xdg-portal-required-version":{type:"string"},_:{type:"string[]"}};function ey(o){return o.VSCODE_CLI==="1"}function N1(o,r,e){return Math.min(Math.max(o,r),e)}var ty;async function V1(o,r,e,t){return e["force-disable-user-env"]?(r.trace("resolveShellEnv(): skipped (--force-disable-user-env)"),{}):he?(r.trace("resolveShellEnv(): skipped (Windows)"),{}):ey(t)&&!e["force-user-env"]?(r.trace("resolveShellEnv(): skipped (VSCODE_CLI is set)"),{}):(ey(t)?r.trace("resolveShellEnv(): running (--force-user-env)"):r.trace("resolveShellEnv(): running (macOS/Linux)"),ty||(ty=Ke.withAsyncBody(async(n,i)=>{let s=new mt,a=1e4,l=o.getValue("application.shellEnvironmentResolutionTimeout");typeof l=="number"&&(a=N1(l,1,120)*1e3);let c=setTimeout(()=>{s.dispose(!0),i(new Error(S(2294,null)))},a);try{n(await pC(r,s.token))}catch(d){!lr(d)&&!s.token.isCancellationRequested?i(new Error(S(2292,null,_t(d)))):n({})}finally{clearTimeout(c),s.dispose()}})),ty)}async function pC(o,r){let e=process.env.ELECTRON_RUN_AS_NODE;o.trace("getUnixShellEnvironment#runAsNode",e);let t=process.env.ELECTRON_NO_ATTACH_CONSOLE;o.trace("getUnixShellEnvironment#noAttach",t);let n=Le().replace(/-/g,"").substr(0,12),i=new RegExp(n+"({.*})"+n),s={...process.env,ELECTRON_RUN_AS_NODE:"1",ELECTRON_NO_ATTACH_CONSOLE:"1",VSCODE_RESOLVING_ENVIRONMENT:"1"};o.trace("getUnixShellEnvironment#env",s);let a=await O1(bn,s);return o.trace("getUnixShellEnvironment#shell",a),new Promise((l,c)=>{if(r.isCancellationRequested)return c(new We);let d=lt(a),u,p,m="";/^(?:pwsh|powershell)(?:-preview)?$/.test(d)?(u=`& '${process.execPath}' ${m} -p '''${n}'' + JSON.stringify(process.env) + ''${n}'''`,p=["-Login","-Command"]):d==="nu"?(u=`^'${process.execPath}' ${m} -p '"${n}" + JSON.stringify(process.env) + "${n}"'`,p=["-i","-l","-c"]):d==="xonsh"?(u=`import os, json; print("${n}", json.dumps(dict(os.environ)), "${n}")`,p=["-i","-l","-c"]):(u=`'${process.execPath}' ${m} -p '"${n}" + JSON.stringify(process.env) + "${n}"'`,d==="tcsh"||d==="csh"?p=["-ic"]:p=["-i","-l","-c"]),o.trace("getUnixShellEnvironment#spawn",JSON.stringify(p),u);let h=uC(a,[...p,u],{detached:!0,stdio:["ignore","pipe","pipe"],env:s});r.onCancellationRequested(()=>(h.kill(),c(new We))),h.on("error",x=>{o.error("getUnixShellEnvironment#errorChildProcess",_t(x)),c(x)});let v=[];h.stdout.on("data",x=>v.push(x));let y=[];h.stderr.on("data",x=>y.push(x)),h.on("close",(x,E)=>{let R=Buffer.concat(v).toString("utf8");o.trace("getUnixShellEnvironment#raw",R);let F=Buffer.concat(y).toString("utf8");if(F.trim()&&o.trace("getUnixShellEnvironment#stderr",F),x||E)return c(new Error(S(2293,null,x,E)));let H=i.exec(R),qe=H?H[1]:"{}";try{let B=JSON.parse(qe);e?B.ELECTRON_RUN_AS_NODE=e:delete B.ELECTRON_RUN_AS_NODE,t?B.ELECTRON_NO_ATTACH_CONSOLE=t:delete B.ELECTRON_NO_ATTACH_CONSOLE,delete B.VSCODE_RESOLVING_ENVIRONMENT,delete B.XDG_RUNTIME_DIR,o.trace("getUnixShellEnvironment#result",B),l(B)}catch(B){o.error("getUnixShellEnvironment#errorCaught",_t(B)),c(B)}})})}import{parse as W1}from"url";function fC(o,r){return o.protocol==="http:"?r.HTTP_PROXY||r.http_proxy||null:o.protocol==="https:"&&(r.HTTPS_PROXY||r.https_proxy||r.HTTP_PROXY||r.http_proxy)||null}async function B1(o,r,e={}){let t=W1(o),n=e.proxyUrl||fC(t,r);if(!n)return null;let i=W1(n);if(!/^https?:$/.test(i.protocol||""))return null;let s={host:i.hostname||"",port:(i.port?+i.port:0)||(i.protocol==="https"?443:80),auth:i.auth,rejectUnauthorized:Bt(e.strictSSL)?e.strictSSL:!0};if(t.protocol==="http:"){let{default:a}=await import("http-proxy-agent");return new a.HttpProxyAgent(n,s)}else{let{default:a}=await import("https-proxy-agent");return new a.HttpsProxyAgent(n,s)}}import{createGunzip as mC}from"zlib";var gC=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ENETDOWN","ENETUNREACH","EPROTO"]),hC=/^(GET|HEAD|OPTIONS)$/i;function vC(o){if(o instanceof Error){let r=o.code;return!!r&&gC.has(r)}return!1}var Za=class extends Ou{constructor(e,t,n,i){super(i);this.machine=e;this.configurationService=t;this.environmentService=n;this.configure(),this._register(t.onDidChangeConfiguration(s=>{s.affectsConfiguration("http")&&this.configure()}))}configure(){this.proxyUrl=this.getConfigValue("http.proxy"),this.strictSSL=!!this.getConfigValue("http.proxyStrictSSL"),this.authorization=this.getConfigValue("http.proxyAuthorization")}async request(e,t){let{proxyUrl:n,strictSSL:i}=this,s;try{s=await V1(this.configurationService,this.logService,this.environmentService.args,process.env)}catch(c){this.shellEnvErrorLogged||(this.shellEnvErrorLogged=!0,this.logService.error("resolving shell environment failed",ee(c)))}let a={...process.env,...s},l=e.agent?e.agent:await B1(e.url||"",a,{proxyUrl:n,strictSSL:i});return e.agent=l,e.strictSSL=i,this.authorization&&(e.headers={...e.headers||{},"Proxy-Authorization":this.authorization}),this.logAndRequest(e,()=>G1(e,t))}async resolveProxy(e){}async lookupAuthorization(e){}async lookupKerberosAuthorization(e){try{let t=this.getConfigValue("http.proxyKerberosServicePrincipal");return"Negotiate "+await yC(e,t,this.logService,"RequestService#lookupKerberosAuthorization")}catch(t){this.logService.debug("RequestService#lookupKerberosAuthorization Kerberos authentication failed",t);return}}async loadCertificates(){return(await import("@vscode/proxy-agent")).loadSystemCertificates({loadSystemCertificatesFromNode:()=>this.getConfigValue("http.systemCertificatesNode",jg),log:this.logService})}getConfigValue(e,t){if(this.machine==="remote")return this.configurationService.getValue(e);let n=this.configurationService.inspect(e);return n.userLocalValue??n.defaultValue??t}};Za=b([g(1,Q),g(2,nt),g(3,V)],Za);async function yC(o,r,e,t){let n=await import("kerberos"),i=n.default||n,s=new URL(o),a=r||(process.platform==="win32"?`HTTP/${s.hostname}`:`HTTP@${s.hostname}`);return e.debug(`${t} Kerberos authentication lookup`,`proxyURL:${s}`,`spn:${a}`),(await i.initializeClient(a)).step("")}async function SC(o){return($1(o.url).protocol==="https:"?await import("https"):await import("http")).request}async function G1(o,r){let t,n=hC.test(o.type||"GET");for(let i=1;i<=3;i++)try{return await IC(o,r)}catch(s){if(t=s,s instanceof We||!n||!vC(s)||i===3)throw s;await Lr(100*i,r)}throw t}async function IC(o,r){return Ke.withAsyncBody(async(e,t)=>{let n=$1(o.url),i=o.getRawRequest?o.getRawRequest(o):await SC(o),s={hostname:n.hostname,port:n.port?parseInt(n.port):n.protocol==="https:"?443:80,protocol:n.protocol,path:n.path,method:o.type||"GET",headers:o.headers,agent:o.agent,rejectUnauthorized:Bt(o.strictSSL)?o.strictSSL:!0};o.user&&o.password&&(s.auth=o.user+":"+o.password),o.disableCache&&(s.cache="no-store");let a=i(s,c=>{let d=Un(o.followRedirects)?o.followRedirects:3;if(c.statusCode&&c.statusCode>=300&&c.statusCode<400&&d>0&&c.headers.location)G1({...o,url:c.headers.location,followRedirects:d-1},r).then(e,t);else{let u=c;!o.isChromiumNetwork&&c.headers["content-encoding"]==="gzip"&&(u=c.pipe(mC())),e({res:c,stream:KS(u)})}});if(a.on("error",t),o.timeout)if(o.isChromiumNetwork){let c=setTimeout(()=>{a.abort(),t(new Error(`Request timeout after ${o.timeout}ms`))},o.timeout);a.on("response",()=>clearTimeout(c)),a.on("error",()=>clearTimeout(c)),a.on("abort",()=>clearTimeout(c))}else a.setTimeout(o.timeout);o.isChromiumNetwork&&a.removeHeader("Content-Length"),o.data&&typeof o.data=="string"&&a.write(o.data),a.end();let l=r.onCancellationRequested(()=>{l.dispose(),a.abort(),t(new We)});a.on("response",()=>l.dispose()),a.on("error",()=>l.dispose())})}function xC(o){return bC.request}var el=class extends Za{constructor(r,e,t){super("local",r,e,t)}request(r,e){return super.request({...r||{},getRawRequest:xC,isChromiumNetwork:!0},e)}};el=b([g(0,Q),g(1,nt),g(2,V)],el);var ry="initializing-default-extensions",tl=class extends T{constructor(e,t,n,i,s,a){super();this.environmentService=e;this.extensionManagementService=t;this.fileService=i;this.logService=s;this.productService=a;he&&n.getBoolean(ry,-1,!0)&&(n.store(ry,!0,-1,1),this.initializeDefaultExtensions().then(()=>n.store(ry,!1,-1,1)))}async initializeDefaultExtensions(){let e=this.getDefaultExtensionVSIXsLocation(),t;try{if(t=await this.fileService.resolve(e),!t.children){this.logService.debug("There are no default extensions to initialize",e.toString());return}}catch(i){if(_e(i)===1){this.logService.debug("There are no default extensions to initialize",e.toString());return}this.logService.error("Error initializing extensions",i);return}let n=t.children.filter(i=>i.name.toLowerCase().endsWith(".vsix"));if(n.length===0){this.logService.debug("There are no default extensions to initialize",e.toString());return}this.logService.info("Initializing default extensions",e.toString()),await Promise.all(n.map(async i=>{this.logService.info("Installing default extension",i.resource.toString());try{await this.extensionManagementService.install(i.resource,{donotIncludePackAndDependencies:!0,keepExisting:!1}),this.logService.info("Default extension installed",i.resource.toString())}catch(s){this.logService.error("Error installing default extension",i.resource.toString(),ee(s))}})),this.logService.info("Default extensions initialized",e.toString())}getDefaultExtensionVSIXsLocation(){return this.productService.win32VersionedUpdate?P.file(G($e($e($e(this.environmentService.appRoot))),"bootstrap","extensions")):P.file(G($e($e(this.environmentService.appRoot)),"bootstrap","extensions"))}};tl=b([g(0,nt),g(1,oa),g(2,K),g(3,W),g(4,V),g(5,ne)],tl);function EC(o){return o.type==="gallery"}function wC(o){return o.type===1||o.type===0}var PC=/^(?<version>\d+\.\d+\.\d+(-.*)?)(@(?<platform>.+))?$/,Vi=class extends T{constructor(e,t){super();this.configurationService=t;this._onDidChangeAllowedExtensions=this._register(new w);this.onDidChangeAllowedExtensionsConfigValue=this._onDidChangeAllowedExtensions.event;this.publisherOrgs=e.extensionPublisherOrgs?.map(n=>n.toLowerCase())??[],this._allowedExtensionsConfigValue=this.getAllowedExtensionsValue(),this._register(this.configurationService.onDidChangeConfiguration(n=>{n.affectsConfiguration(vu)&&this.refreshAllowedExtensionsConfigValue()}))}get allowedExtensionsConfigValue(){return this._allowedExtensionsConfigValue}refreshAllowedExtensionsConfigValue(){this._allowedExtensionsConfigValue=this.getAllowedExtensionsValue(),this._onDidChangeAllowedExtensions.fire()}getAllowedExtensionsValue(){let e=this.configurationService.getValue(vu);return Vi.normalizeAllowedExtensionsValue(e)}static normalizeAllowedExtensionsValue(e){if(!Re(e)||Array.isArray(e))return;let t=Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]);if(!(t.length===1&&t[0][0]==="*"&&t[0][1]===!0))return Object.fromEntries(t)}isAllowed(e){if(!this._allowedExtensionsConfigValue)return!0;let t,n,i,s,a,l;EC(e)?(t=e.identifier.id.toLowerCase(),n=e.version,s=e.properties.isPreReleaseVersion,a=e.publisher.toLowerCase(),l=e.publisherDisplayName.toLowerCase(),i=e.properties.targetPlatform):wC(e)?(t=e.identifier.id.toLowerCase(),n=e.manifest.version,s=e.preRelease,a=e.manifest.publisher.toLowerCase(),l=e.publisherDisplayName?.toLowerCase(),i=e.targetPlatform):(t=e.id.toLowerCase(),n=e.version??"*",i=e.targetPlatform??"universal",s=e.prerelease??!1,a=e.id.substring(0,e.id.indexOf(".")).toLowerCase(),l=e.publisherDisplayName?.toLowerCase());let c=this._allowedExtensionsConfigValue[t],d=new Qt(S(1968,null));if(!st(c))return Bt(c)?c?!0:d:c==="stable"&&s?new Qt(S(1965,null)):n!=="*"&&Array.isArray(c)&&!c.some(m=>{let h=PC.exec(m);if(h&&h.groups){let{platform:v,version:y}=h.groups;return!(y!==n||i!=="universal"&&v&&i!==v)}return!1})?new Qt(S(1969,null,n)):!0;let u=l&&this.publisherOrgs.includes(l)?l:a,p=this._allowedExtensionsConfigValue[u];return st(p)?this._allowedExtensionsConfigValue["*"]===!0?!0:d:Bt(p)?p?!0:new Qt(S(1967,null)):p==="stable"&&s?new Qt(S(1966,null)):!0}};Vi=b([g(0,ne),g(1,Q)],Vi);var rl=class extends T{constructor(e,t){super();this.productService=e;this.configurationService=t;this.onDidChangeExtensionGalleryManifest=k.None;this.onDidChangeExtensionGalleryManifestStatus=k.None}get extensionGalleryManifestStatus(){return this.productService.extensionsGallery?.serviceUrl?"available":"unavailable"}async getExtensionGalleryManifest(){let e=this.productService.extensionsGallery;if(!e?.serviceUrl)return null;let n=(this.configurationService.inspect("devin.marketplaceExtensionGalleryServiceURL")?.userValue??this.configurationService.inspect("windsurf.marketplaceExtensionGalleryServiceURL")?.userValue)||e.serviceUrl,i=[{id:`${n}/extensionquery`,type:"ExtensionQueryService"},{id:`${n}/{publisher}/{name}/latest`,type:"ExtensionLatestVersionUriTemplate"},{id:`${n}/publishers/{publisher}/extensions/{name}/{version}/stats?statType={statTypeName}`,type:"ExtensionStatisticsUriTemplate"},{id:`${n}/itemName/{publisher}.{name}/version/{version}/statType/{statTypeValue}/vscodewebextension`,type:"WebExtensionStatisticsUriTemplate"}];e.publisherUrl&&i.push({id:`${e.publisherUrl}/{publisher}`,type:"PublisherViewUriTemplate"});let a=(this.configurationService.inspect("devin.marketplaceGalleryItemURL")?.userValue??this.configurationService.inspect("windsurf.marketplaceGalleryItemURL")?.userValue)||e.itemUrl;a&&(i.push({id:`${a}?itemName={publisher}.{name}`,type:"ExtensionDetailsViewUriTemplate"}),i.push({id:`${a}?itemName={publisher}.{name}&ssr=false#review-details`,type:"ExtensionRatingViewUriTemplate"})),e.resourceUrlTemplate&&i.push({id:e.resourceUrlTemplate,type:"ExtensionResourceUriTemplate"});let l=[{name:"Tag",value:1},{name:"ExtensionId",value:4},{name:"Category",value:5},{name:"ExtensionName",value:7},{name:"Target",value:8},{name:"Featured",value:9},{name:"SearchText",value:10},{name:"ExcludeWithFlags",value:12}],c=[{name:"NoneOrRelevance",value:0},{name:"LastUpdatedDate",value:1},{name:"Title",value:2},{name:"PublisherName",value:3},{name:"InstallCount",value:4},{name:"AverageRating",value:6},{name:"PublishedDate",value:10},{name:"WeightedRating",value:12}],d=[{name:"None",value:0},{name:"IncludeVersions",value:1},{name:"IncludeFiles",value:2},{name:"IncludeCategoryAndTags",value:4},{name:"IncludeSharedAccounts",value:8},{name:"IncludeVersionProperties",value:16},{name:"ExcludeNonValidated",value:32},{name:"IncludeInstallationTargets",value:64},{name:"IncludeAssetUri",value:128},{name:"IncludeStatistics",value:256},{name:"IncludeLatestVersionOnly",value:512},{name:"Unpublished",value:4096},{name:"IncludeNameConflictInfo",value:32768},{name:"IncludeLatestPrereleaseAndStableVersionOnly",value:65536}];return{version:"",resources:i,capabilities:{extensionQuery:{filtering:l,sorting:c,flags:d},signing:{allPublicRepositorySigned:!1}}}}};rl=b([g(0,ne),g(1,Q)],rl);var nl=class extends rl{constructor(e,t,n){super(t,n);this._onDidChangeExtensionGalleryManifest=this._register(new w);this.onDidChangeExtensionGalleryManifest=this._onDidChangeExtensionGalleryManifest.event;this._onDidChangeExtensionGalleryManifestStatus=this._register(new w);this.onDidChangeExtensionGalleryManifestStatus=this._onDidChangeExtensionGalleryManifestStatus.event;this.barrier=new Kr;e.registerChannel("extensionGalleryManifest",{listen:()=>k.None,call:async(i,s,a)=>{if(s==="setExtensionGalleryManifest")return Promise.resolve(this.setExtensionGalleryManifest(a[0]));throw new Error("Invalid call")}})}get extensionGalleryManifestStatus(){return this._extensionGalleryManifest?"available":"unavailable"}async getExtensionGalleryManifest(){return await this.barrier.wait(),this._extensionGalleryManifest??null}setExtensionGalleryManifest(e){this._extensionGalleryManifest=e,this._onDidChangeExtensionGalleryManifest.fire(e),this._onDidChangeExtensionGalleryManifestStatus.fire(this.extensionGalleryManifestStatus),this.barrier.open()}};nl=b([g(1,ne),g(2,Q)],nl);var mfe=L("IWebContentExtractorService"),ny=L("ISharedWebContentExtractorService");var Yf=class{async readImage(r,e){if(!e.isCancellationRequested)try{let t=await fetch(r.toString(!0),{headers:{Accept:"image/*","User-Agent":"Mozilla/5.0"}}),n=t.headers.get("content-type");return!t.ok||!n?.startsWith("image/")||!/(webp|jpg|jpeg|gif|png|bmp)$/i.test(n)?void 0:U.wrap(await t.bytes())}catch(t){console.log(t);return}}};var Lo=L("IMcpGalleryService"),iy=L("IMcpManagementService"),Mo=L("IAllowedMcpServersService"),Zf="chat.mcp.access";var Wi=L("IMcpResourceScannerService"),Ao=class extends T{constructor(e,t){super();this.fileService=e;this.uriIdentityService=t;this.resourcesAccessQueueMap=new He}async scanMcpServers(e,t){return this.withProfileMcpServers(e,t)}async addMcpServers(e,t,n){await this.withProfileMcpServers(t,n,i=>{let s=i.inputs??[],a=i.servers??{};for(let{name:l,config:c,inputs:d}of e)if(a[l]=c,d){let u=new Set(s.map(m=>m.id)),p=d.filter(m=>!u.has(m.id));s=[...s,...p]}return{servers:a,inputs:s,sandbox:i.sandbox}})}async removeMcpServers(e,t,n){await this.withProfileMcpServers(t,n,i=>{for(let s of e)i.servers?.[s]&&delete i.servers[s];return i})}async withProfileMcpServers(e,t,n){return this.getResourceAccessQueue(e).queue(async()=>{t=t??2;let i={};try{let s=await this.fileService.readFile(e),a=[],l=je(s.value.toString(),a,{allowTrailingComma:!0,allowEmptyContent:!0})||{};if(a.length>0)throw new Error("Failed to parse scanned MCP servers: "+a.join(", "));if(t===2)i=this.fromUserMcpServers(l);else if(t===6)i=this.fromWorkspaceFolderMcpServers(l);else if(t===5){let c=l;c.settings?.mcp&&(i=this.fromWorkspaceFolderMcpServers(c.settings?.mcp))}}catch(s){if(_e(s)!==1)throw s}return n&&(i=n(i??{}),t===2?await this.writeScannedMcpServers(e,i):t===6?await this.writeScannedMcpServersToWorkspaceFolder(e,i):t===5?await this.writeScannedMcpServersToWorkspace(e,i):vm(t,`Invalid Target: ${SI(t)}`)),i})}async writeScannedMcpServers(e,t){t.servers&&Object.keys(t.servers).length>0||t.inputs&&t.inputs.length>0?await this.fileService.writeFile(e,U.fromString(JSON.stringify(t,null,"	"))):await this.fileService.del(e)}async writeScannedMcpServersToWorkspaceFolder(e,t){await this.fileService.writeFile(e,U.fromString(JSON.stringify(t,null,"	")))}async writeScannedMcpServersToWorkspace(e,t){let n;try{let i=await this.fileService.readFile(e),s=[];if(n=je(i.value.toString(),s,{allowTrailingComma:!0,allowEmptyContent:!0}),s.length>0)throw new Error("Failed to parse scanned MCP servers: "+s.join(", "))}catch(i){if(_e(i)!==1)throw i;n={settings:{}}}n.settings||(n.settings={}),n.settings.mcp=t,await this.fileService.writeFile(e,U.fromString(JSON.stringify(n,null,"	")))}fromUserMcpServers(e){let t={inputs:e.inputs,sandbox:e.sandbox},n=Object.entries(e.servers??{});if(n.length>0){t.servers={};for(let[i,s]of n)t.servers[i]=this.sanitizeServer(s,e.sandbox)}return t}fromWorkspaceFolderMcpServers(e){let t={inputs:e.inputs,sandbox:e.sandbox},n=Object.entries(e.servers??{});if(n.length>0){t.servers={};for(let[i,s]of n)t.servers[i]=this.sanitizeServer(s,e.sandbox)}return t}sanitizeServer(e,t){let n;if(e.config){let i=e;n={...i.config,version:i.version,gallery:i.gallery}}else n=e;return(n.type===void 0||n.type!=="http"&&n.type!=="stdio")&&(n.type=n.command?"stdio":"http"),t&&n.type==="stdio"&&!n.sandbox&&n.sandboxEnabled&&(n.sandbox=t),n}getResourceAccessQueue(e){let t=this.resourcesAccessQueueMap.get(e);return t||(t=new kr,this.resourcesAccessQueueMap.set(e,t)),t}};Ao=b([g(0,W),g(1,te)],Ao);_f(Wi,Ao,1);var il=class extends T{constructor(e){super();this.logService=e}getMcpServerConfigurationFromManifest(e,t){if(t==="remote"&&e.remotes?.length){let c=e.remotes[0].url,d=e.remotes[0].headers??[],{inputs:u,variables:p}=this.processKeyValueInputs(c.startsWith("https://api.githubcopilot.com/mcp")?d.filter(m=>m.name.toLowerCase()!=="authorization"):d);return{mcpServerConfiguration:{config:{type:"http",url:e.remotes[0].url,headers:Object.keys(u).length?u:void 0},inputs:p.length?p:void 0},notices:[]}}let n=e.packages?.find(c=>c.registryType===t)??e.packages?.[0];if(!n)throw new Error("No server package found");let i=[],s=[],a={},l=[];if(n.registryType==="oci"&&(i.push("run"),i.push("-i"),i.push("--rm")),n.runtimeArguments?.length){let c=this.processArguments(n.runtimeArguments??[]);i.push(...c.args),s.push(...c.variables),l.push(...c.notices)}if(n.environmentVariables?.length){let{inputs:c,variables:d,notices:u}=this.processKeyValueInputs(n.environmentVariables??[]);s.push(...d),l.push(...u);for(let[p,m]of Object.entries(c))a[p]=m,n.registryType==="oci"&&(i.push("-e"),i.push(p))}switch(n.registryType){case"npm":n.registryBaseUrl&&i.push("--registry",n.registryBaseUrl),i.push(n.version?`${n.identifier}@${n.version}`:n.identifier);break;case"pypi":n.registryBaseUrl&&i.push("--index-url",n.registryBaseUrl),i.push(n.version?`${n.identifier}@${n.version}`:n.identifier);break;case"oci":{let c=n.registryBaseUrl?`${n.registryBaseUrl}/${n.identifier}`:n.identifier;i.push(n.version?`${c}:${n.version}`:c);break}case"nuget":i.push(n.version?`${n.identifier}@${n.version}`:n.identifier),i.push("--yes"),n.registryBaseUrl&&i.push("--source",n.registryBaseUrl),n.packageArguments?.length&&i.push("--");break}if(n.packageArguments?.length){let c=this.processArguments(n.packageArguments);i.push(...c.args),s.push(...c.variables),l.push(...c.notices)}return{notices:l,mcpServerConfiguration:{config:{type:"stdio",command:this.getCommandName(n.registryType),args:i.length?i:void 0,env:Object.keys(a).length?a:void 0},inputs:s.length?s:void 0}}}getCommandName(e){switch(e){case"npm":return"npx";case"oci":return"docker";case"pypi":return"uvx";case"nuget":return"dnx"}return e}getVariables(e){let t=[];for(let[n,i]of Object.entries(e))t.push({id:n,type:i.choices?"pickString":"promptString",description:i.description??"",password:!!i.isSecret,default:i.default,options:i.choices});return t}processKeyValueInputs(e){let t=[],n={},i=[];for(let s of e){let a=s.variables?this.getVariables(s.variables):[],l=s.value||"";if(a.length){for(let c of a)l=l.replace(`{${c.id}}`,`\${input:${c.id}}`);i.push(...a)}else!l&&(s.description||s.choices||s.default!==void 0)&&(i.push({id:s.name,type:s.choices?"pickString":"promptString",description:s.description??"",password:!!s.isSecret,default:s.default,options:s.choices}),l=`\${input:${s.name}}`);n[s.name]=l}return{inputs:n,variables:i,notices:t}}processArguments(e){let t=[],n=[],i=[];for(let s of e){let a=s.variables?this.getVariables(s.variables):[];if(s.type==="positional"){let l=s.value;if(l){for(let c of a)l=l.replace(`{${c.id}}`,`\${input:${c.id}}`);t.push(l),a.length&&n.push(...a)}else s.valueHint&&(s.description||s.default!==void 0)?(n.push({id:s.valueHint,type:"promptString",description:s.description??"",password:!1,default:s.default}),t.push(`\${input:${s.valueHint}}`)):t.push(s.valueHint??"")}else if(s.type==="named"){if(!s.name){i.push(`Named argument is missing a name. ${JSON.stringify(s)}`);continue}if(t.push(s.name),s.value){let l=s.value;for(let c of a)l=l.replace(`{${c.id}}`,`\${input:${c.id}}`);t.push(l),a.length&&n.push(...a)}else if(s.description||s.default!==void 0){let l=s.name.replace(/^--?/,"");n.push({id:l,type:"promptString",description:s.description??"",password:!1,default:s.default}),t.push(`\${input:${l}}`)}}}return{args:t,variables:n,notices:i}}};il=b([g(0,V)],il);var zc=class extends il{constructor(e,t,n,i,s,a,l){super(a);this.mcpResource=e;this.target=t;this.mcpGalleryService=n;this.fileService=i;this.uriIdentityService=s;this.mcpResourceScannerService=l;this.local=new Map;this._onInstallMcpServer=this._register(new w);this.onInstallMcpServer=this._onInstallMcpServer.event;this._onDidInstallMcpServers=this._register(new w);this._onDidUpdateMcpServers=this._register(new w);this._onUninstallMcpServer=this._register(new w);this._onDidUninstallMcpServer=this._register(new w);this.reloadConfigurationScheduler=this._register(new It(()=>this.updateLocal(),50))}get onDidInstallMcpServers(){return this._onDidInstallMcpServers.event}get onDidUpdateMcpServers(){return this._onDidUpdateMcpServers.event}get onUninstallMcpServer(){return this._onUninstallMcpServer.event}get onDidUninstallMcpServer(){return this._onDidUninstallMcpServer.event}initialize(){return this.initializePromise||(this.initializePromise=(async()=>{try{this.local=await this.populateLocalServers()}finally{this.startWatching()}})()),this.initializePromise}async populateLocalServers(){this.logService.trace("AbstractMcpResourceManagementService#populateLocalServers",this.mcpResource.toString());let e=new Map;try{let t=await this.mcpResourceScannerService.scanMcpServers(this.mcpResource,this.target);t.servers&&await Promise.allSettled(Object.entries(t.servers).map(async([n,i])=>{let s=await this.scanLocalServer(n,i);e.set(n,s)}))}catch(t){throw this.logService.debug("Could not read user MCP servers:",t),t}return e}startWatching(){this._register(this.fileService.watch(this.mcpResource)),this._register(this.fileService.onDidFilesChange(e=>{e.affects(this.mcpResource)&&this.reloadConfigurationScheduler.schedule()}))}async updateLocal(){try{let e=await this.populateLocalServers(),t=[],n=[],i=[...this.local.keys()].filter(s=>!e.has(s));for(let s of i)this.local.delete(s);for(let[s,a]of e){let l=this.local.get(s);l?it(l,a)||(n.push(a),this.local.set(s,a)):(t.push(a),this.local.set(s,a))}for(let s of i)this.local.delete(s),this._onDidUninstallMcpServer.fire({name:s,mcpResource:this.mcpResource});n.length&&this._onDidUpdateMcpServers.fire(n.map(s=>({name:s.name,local:s,mcpResource:this.mcpResource}))),t.length&&this._onDidInstallMcpServers.fire(t.map(s=>({name:s.name,local:s,mcpResource:this.mcpResource})))}catch(e){this.logService.error("Failed to load installed MCP servers:",e)}}async getInstalled(){return await this.initialize(),Array.from(this.local.values())}async scanLocalServer(e,t){let n=await this.getLocalServerInfo(e,t);return n||(n={name:e,version:t.version,galleryUrl:ue(t.gallery)?t.gallery:void 0}),{name:e,config:t,mcpResource:this.mcpResource,version:n.version,location:n.location,displayName:n.displayName,description:n.description,publisher:n.publisher,publisherDisplayName:n.publisherDisplayName,galleryUrl:n.galleryUrl,galleryId:n.galleryId,repositoryUrl:n.repositoryUrl,readmeUrl:n.readmeUrl,icon:n.icon,codicon:n.codicon,manifest:n.manifest,source:t.gallery?"gallery":"local"}}async install(e,t){this.logService.trace("MCP Management Service: install",e.name),this._onInstallMcpServer.fire({name:e.name,mcpResource:this.mcpResource});try{await this.mcpResourceScannerService.addMcpServers([e],this.mcpResource,this.target),await this.updateLocal();let n=this.local.get(e.name);if(!n)throw new Error(`Failed to install MCP server: ${e.name}`);return n}catch(n){throw this._onDidInstallMcpServers.fire([{name:e.name,error:n,mcpResource:this.mcpResource}]),n}}async uninstall(e,t){this.logService.trace("MCP Management Service: uninstall",e.name),this._onUninstallMcpServer.fire({name:e.name,mcpResource:this.mcpResource});try{if(!(await this.mcpResourceScannerService.scanMcpServers(this.mcpResource,this.target)).servers)return;await this.mcpResourceScannerService.removeMcpServers([e.name],this.mcpResource,this.target),e.location&&await this.fileService.del(P.revive(e.location),{recursive:!0}),await this.updateLocal()}catch(n){throw this._onDidUninstallMcpServer.fire({name:e.name,error:n,mcpResource:this.mcpResource}),n}}};zc=b([g(2,Lo),g(3,W),g(4,te),g(5,V),g(6,Wi)],zc);var Fo=class extends zc{constructor(r,e,t,n,i,s,a){super(r,2,e,t,n,i,s),this.mcpLocation=n.extUri.joinPath(a.userRoamingDataHome,"mcp")}async installFromGallery(r,e){throw new Error("Not supported")}async updateMetadata(r,e){await this.updateMetadataFromGallery(e),await this.updateLocal();let t=(await this.getInstalled()).find(n=>n.name===r.name);if(!t)throw new Error(`Failed to find MCP server: ${r.name}`);return t}async updateMetadataFromGallery(r){let e=r.configuration,t=this.getLocation(r.name,r.version),n=this.uriIdentityService.extUri.joinPath(t,"manifest.json"),i={galleryUrl:r.galleryUrl,galleryId:r.id,name:r.name,displayName:r.displayName,description:r.description,version:r.version,publisher:r.publisher,publisherDisplayName:r.publisherDisplayName,repositoryUrl:r.repositoryUrl,licenseUrl:r.license,icon:r.icon,codicon:r.codicon,manifest:e};if(await this.fileService.writeFile(n,U.fromString(JSON.stringify(i))),r.readmeUrl||r.readme){let s=r.readme?r.readme:await this.mcpGalleryService.getReadme(r,Y.None);await this.fileService.writeFile(this.uriIdentityService.extUri.joinPath(t,"README.md"),U.fromString(s))}return e}async getLocalServerInfo(r,e){let t,n,i;if(e.gallery){n=this.getLocation(r,e.version);let s=this.uriIdentityService.extUri.joinPath(n,"manifest.json");try{let a=await this.fileService.readFile(s);t=JSON.parse(a.value.toString()),t.galleryUrl?.includes("/v0/")&&(t.galleryUrl=t.galleryUrl.substring(0,t.galleryUrl.indexOf("/v0/")),await this.fileService.writeFile(s,U.fromString(JSON.stringify(t)))),t.location=n,i=this.uriIdentityService.extUri.joinPath(n,"README.md"),await this.fileService.exists(i)||(i=void 0),t.readmeUrl=i}catch(a){this.logService.error("MCP Management Service: failed to read manifest",n.toString(),a)}}return t}getLocation(r,e){return r=r.replace("/","."),this.uriIdentityService.extUri.joinPath(this.mcpLocation,e?`${r}-${e}`:r)}installFromUri(r,e){throw new Error("Method not supported.")}canInstall(){throw new Error("Not supported")}};Fo=b([g(1,Lo),g(2,W),g(3,te),g(4,V),g(5,Wi),g(6,X)],Fo);var Oo=class extends il{constructor(e,t){super(t);this.allowedMcpServersService=e}canInstall(e){let t=this.allowedMcpServersService.isAllowed(e);return t!==!0?new Qt(S(2164,null,t.value)):!0}};Oo=b([g(0,Mo),g(1,V)],Oo);var ol=class extends Oo{constructor(e,t,n,i){super(e,t);this.userDataProfilesService=n;this.instantiationService=i;this._onInstallMcpServer=this._register(new w);this.onInstallMcpServer=this._onInstallMcpServer.event;this._onDidInstallMcpServers=this._register(new w);this.onDidInstallMcpServers=this._onDidInstallMcpServers.event;this._onDidUpdateMcpServers=this._register(new w);this.onDidUpdateMcpServers=this._onDidUpdateMcpServers.event;this._onUninstallMcpServer=this._register(new w);this.onUninstallMcpServer=this._onUninstallMcpServer.event;this._onDidUninstallMcpServer=this._register(new w);this.onDidUninstallMcpServer=this._onDidUninstallMcpServer.event;this.mcpResourceManagementServices=new He}getMcpResourceManagementService(e){let t=this.mcpResourceManagementServices.get(e);if(!t){let n=new se,i=n.add(this.createMcpResourceManagementService(e));n.add(i.onInstallMcpServer(s=>this._onInstallMcpServer.fire(s))),n.add(i.onDidInstallMcpServers(s=>this._onDidInstallMcpServers.fire(s))),n.add(i.onDidUpdateMcpServers(s=>this._onDidUpdateMcpServers.fire(s))),n.add(i.onUninstallMcpServer(s=>this._onUninstallMcpServer.fire(s))),n.add(i.onDidUninstallMcpServer(s=>this._onDidUninstallMcpServer.fire(s))),this.mcpResourceManagementServices.set(e,t={service:i,dispose:()=>n.dispose()})}return t.service}async getInstalled(e){let t=e||this.userDataProfilesService.defaultProfile.mcpResource;return this.getMcpResourceManagementService(t).getInstalled()}async install(e,t){let n=t?.mcpResource||this.userDataProfilesService.defaultProfile.mcpResource;return this.getMcpResourceManagementService(n).install(e,t)}async uninstall(e,t){let n=t?.mcpResource||this.userDataProfilesService.defaultProfile.mcpResource;return this.getMcpResourceManagementService(n).uninstall(e,t)}async installFromGallery(e,t){let n=t?.mcpResource||this.userDataProfilesService.defaultProfile.mcpResource;return this.getMcpResourceManagementService(n).installFromGallery(e,t)}async updateMetadata(e,t,n){return this.getMcpResourceManagementService(n||this.userDataProfilesService.defaultProfile.mcpResource).updateMetadata(e,t)}dispose(){this.mcpResourceManagementServices.forEach(e=>e.dispose()),this.mcpResourceManagementServices.clear(),super.dispose()}createMcpResourceManagementService(e){return this.instantiationService.createInstance(Fo,e)}};ol=b([g(0,Mo),g(1,V),g(2,fe),g(3,bt)],ol);var Kc=class extends Fo{constructor(r,e,t,n,i,s,a){super(r,e,t,n,i,s,a)}async installFromGallery(r,e){this.logService.trace("MCP Management Service: installGallery",r.name,r.galleryUrl),this._onInstallMcpServer.fire({name:r.name,mcpResource:this.mcpResource});try{let t=await this.updateMetadataFromGallery(r),n=e?.packageType??(t.remotes?.length?"remote":t.packages?.[0]?.registryType??"remote"),{mcpServerConfiguration:i,notices:s}=this.getMcpServerConfigurationFromManifest(t,n);s.length>0&&this.logService.warn(`MCP Management Service: Warnings while installing ${r.name}`,s);let a={name:r.name,config:{...i.config,gallery:r.galleryUrl??!0,version:r.version},inputs:i.inputs};await this.mcpResourceScannerService.addMcpServers([a],this.mcpResource,this.target),await this.updateLocal();let l=(await this.getInstalled()).find(c=>c.name===r.name);if(!l)throw new Error(`Failed to install MCP server: ${r.name}`);return l}catch(t){throw this._onDidInstallMcpServers.fire([{name:r.name,source:r,error:t,mcpResource:this.mcpResource}]),t}}};Kc=b([g(1,Lo),g(2,W),g(3,te),g(4,V),g(5,Wi),g(6,X)],Kc);var em=class extends ol{createMcpResourceManagementService(r){return this.instantiationService.createInstance(Kc,r)}};var tm=L("IMcpGalleryManifestService");function No(o,r){let[e,t]=r.split("/");for(let n of o.resources){let[i,s]=n.type.split("/");if(i===e){if(!t||s===t)return n.id;break}}}var z1;(n=>{n.VERSION="v0-2025-07-09",n.SCHEMA="https://static.modelcontextprotocol.io/schemas/2025-07-09/server.schema.json";class e{toRawGalleryMcpServerResult(s){if(!s||typeof s!="object"||!Array.isArray(s.servers))return;let a=s,l=[];for(let c of a.servers){let d=this.toRawGalleryMcpServer(c);if(!d)return;l.push(d)}return{metadata:{count:a.metadata.count??0,nextCursor:a.metadata?.next_cursor},servers:l}}toRawGalleryMcpServer(s){if(!s||typeof s!="object")return;let a=s;if(!a.name||!ue(a.name)||!a.description||!ue(a.description)||!a.version||!ue(a.version)||a.$schema&&a.$schema!==n.SCHEMA)return;let l=a._meta?.["io.modelcontextprotocol.registry/official"];function c(y){return{...y,isRequired:y.is_required,isSecret:y.is_secret}}function d(y){let x={};for(let[E,R]of Object.entries(y))x[E]=c(R);return x}function u(y){return y.type==="positional"?{...y,valueHint:y.value_hint,isRepeated:y.is_repeated,isRequired:y.is_required,isSecret:y.is_secret,variables:y.variables?d(y.variables):void 0}:{...y,isRepeated:y.is_repeated,isRequired:y.is_required,isSecret:y.is_secret,variables:y.variables?d(y.variables):void 0}}function p(y){return{...y,isRequired:y.is_required,isSecret:y.is_secret,variables:y.variables?d(y.variables):void 0}}function m(y){switch(y.type){case"stdio":return{type:"stdio"};case"streamable-http":return{type:"streamable-http",url:y.url,headers:y.headers?.map(p)};case"sse":return{type:"sse",url:y.url,headers:y.headers?.map(p)};default:return{type:"stdio"}}}function h(y){switch(y){case"npm":return"npm";case"docker":case"docker-hub":case"oci":return"oci";case"pypi":return"pypi";case"nuget":return"nuget";case"mcpb":return"mcpb";default:return"npm"}}let v=a._meta["io.modelcontextprotocol.registry/publisher-provided"]?.github;return{id:l.id,name:a.name,description:a.description,repository:a.repository?{url:a.repository.url,source:a.repository.source,id:a.repository.id}:void 0,readme:a.repository?.readme,version:a.version,createdAt:a.created_at,updatedAt:a.updated_at,packages:a.packages?.map(y=>({identifier:y.identifier??y.name,registryType:h(y.registry_type??y.registry_name),version:y.version,fileSha256:y.file_sha256,registryBaseUrl:y.registry_base_url,transport:y.transport?m(y.transport):{type:"stdio"},packageArguments:y.package_arguments?.map(u),runtimeHint:y.runtime_hint,runtimeArguments:y.runtime_arguments?.map(u),environmentVariables:y.environment_variables?.map(p)})),remotes:a.remotes?.map(y=>({type:(y.type??y.transport_type??y.transport)==="sse"?"sse":"streamable-http",url:y.url,headers:y.headers?.map(p)})),registryInfo:{isLatest:l.is_latest,publishedAt:l.published_at,updatedAt:l.updated_at},githubInfo:v?{name:v.name,nameWithOwner:v.name_with_owner,displayName:v.display_name,isInOrganization:v.is_in_organization,license:v.license,opengraphImageUrl:v.opengraph_image_url,ownerAvatarUrl:v.owner_avatar_url,primaryLanguage:v.primary_language,primaryLanguageColor:v.primary_language_color,pushedAt:v.pushed_at,stargazerCount:v.stargazer_count,topics:v.topics,usesCustomOpengraphImage:v.uses_custom_opengraph_image}:void 0}}}n.SERIALIZER=new e})(z1||={});var rm;(t=>{t.VERSION="v0.1";class r{toRawGalleryMcpServerResult(i){if(!i||typeof i!="object"||!Array.isArray(i.servers))return;let s=i,a=[];for(let l of s.servers){let c=this.toRawGalleryMcpServer(l);if(!c){if(a.length===0)return;continue}a.push(c)}return{metadata:s.metadata,servers:a}}toRawGalleryMcpServer(i){if(!i||typeof i!="object")return;let s=i;if(!s.server||!Re(s.server)||!s.server.name||!ue(s.server.name)||!s.server.description||!ue(s.server.description)||!s.server.version||!ue(s.server.version))return;let{"io.modelcontextprotocol.registry/official":a,...l}=s._meta,c=s.server._meta?.["io.modelcontextprotocol.registry/publisher-provided"]?.github;return{name:s.server.name,description:s.server.description,version:s.server.version,title:s.server.title,repository:s.server.repository?{url:s.server.repository.url,source:s.server.repository.source,id:s.server.repository.id}:void 0,readme:c?.readme,icons:s.server.icons,websiteUrl:s.server.websiteUrl,packages:s.server.packages,remotes:s.server.remotes,status:a?.status,registryInfo:a,githubInfo:c,apicInfo:l}}}t.SERIALIZER=new r})(rm||={});var oy;(t=>{t.VERSION="v0";class r{constructor(){this.galleryMcpServerDataSerializers=[];this.galleryMcpServerDataSerializers.push(rm.SERIALIZER),this.galleryMcpServerDataSerializers.push(z1.SERIALIZER)}toRawGalleryMcpServerResult(i){for(let s of this.galleryMcpServerDataSerializers){let a=s.toRawGalleryMcpServerResult(i);if(a)return a}}toRawGalleryMcpServer(i){for(let s of this.galleryMcpServerDataSerializers){let a=s.toRawGalleryMcpServer(i);if(a)return a}}}t.SERIALIZER=new r})(oy||={});var CC=50,DC={pageSize:CC},sy=class o{constructor(r=DC){this.state=r}get pageSize(){return this.state.pageSize}get searchText(){return this.state.searchText}get cursor(){return this.state.cursor}withPage(r,e=this.pageSize){return new o({...this.state,pageSize:e,cursor:r})}withSearchText(r){return new o({...this.state,searchText:r})}},sl=class extends T{constructor(e,t,n,i){super();this.requestService=e;this.fileService=t;this.logService=n;this.mcpGalleryManifestService=i;this.galleryMcpServerDataSerializers=new Map,this.galleryMcpServerDataSerializers.set(oy.VERSION,oy.SERIALIZER),this.galleryMcpServerDataSerializers.set(rm.VERSION,rm.SERIALIZER)}isEnabled(){return this.mcpGalleryManifestService.mcpGalleryManifestStatus==="available"}async query(e,t=Y.None){let n=await this.mcpGalleryManifestService.getMcpGalleryManifest();if(!n)return{firstPage:{items:[],hasMore:!1},getNextPage:async()=>({items:[],hasMore:!1})};let i=new sy;e?.text&&(i=i.withSearchText(e.text.trim()));let{servers:s,metadata:a}=await this.queryGalleryMcpServers(i,n,t),l=a.nextCursor;return{firstPage:{items:s,hasMore:!!a.nextCursor},getNextPage:async c=>{if(c.isCancellationRequested)throw new We;if(!l)return{items:[],hasMore:!1};let{servers:d,metadata:u}=await this.queryGalleryMcpServers(i.withPage(l).withSearchText(void 0),n,c);return l=u.nextCursor,{items:d,hasMore:!!u.nextCursor}}}}async getMcpServersFromGallery(e){let t=await this.mcpGalleryManifestService.getMcpGalleryManifest();if(!t)return[];let n=[];return await Promise.allSettled(e.map(async i=>{let s=await this.getMcpServerByName(i,t);s&&n.push(s)})),n}async getMcpServerByName({name:e,id:t},n){let i=this.getLatestServerVersionUrl(e,n);if(i){let l=await this.getMcpServer(i);if(l)return l}let s=this.getNamedServerUrl(e,n);if(s){let l=await this.getMcpServer(s);if(l)return l}let a=t?this.getServerIdUrl(t,n):void 0;if(a){let l=await this.getMcpServer(a);if(l)return l}}async getReadme(e,t){let n=e.readmeUrl;if(!n)return Promise.resolve(S(2162,null));let i=P.parse(n);if(i.scheme===re.file)try{return(await this.fileService.readFile(i)).value.toString()}catch(l){this.logService.error(`Failed to read file from ${i}: ${l}`)}if(i.authority!=="raw.githubusercontent.com")return new Qt(S(2163,null,n)).value;let s=await this.requestService.request({type:"GET",url:n},t),a=await cc(s);if(!a)throw new Error(`Failed to fetch README from ${n}`);return a}toGalleryMcpServer(e,t){let n="",i=e.title;if(e.githubInfo?.name)i||(i=e.githubInfo.name.split("-").map(c=>c.toLowerCase()==="mcp"?"MCP":c.toLowerCase()==="github"?"GitHub":Pl(c)).join(" ")),n=e.githubInfo.nameWithOwner.split("/")[0];else{let c=e.name.split("/");if(c.length>0){let d=c[0].split(".");d.length>0&&(n=d[d.length-1])}i||(i=c[c.length-1].split("-").map(d=>Pl(d)).join(" "))}e.githubInfo?.displayName&&(i=e.githubInfo.displayName);let s;if(e.githubInfo?.preferredImage)s={light:e.githubInfo.preferredImage,dark:e.githubInfo.preferredImage};else if(e.githubInfo?.ownerAvatarUrl)s={light:e.githubInfo.ownerAvatarUrl,dark:e.githubInfo.ownerAvatarUrl};else if(e.apicInfo?.["x-ms-icon"])s={light:e.apicInfo["x-ms-icon"],dark:e.apicInfo["x-ms-icon"]};else if(e.icons&&e.icons.length>0){let c=e.icons.find(u=>u.theme==="light")??e.icons[0],d=e.icons.find(u=>u.theme==="dark")??c;s={light:c.src,dark:d.src}}let a=t?this.getWebUrl(e.name,t):void 0,l=t?this.getPublisherUrl(n,t):void 0;return{id:e.id,name:e.name,displayName:i,galleryUrl:t?.url,webUrl:a,description:e.description,status:e.status??"active",version:e.version,isLatest:e.registryInfo?.isLatest??!0,publishDate:e.registryInfo?.publishedAt?Date.parse(e.registryInfo.publishedAt):void 0,lastUpdated:e.githubInfo?.pushedAt?Date.parse(e.githubInfo.pushedAt):e.registryInfo?.updatedAt?Date.parse(e.registryInfo.updatedAt):void 0,repositoryUrl:e.repository?.url,readme:e.readme,icon:s,publisher:n,publisherUrl:l,license:e.githubInfo?.license,starsCount:e.githubInfo?.stargazerCount,topics:e.githubInfo?.topics,configuration:{packages:e.packages,remotes:e.remotes}}}async queryGalleryMcpServers(e,t,n){let{servers:i,metadata:s}=await this.queryRawGalleryMcpServers(e,t,n);return{servers:i.map(a=>this.toGalleryMcpServer(a,t)),metadata:s}}async queryRawGalleryMcpServers(e,t,n){let i=this.getMcpGalleryUrl(t);if(!i)return{servers:[],metadata:{count:0}};let s=P.parse(i);if(s.scheme===re.file)try{let p=(await this.fileService.readFile(s)).value.toString();return JSON.parse(p)}catch(u){this.logService.error(`Failed to read file from ${s}: ${u}`)}let a=`${i}?limit=${e.pageSize}&version=latest`;if(e.cursor&&(a+=`&cursor=${e.cursor}`),e.searchText){let u=encodeURIComponent(e.searchText);a+=`&search=${u}`}let l=await this.requestService.request({type:"GET",url:a},n),c=await jr(l);if(!c)return{servers:[],metadata:{count:0}};let d=this.serializeMcpServersResult(c,t);if(!d)throw new Error(`Failed to serialize MCP servers result from ${i}`,c);return d}async getMcpServer(e,t){let n=await this.requestService.request({type:"GET",url:e},Y.None);if(n.res.statusCode&&n.res.statusCode>=400&&n.res.statusCode<500)return;let i=await jr(n);if(!i)return;t||(t=await this.mcpGalleryManifestService.getMcpGalleryManifest()),t=t&&e.startsWith(t.url)?t:null;let s=this.serializeMcpServer(i,t);if(!s)throw new Error(`Failed to serialize MCP server from ${e}`,i);return this.toGalleryMcpServer(s,t)}serializeMcpServer(e,t){return this.getSerializer(t)?.toRawGalleryMcpServer(e)}serializeMcpServersResult(e,t){return this.getSerializer(t)?.toRawGalleryMcpServerResult(e)}getSerializer(e){let t=e?.version??"v0";return this.galleryMcpServerDataSerializers.get(t)}getNamedServerUrl(e,t){let n=No(t,"McpServerNamedResourceUriTemplate");if(n)return Dr(n,{name:e})}getServerIdUrl(e,t){let n=No(t,"McpServerIdUriTemplate");if(n)return Dr(n,{id:e})}getLatestServerVersionUrl(e,t){let n=No(t,"McpServerLatestVersionUriTemplate");if(n)return Dr(n,{name:encodeURIComponent(e)})}getWebUrl(e,t){let n=No(t,"McpServerWebUriTemplate");if(n)return Dr(n,{name:e})}getPublisherUrl(e,t){let n=No(t,"PublisherUriTemplate");if(n)return Dr(n,{name:e})}getMcpGalleryUrl(e){return No(e,"McpServersQueryService")}};sl=b([g(0,Nr),g(1,W),g(2,V),g(3,tm)],sl);function Vo(o,r){return o?P.revive(r?r.transformIncoming(o):o):void 0}function Bi(o,r){r=r||js;let e=o.manifest;return{...Hs({...o,manifest:void 0},r),manifest:e}}function ay(o,r){return o?.mcpResource?Hs(o,r??js):o}function ly(o,r){return r?_s(o,e=>e instanceof P?r.transformOutgoingURI(e):void 0):o}function jc(o,r){return r?r.transformOutgoingURI(o):o}var im=class{constructor(r,e){this.service=r;this.getUriTransformer=e;this.onInstallMcpServer=k.buffer(r.onInstallMcpServer,!0),this.onDidInstallMcpServers=k.buffer(r.onDidInstallMcpServers,!0),this.onDidUpdateMcpServers=k.buffer(r.onDidUpdateMcpServers,!0),this.onUninstallMcpServer=k.buffer(r.onUninstallMcpServer,!0),this.onDidUninstallMcpServer=k.buffer(r.onDidUninstallMcpServer,!0)}listen(r,e){let t=this.getUriTransformer(r);switch(e){case"onInstallMcpServer":return k.map(this.onInstallMcpServer,n=>({...n,mcpResource:jc(n.mcpResource,t)}));case"onDidInstallMcpServers":return k.map(this.onDidInstallMcpServers,n=>n.map(i=>({...i,local:i.local?ly(i.local,t):i.local,mcpResource:jc(i.mcpResource,t)})));case"onDidUpdateMcpServers":return k.map(this.onDidUpdateMcpServers,n=>n.map(i=>({...i,local:i.local?ly(i.local,t):i.local,mcpResource:jc(i.mcpResource,t)})));case"onUninstallMcpServer":return k.map(this.onUninstallMcpServer,n=>({...n,mcpResource:jc(n.mcpResource,t)}));case"onDidUninstallMcpServer":return k.map(this.onDidUninstallMcpServer,n=>({...n,mcpResource:jc(n.mcpResource,t)}))}throw new Error("Invalid listen")}async call(r,e,t){let n=this.getUriTransformer(r),i=Array.isArray(t)?t:[];switch(e){case"getInstalled":return(await this.service.getInstalled(Vo(i[0],n))).map(a=>ly(a,n));case"install":return this.service.install(i[0],ay(i[1],n));case"installFromGallery":return this.service.installFromGallery(i[0],ay(i[1],n));case"uninstall":return this.service.uninstall(Bi(i[0],n),ay(i[1],n));case"updateMetadata":return this.service.updateMetadata(Bi(i[0],n),i[1],Vo(i[2],n))}throw new Error("Invalid call")}},nm=class extends Oo{constructor(e,t,n){super(t,n);this.channel=e;this._onInstallMcpServer=this._register(new w);this._onDidInstallMcpServers=this._register(new w);this._onUninstallMcpServer=this._register(new w);this._onDidUninstallMcpServer=this._register(new w);this._onDidUpdateMcpServers=this._register(new w);this._register(this.channel.listen("onInstallMcpServer")(i=>this._onInstallMcpServer.fire({...i,mcpResource:Vo(i.mcpResource,null)}))),this._register(this.channel.listen("onDidInstallMcpServers")(i=>this._onDidInstallMcpServers.fire(i.map(s=>({...s,local:s.local?Bi(s.local,null):s.local,mcpResource:Vo(s.mcpResource,null)}))))),this._register(this.channel.listen("onDidUpdateMcpServers")(i=>this._onDidUpdateMcpServers.fire(i.map(s=>({...s,local:s.local?Bi(s.local,null):s.local,mcpResource:Vo(s.mcpResource,null)}))))),this._register(this.channel.listen("onUninstallMcpServer")(i=>this._onUninstallMcpServer.fire({...i,mcpResource:Vo(i.mcpResource,null)}))),this._register(this.channel.listen("onDidUninstallMcpServer")(i=>this._onDidUninstallMcpServer.fire({...i,mcpResource:Vo(i.mcpResource,null)})))}get onInstallMcpServer(){return this._onInstallMcpServer.event}get onDidInstallMcpServers(){return this._onDidInstallMcpServers.event}get onUninstallMcpServer(){return this._onUninstallMcpServer.event}get onDidUninstallMcpServer(){return this._onDidUninstallMcpServer.event}get onDidUpdateMcpServers(){return this._onDidUpdateMcpServers.event}install(e,t){return Promise.resolve(this.channel.call("install",[e,t])).then(n=>Bi(n,null))}installFromGallery(e,t){return Promise.resolve(this.channel.call("installFromGallery",[e,t])).then(n=>Bi(n,null))}uninstall(e,t){return Promise.resolve(this.channel.call("uninstall",[e,t]))}getInstalled(e){return Promise.resolve(this.channel.call("getInstalled",[e])).then(t=>t.map(n=>Bi(n,null)))}updateMetadata(e,t,n){return Promise.resolve(this.channel.call("updateMetadata",[e,t,n])).then(i=>Bi(i,null))}};nm=b([g(1,Mo),g(2,V)],nm);var al=class extends T{constructor(e){super();this.configurationService=e;this._onDidChangeAllowedMcpServers=this._register(new w);this.onDidChangeAllowedMcpServers=this._onDidChangeAllowedMcpServers.event;this._register(this.configurationService.onDidChangeConfiguration(t=>{t.affectsConfiguration(Zf)&&this._onDidChangeAllowedMcpServers.fire()}))}isAllowed(e){if(this.configurationService.getValue(Zf)!=="none")return!0;let t=Zb("workbench.action.openSettings",{query:`@id:${Zf}`}).toString();return new Qt(S(2161,null,t))}};al=b([g(0,Q)],al);var om=class extends T{constructor(e){super();this._onDidChangeMcpGalleryManifest=this._register(new w);this.onDidChangeMcpGalleryManifest=this._onDidChangeMcpGalleryManifest.event;this._onDidChangeMcpGalleryManifestStatus=this._register(new w);this.onDidChangeMcpGalleryManifestStatus=this._onDidChangeMcpGalleryManifestStatus.event;this.barrier=new Kr;e.registerChannel("mcpGalleryManifest",{listen:()=>k.None,call:async(t,n,i)=>{if(n==="setMcpGalleryManifest"){let s=Array.isArray(i)?i[0]:null;return Promise.resolve(this.setMcpGalleryManifest(s))}throw new Error("Invalid call")}})}get mcpGalleryManifestStatus(){return this._mcpGalleryManifest?"available":"unavailable"}async getMcpGalleryManifest(){return await this.barrier.wait(),this._mcpGalleryManifest??null}setMcpGalleryManifest(e){this._mcpGalleryManifest=e,this._onDidChangeMcpGalleryManifest.fire(e),this._onDidChangeMcpGalleryManifestStatus.fire(this.mcpGalleryManifestStatus),this.barrier.open()}};var K1="meteredConnection";var sm=class extends T{constructor(e){super();this._onDidChangeIsConnectionMetered=this._register(new w);this.onDidChangeIsConnectionMetered=this._onDidChangeIsConnectionMetered.event;this._isConnectionMetered=!1;e.call("IsConnectionMetered").then(t=>{this._isConnectionMetered=t,t&&this._onDidChangeIsConnectionMetered.fire(t)}),this._register(e.listen("OnDidChangeIsConnectionMetered")(t=>{this._isConnectionMetered!==t&&(this._isConnectionMetered=t,this._onDidChangeIsConnectionMetered.fire(t))}))}get isConnectionMetered(){return this._isConnectionMetered}};var cy=L("playwrightService");var j1="browserViewGroup";var am=L("browserViewGroupRemoteService"),dy=class extends T{constructor(e,t){super();this.id=e;this.groupService=t;this._register(t.onDynamicDidDestroy(this.id)(()=>{this.dispose(!0)}))}get onDidAddView(){return this.groupService.onDynamicDidAddView(this.id)}get onDidRemoveView(){return this.groupService.onDynamicDidRemoveView(this.id)}get onDidDestroy(){return this.groupService.onDynamicDidDestroy(this.id)}async addView(e){return this.groupService.addViewToGroup(this.id,e)}async removeView(e){return this.groupService.removeViewFromGroup(this.id,e)}async getDebugWebSocketEndpoint(){return this.groupService.getDebugWebSocketEndpoint(this.id)}dispose(e=!1){e||this.groupService.destroyGroup(this.id),super.dispose()}},ll=class{constructor(r){this._groups=new Map;let e=r.getChannel(j1);this._groupService=Rt.toService(e)}async createGroup(){let r=await this._groupService.createGroup();return this._wrap(r)}_wrap(r){let e=new dy(r,this._groupService);return this._groups.set(r,e),k.once(e.onDidDestroy)(()=>{this._groups.delete(r)}),e}};ll=b([g(0,Rn)],ll);var lm=class{constructor(r){this.page=r;this._onDialogStateChanged=new w;this._logs=[];this._needsFullSnapshot=!1;r.on("console",e=>this._handleConsoleMessage(e)).on("pageerror",e=>this._handlePageError(e)).on("requestfailed",e=>this._handleRequestFailed(e)).on("dialog",e=>this._handleDialog(e)).on("download",e=>this._handleDownload(e)),this._initialized=this._initialize()}async _initialize(){let r=await this.page.consoleMessages().catch(()=>[]);for(let t of r)this._handleConsoleMessage(t);let e=await this.page.pageErrors().catch(()=>[]);for(let t of e)this._handlePageError(t)}_handleDialog(r){this._dialog=r,this.page.waitForFunction(()=>!0,void 0,{timeout:0}).then(()=>{this._dialog===r&&(this._dialog=void 0,this._onDialogStateChanged.fire())}),this._onDialogStateChanged.fire()}async replyToDialog(r,e){if(!this._dialog)throw new Error("No active modal dialog to respond to");let t=this._dialog;this._dialog=void 0,this._onDialogStateChanged.fire(),await this.safeRunAgainstPage(async()=>{r?await t.accept(e):await t.dismiss()})}_handleFileChooser(r){this._fileChooser=r}async replyToFileChooser(r){if(!this._fileChooser)throw new Error("No active file chooser dialog to respond to");let e=this._fileChooser;this._fileChooser=void 0,await this.safeRunAgainstPage(()=>e.setFiles(r))}async _handleDownload(r){this._logs.push({type:"download",time:Date.now(),description:`${r.suggestedFilename()}`})}_handleRequestFailed(r){let e=r.timing();this._logs.push({type:"requestFailed",time:e.responseEnd+e.startTime,description:`${r.method()} request to ${r.url()} failed: "${r.failure()?.errorText}"`})}_handleConsoleMessage(r){(r.type()==="error"||r.type()==="warning")&&this._logs.push({type:"console",time:r.timestamp(),description:`[${r.type()}] ${r.text()}`})}_handlePageError(r){this._logs.push({type:"pageError",time:Date.now(),description:r.stack??r.message})}async safeRunAgainstPage(r){if(this._dialog)throw new Error("Cannot perform action while a dialog is open");let e=!1,t,n=k.toPromise(this._onDialogStateChanged.event),i=Je(async s=>{let a=l=>this._handleFileChooser(l);this.page.on("filechooser",a);try{t=await this.runAndWaitForCompletion(l=>r(this.page,l),s),e=!0}finally{this.page.off("filechooser",a)}});return AS([n,i]).then(()=>{if(!e)throw new Error("Action was interrupted by a dialog");return t})}async getSummary(r=this._needsFullSnapshot){await this._initialized,r&&this._needsFullSnapshot&&(this._needsFullSnapshot=!1);let e=await this.safeRunAgainstPage(s=>s._snapshotForAI({track:"response"})).catch(()=>{this._needsFullSnapshot=!0}),t=await this.safeRunAgainstPage(s=>s.title()).catch(()=>""),n=this._logs;this._logs=[];let i=(r?e?.full:e?.incremental??e?.full)?.trim()??"";return[...t?[`Page Title: ${t}`]:[],`URL: ${this.page.url()}`,...this._dialog?[`Active ${this._dialog.type()} dialog: "${this._dialog.message()}"`]:[],...this._fileChooser?["Active file chooser dialog"]:[],...n.length>0?["Recent events:",...n.map(s=>`- [${new Date(s.time).toISOString()}] (${s.type}) ${s.description}`)]:[],...i?["Snapshot:",i]:[]].join(`
`)}async runAndWaitForCompletion(r,e=Y.None){let t=[],n=d=>t.push(d),i=()=>{this.page.off("request",n)};this.page.on("request",n);let s;try{s=await r(e)}finally{i()}if(t.some(d=>d.isNavigationRequest()))return await this.page.mainFrame().waitForLoadState("load",{timeout:1e4}).catch(()=>{}),s;let l=[];for(let d of t)["document","stylesheet","script","xhr","fetch"].includes(d.resourceType())?l.push(d.response().then(u=>u?.finished()).catch(()=>{})):l.push(d.response().catch(()=>{}));let c=new Promise(d=>setTimeout(d,5e3));return await Promise.race([Promise.all(l),c]),s}};var cl=class extends T{constructor(e,t){super();this.browserViewGroupRemoteService=e;this.logService=t;this._pages=this._register(new uy(t)),this.onDidChangeTrackedPages=this._pages.onDidChangeTrackedPages}async startTrackingPage(e){return this._pages.startTrackingPage(e)}async stopTrackingPage(e){return this._pages.stopTrackingPage(e)}async isPageTracked(e){return this._pages.isPageTracked(e)}async getTrackedPages(){return this._pages.getTrackedPages()}async initialize(){if(!this._browser)return this._initPromise?this._initPromise:(this._initPromise=(async()=>{try{this.logService.debug("[PlaywrightService] Creating browser view group");let e=await this.browserViewGroupRemoteService.createGroup();this.logService.debug("[PlaywrightService] Connecting to browser via CDP");let t=await import("playwright-core"),n=await e.getDebugWebSocketEndpoint(),i=await t.chromium.connectOverCDP(n);if(this.logService.debug("[PlaywrightService] Connected to browser"),this._initPromise===void 0)throw i.close().catch(()=>{}),e.dispose(),new Error("PlaywrightService was disposed during initialization");i.on("disconnected",()=>{this.logService.debug("[PlaywrightService] Browser disconnected"),this._browser===i&&(this._pages.reset(),this._browser=void 0,this._initPromise=void 0)}),await this._pages.initialize(i,e),this._browser=i}catch(e){throw this._initPromise=void 0,e}})(),this._initPromise)}async openPage(e){await this.initialize();let t=await this._pages.newPage(e),n=await this._pages.getSummary(t);return{pageId:t,summary:n}}async getSummary(e){return await this.initialize(),this._pages.getSummary(e,!0)}async invokeFunction(e,t,...n){this.logService.info(`[PlaywrightService] Invoking function on view ${e}`);try{await this.initialize();let i=await import("vm"),s=i.compileFunction(`return (${t})(page, ...args)`,["page","args"],{parsingContext:i.createContext()}),a;try{a=await this._pages.runAgainstPage(e,c=>s(c,n))}catch(c){a=c instanceof Error?c.message:String(c)}let l;try{l=await this._pages.getSummary(e)}catch(c){l=c instanceof Error?c.message:String(c)}return{result:a,summary:l}}catch(i){let s=i instanceof Error?i.message:String(i);throw this.logService.error("[PlaywrightService] Script execution failed:",s),i}}async captureScreenshot(e,t,n){return await this.initialize(),this._pages.runAgainstPage(e,async i=>{let s=t?await i.locator(t).screenshot({type:"jpeg",quality:80}):await i.screenshot({type:"jpeg",quality:80,fullPage:n??!1});return U.wrap(s)})}async replyToFileChooser(e,t){return await this.initialize(),{summary:await this._pages.replyToFileChooser(e,t)}}async replyToDialog(e,t,n){return await this.initialize(),{summary:await this._pages.replyToDialog(e,t,n)}}dispose(){this._browser&&(this._browser.close().catch(()=>{}),this._browser=void 0),this._initPromise=void 0,super.dispose()}};cl=b([g(0,am),g(1,V)],cl);var uy=class extends T{constructor(e){super();this.logService=e;this._trackedPages=new Set;this._onDidChangeTrackedPages=this._register(new w);this.onDidChangeTrackedPages=this._onDidChangeTrackedPages.event;this._viewIdToPage=new Map;this._pageToViewId=new WeakMap;this._tabs=new WeakMap;this._viewIdQueue=[];this._pageQueue=[];this._watchedContexts=new WeakSet;this._initStore=this._register(new se);this._openContext=void 0}isPageTracked(e){return this._trackedPages.has(e)}getTrackedPages(){return[...this._trackedPages]}async startTrackingPage(e){this._trackedPages.has(e)||(this._trackedPages.add(e),this._fireTrackedPagesChanged(),this._group&&await this._addPageToGroup(e))}async stopTrackingPage(e){this._trackedPages.has(e)&&(this._trackedPages.delete(e),this._fireTrackedPagesChanged(),this._group&&await this._removePageFromGroup(e))}async newPage(e){if(!this._browser)throw new Error("PlaywrightPageManager has not been initialized");this._openContext||(this._openContext=await this._browser.newContext(),this.onContextAdded(this._openContext));let t=await this._openContext.newPage(),n=await this.onPageAdded(t);return this._trackedPages.add(n),this._fireTrackedPagesChanged(),await t.goto(e,{waitUntil:"domcontentloaded",timeout:3e4}),n}async runAgainstPage(e,t){let n=await this.getPage(e),i=this._tabs.get(n);if(!i)throw new Error("Failed to execute function against page");return i.safeRunAgainstPage(async()=>t(n))}async getSummary(e,t=!1){let n=await this.getPage(e),i=this._tabs.get(n);if(!i)throw new Error("Failed to get page summary");return i.getSummary(t)}async replyToDialog(e,t,n){let i=await this.getPage(e),s=this._tabs.get(i);if(!s)throw new Error("Failed to reply to dialog");return await s.replyToDialog(t,n),s.getSummary()}async replyToFileChooser(e,t){let n=await this.getPage(e),i=this._tabs.get(n);if(!i)throw new Error("Failed to reply to file chooser");return await i.replyToFileChooser(t),i.getSummary()}async initialize(e,t){this._initStore.clear(),this._browser=e,this._group=t,this._initStore.add(t),this._initStore.add(t.onDidAddView(n=>this.onViewAdded(n.viewId))),this._initStore.add(t.onDidRemoveView(n=>this.onViewRemoved(n.viewId))),this.scanForNewContexts(),await Promise.all([...this._trackedPages].map(n=>this._addPageToGroup(n)))}reset(){this._initStore.clear(),this._browser=void 0,this._group=void 0,this.stopScanning(),this._viewIdToPage.clear();for(let{page:e}of this._viewIdQueue)e.error(new Error("PlaywrightPageManager reset"));for(let{viewId:e}of this._pageQueue)e.error(new Error("PlaywrightPageManager reset"));this._viewIdQueue=[],this._pageQueue=[]}async _addPageToGroup(e){if(!this._viewIdToPage.has(e)&&!this._viewIdQueue.some(t=>t.viewId===e)){this.onViewAdded(e);try{await this._group.addView(e)}catch(t){let n=t instanceof Error?t.message:String(t);this.logService.error("[PlaywrightPageManager] Failed to add view:",n),this.onViewRemoved(e)}}}async _removePageFromGroup(e){this.onViewRemoved(e);try{await this._group.removeView(e)}catch(t){let n=t instanceof Error?t.message:String(t);this.logService.error("[PlaywrightPageManager] Failed to remove view:",n)}}_fireTrackedPagesChanged(){this._onDidChangeTrackedPages.fire([...this._trackedPages])}async getPage(e){let t=this._viewIdToPage.get(e);if(t)return t;let n=this._viewIdQueue.find(i=>i.viewId===e);if(n)return n.page.p;throw new Error(`Page "${e}" not found`)}onViewAdded(e,t=1e4){let n=this._viewIdToPage.get(e);if(n)return Promise.resolve(n);let i=this._viewIdQueue.find(l=>l.viewId===e);if(i)return i.page.p;let s=new Ur,a=setTimeout(()=>s.error(new Error("Timed out waiting for page")),t);return s.p.finally(()=>{clearTimeout(a),this._viewIdQueue=this._viewIdQueue.filter(l=>l.viewId!==e),this._viewIdQueue.length===0&&this.stopScanning()}),this._viewIdQueue.push({viewId:e,page:s}),this.tryMatch(),this.ensureScanning(),s.p}onViewRemoved(e){this._viewIdQueue=this._viewIdQueue.filter(n=>n.viewId!==e);let t=this._viewIdToPage.get(e);t&&this._pageToViewId.delete(t),this._viewIdToPage.delete(e),this._trackedPages.delete(e),this._fireTrackedPagesChanged()}onPageAdded(e,t=1e4){let n=this._pageToViewId.get(e);if(n)return Promise.resolve(n);let i=this._pageQueue.find(l=>l.page===e);if(i)return i.viewId.p;this.onContextAdded(e.context()),e.once("close",()=>this.onPageRemoved(e)),e.setDefaultTimeout(1e4),this._tabs.set(e,new lm(e));let s=new Ur,a=setTimeout(()=>s.error(new Error("Timed out waiting for browser view")),t);return s.p.finally(()=>{clearTimeout(a),this._pageQueue=this._pageQueue.filter(l=>l.page!==e)}),this._pageQueue.push({page:e,viewId:s}),this.tryMatch(),s.p}onPageRemoved(e){this._pageQueue=this._pageQueue.filter(n=>n.page!==e);let t=this._pageToViewId.get(e);t&&(this._viewIdToPage.delete(t),this._trackedPages.delete(t),this._fireTrackedPagesChanged()),this._pageToViewId.delete(e)}onContextAdded(e){if(!this._watchedContexts.has(e)){this._watchedContexts.add(e),e.on("page",t=>this.onPageAdded(t)),e.on("close",()=>this.onContextRemoved(e));for(let t of e.pages())this.onPageAdded(t)}}onContextRemoved(e){this._watchedContexts.delete(e)}tryMatch(){for(;this._viewIdQueue.length>0&&this._pageQueue.length>0;){let e=this._viewIdQueue.shift(),t=this._pageQueue.shift();this._viewIdToPage.set(e.viewId,t.page),this._pageToViewId.set(t.page,e.viewId),e.page.complete(t.page),t.viewId.complete(e.viewId),this.logService.debug(`[PlaywrightPageManager] Matched view ${e.viewId} \u2192 page`)}this._viewIdQueue.length===0&&this.stopScanning()}scanForNewContexts(){if(this._browser)for(let e of this._browser.contexts())this.onContextAdded(e)}ensureScanning(){this._scanTimer===void 0&&(this._scanTimer=setInterval(()=>this.scanForNewContexts(),100))}stopScanning(){this._scanTimer!==void 0&&(clearInterval(this._scanTimer),this._scanTimer=void 0)}dispose(){this.stopScanning();for(let{page:e}of this._viewIdQueue)e.error(new Error("PlaywrightPageManager disposed"));for(let{viewId:e}of this._pageQueue)e.error(new Error("PlaywrightPageManager disposed"));this._viewIdQueue=[],this._pageQueue=[],super.dispose()}};var py=class extends T{constructor(e){super();this.configuration=e;this.server=this._register(new Fd(this));this.lifecycleService=void 0;this.onDidWindowConnectRaw=this._register(new w);this.registerListeners()}registerListeners(){let e=!1,t=()=>{e||(e=!0,this.lifecycleService?.fireOnWillShutdown(),this.dispose())};process.once("exit",t),tI(process.parentPort,Qf.exit,t)}async init(){let e=await this.initServices();kx(),e.invokeFunction(t=>{let n=t.get(V),i=t.get(de);n.trace("sharedProcess configuration",JSON.stringify(this.configuration)),this.initChannels(t),this.registerErrorHandler(n),this.reportClientOSInfo(i,n)}),this._register(zo(e.createInstance(us,this.configuration.codeCachePath),e.createInstance(ps),e.createInstance(Rs),e.createInstance(Es),e.createInstance(xs),e.createInstance(Ba),e.createInstance(Wa),e.createInstance(tl)))}async initServices(){let e=new Ei,t={_serviceBrand:void 0,...fr};e.set(ne,t);let n=new Ml(N=>N==="main"),i=new xu(this.server,n);e.set(Rn,i);let s=this.configuration.policiesData?new Af(this.configuration.policiesData,i.getChannel("policy")):new Ms;e.set(Du,s);let a=new Jf(this.configuration.args,t);e.set(nt,a);let l=new Fp(void 0,this.configuration.logLevel,a.logsHome,this.configuration.loggers.map(N=>({...N,resource:P.revive(N.resource)})),i.getChannel("logger"));e.set(wn,l);let c={id:"shared",name:S(176,null)},d=this._register(l.createLogger("sharedprocess",{name:S(176,null),group:c})),u=this._register(new qd(d.getLevel())),p=this._register(new Wc(d,[u]));e.set(V,p),this.lifecycleService=this._register(new $a(p)),e.set(Vf,this.lifecycleService);let m=this._register(new xi(p));e.set(W,m);let h=this._register(new Lp(p));m.registerProvider(re.file,h);let v=new _o(m);e.set(te,v);let y=this._register(new Ff(this.configuration.profiles.all,P.revive(this.configuration.profiles.home).with({scheme:a.userRoamingDataHome.scheme}),i.getChannel("userDataProfiles")));e.set(fe,y);let x=this._register(new Uf(re.file,this._register(new Lf(i.getChannel(o1),{pathCaseSensitive:Be})),re.vscodeUserData,y,v,p));m.registerProvider(re.vscodeUserData,x);let E=this._register(new Uu(y.defaultProfile.settingsResource,m,s,p));e.set(Q,E);let R=new $f(void 0,{defaultProfile:y.defaultProfile,currentProfile:y.defaultProfile},i,a);e.set(K,R),this._register(oe(()=>R.flush())),await Promise.all([E.initialize(),R.initialize()]);let F=this._register(l.createLogger("network-shared",{name:S(175,null),group:c})),H=new el(E,a,this._register(new Wc(F)));e.set(Nr,H),e.set(Rg,new Se(Ts,void 0,!1)),e.set(Cv,new Se(Mf,void 0,!1));let qe=new za(-1,i);e.set(mi,qe);let B=this._register(new sm(i.getChannel(K1)));e.set(Ka,B),e.set(Fu,new Se(Ns,void 0,!0));let C=this._register(new yf(qe)),A=new Ml(N=>C.getActiveClientId().then(O=>N===O));e.set(Sp,new Wf(this.server.getChannel("extensionRecommendationNotification",A)));let ae,J=[],ge=yb(t,E);if(Vu(t,a)){let N=new wi("",!1,l,a,t);if(J.push(N),!Wu(t,a)&&t.aiConfig?.ariaKey){let O=new Nf(H,ge,"monacoworkbench",null,t.aiConfig.ariaKey);this._register(oe(()=>O.flush())),J.push(O)}ae=new cn({appenders:J,commonProperties:ub(kC(),_C(),process.arch,t.commit,t.version,this.configuration.machineId,this.configuration.sqmId,this.configuration.devDeviceId,ge,t.date),sendErrorTelemetry:!0,piiPaths:Sb(a),meteredConnectionService:B},E,t)}else{ae=mb;let N=hb;J.push(N)}this.server.registerChannel("telemetryAppender",new Op(J)),e.set(de,ae);let Xe=new da(E,ae,l,a,t);e.set($g,Xe),e.set(Qr,new Se(qa,void 0,!0)),e.set(ra,new Se(Va,void 0,!0)),e.set(ip,new Se(Ks,void 0,!0)),e.set(sn,new Se(Vi,void 0,!0)),e.set(oa,new Se(ia,void 0,!0)),e.set(Mo,new Se(al,void 0,!0)),e.set(tm,new om(this.server)),e.set(Lo,new Se(sl,void 0,!0)),e.set(Wi,new Se(Ao,void 0,!0)),e.set(iy,new Se(em,void 0,!0)),e.set(bi,new nl(this.server,t,E)),e.set(At,new Se(qs,void 0,!0)),e.set(Pg,new Se(Ja,void 0,!1)),e.set(ic,new Se(ca,void 0,!1)),e.set(Ng,new Se(Os,void 0,!1)),e.set(So,new Se(ma,void 0,!0)),e.set(me,new Se(Sa,void 0,!0)),e.set(Ri,Rt.toService(this.server.getChannel("userDataSyncUtil",N=>N.ctx!=="main"))),e.set(gu,new Se(Ii,void 0,!1)),e.set(fa,new Se(pa,void 0,!0)),e.set(ua,new Se(Ot)),e.set(Pr,new Se(va,void 0,!0)),e.set(Ce,new Se(ya,void 0,!0)),e.set(bo,new Se(Xr,void 0,!0)),e.set(Qe,new Se(ha,void 0,!1)),e.set(Oe,new Se(Ia,void 0,!0)),e.set(yo,new Se(ka,void 0,!1)),e.set(Di,new Se(Ua,void 0,!0)),e.set(Pc,new Se(Nt,void 0,!0)),e.set(La,new Se(If,void 0,!1));let Ze=new Df;return e.set(Oa,Ze),Ze.register(0,h1),e.set(xf,new Se(Na)),e.set(Rv,new Se(Fi)),e.set(Lv,new Se(Ga)),e.set(ny,new Se(Yf)),e.set(am,new Se(ll)),e.set(cy,new Se(cl)),new Ap(e)}initChannels(e){let t=new cp(e.get(rr),()=>null);this.server.registerChannel("extensions",t);let n=new im(e.get(iy),()=>null);this.server.registerChannel("mcpManagement",n);let i=Rt.fromService(e.get(ic),this._store);this.server.registerChannel("languagePacks",i);let s=Rt.fromService(e.get(Ng),this._store);this.server.registerChannel("diagnostics",s);let a=new dp(e.get(Pg));this.server.registerChannel("extensionTipsService",a);let l=Rt.fromService(e.get(Rg),this._store);this.server.registerChannel("checksum",l);let c=Rt.fromService(e.get(Cv),this._store);this.server.registerChannel("v8InspectProfiling",c);let d=Rt.fromService(e.get(bo),this._store);this.server.registerChannel("userDataSyncMachines",d);let u=Rt.fromService(e.get($g),this._store);this.server.registerChannel("customEndpointTelemetry",u);let p=new Gp(e.get(So));this.server.registerChannel("userDataSyncAccount",p);let m=new qp(e.get(Pr));this.server.registerChannel("userDataSyncStoreManagement",m);let h=new vf(e.get(yo),e.get(fe),e.get(V));this.server.registerChannel("userDataSync",h);let v=this._register(e.get(bt).createInstance(Ha));this.server.registerChannel("userDataAutoSync",Rt.fromService(v,this._store)),this.server.registerChannel("IUserDataSyncResourceProviderService",Rt.fromService(e.get(Pc),this._store));let y=Rt.fromService(e.get(Rv),this._store);this.server.registerChannel(i1,y);let x=Rt.fromService(e.get(Lv),this._store);this.server.registerChannel("remoteTunnel",x);let E=Rt.fromService(e.get(ny),this._store);this.server.registerChannel("sharedWebContentExtractor",E);let R=Rt.fromService(e.get(cy),this._store);this.server.registerChannel("playwright",R)}registerErrorHandler(e){process.on("uncaughtException",t=>Me(t)),process.on("unhandledRejection",t=>Me(t)),Sy(t=>{let n=_t(t,!0);n&&e.error(`[uncaught exception in sharedProcess]: ${n}`)})}async reportClientOSInfo(e,t){if(Be){let[n,i]=await Promise.all([_1(t.error.bind(t)),U1(t.error.bind(t))]),s=k1(),a=L1(i,this.configuration.args["ozone-platform"]);n&&e.publicLog2("clientPlatformInfo",{platformId:n.id,platformVersionId:n.version_id,platformIdLike:n.id_like,desktopEnvironment:s,displayProtocol:i,codeDisplayProtocol:a})}}handledClientConnection(e){if(e.data!==D1.response)return!1;let t=e.ports.at(0);return t?(this.onDidWindowConnectRaw.fire(t),!0):!1}};async function UC(o){try{let r=new py(o);process.parentPort.postMessage(Qf.ipcReady),await r.init(),process.parentPort.postMessage(Qf.initDone)}catch(r){process.parentPort.postMessage({error:r.toString()})}}var LC=setTimeout(()=>{process.parentPort.postMessage({warning:"[SharedProcess] did not receive configuration within 30s..."})},3e4);process.parentPort.once("message",o=>{clearTimeout(LC),UC(o.data)});export{UC as main};
//# sourceMappingURL=https://cdn.windsurf.com/sourcemaps/0d4bf12ed4a7597cb8ae9016fe8474468aad98a2/core/vs/code/electron-utility/sharedProcess/sharedProcessMain.js.map
