/*!--------------------------------------------------------
 * Copyright (C) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------*/
(function() {
var __m = ["require","exports","vs/base/common/lifecycle","vs/base/common/observableInternal/debugName","vs/base/common/observableInternal/base","vs/base/common/equals","vs/base/common/observableInternal/logging","vs/base/common/observableInternal/autorun","vs/base/common/observableInternal/derived","vs/base/common/errors","vs/editor/common/tokens/lineTokens","vs/editor/common/encodedTokenAttributes","vs/base/common/arrays","vs/base/common/observable","vs/base/common/buffer","vs/editor/common/core/eolCounter","vs/editor/common/core/lineRange","vs/editor/common/tokens/contiguousMultilineTokensBuilder","vs/amdX","vs/base/common/platform","vs/editor/common/languages/nullTokenize","vs/base/common/amd","vs/base/common/assert","vs/base/common/observableInternal/lazyObservableValue","vs/base/common/observableInternal/api","vs/base/common/observableInternal/promise","vs/base/common/observableInternal/utils","vs/base/common/event","vs/base/common/stream","vs/editor/common/model/fixedArray","vs/editor/common/tokens/contiguousTokensEditing","vs/editor/common/tokens/contiguousMultilineTokens","vs/base/common/uri","vs/editor/common/languages","vs/editor/common/model/textModelTokens","vs/base/common/async","vs/base/common/stopwatch","vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateWorkerHost","vs/workbench/services/textMate/browser/tokenizationSupport/textMateTokenizationSupport","vs/workbench/services/textMate/browser/tokenizationSupport/tokenizationSupportWithLineLimit","vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateWorkerTokenizer","vs/workbench/services/textMate/common/TMScopeRegistry","vs/workbench/services/textMate/common/TMGrammarFactory","vs/base/common/cancellation","vs/base/common/lazy","vs/base/common/charCode","vs/editor/common/core/position","vs/base/common/network","vs/base/common/types","vs/editor/common/core/offsetRange","vs/editor/common/model/mirrorTextModel","vs/base/common/resources","vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateTokenizationWorker.worker"];
var __M = function(deps) {
  var result = [];
  for (var i = 0, len = deps.length; i < len; i++) {
    result[i] = __m[deps[i]];
  }
  return result;
};
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[21/*vs/base/common/amd*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$X = exports.LoaderEventType = exports.$W = exports.$V = void 0;
    // ESM-comment-begin
    exports.$V = false;
    exports.$W = true;
    // ESM-comment-end
    // ESM-uncomment-begin
    // export const isESM = true;
    // export const canASAR = false; // TODO@esm: ASAR disabled in ESM
    // ESM-uncomment-end
    var LoaderEventType;
    (function (LoaderEventType) {
        LoaderEventType[LoaderEventType["LoaderAvailable"] = 1] = "LoaderAvailable";
        LoaderEventType[LoaderEventType["BeginLoadingScript"] = 10] = "BeginLoadingScript";
        LoaderEventType[LoaderEventType["EndLoadingScriptOK"] = 11] = "EndLoadingScriptOK";
        LoaderEventType[LoaderEventType["EndLoadingScriptError"] = 12] = "EndLoadingScriptError";
        LoaderEventType[LoaderEventType["BeginInvokeFactory"] = 21] = "BeginInvokeFactory";
        LoaderEventType[LoaderEventType["EndInvokeFactory"] = 22] = "EndInvokeFactory";
        LoaderEventType[LoaderEventType["NodeBeginEvaluatingScript"] = 31] = "NodeBeginEvaluatingScript";
        LoaderEventType[LoaderEventType["NodeEndEvaluatingScript"] = 32] = "NodeEndEvaluatingScript";
        LoaderEventType[LoaderEventType["NodeBeginNativeRequire"] = 33] = "NodeBeginNativeRequire";
        LoaderEventType[LoaderEventType["NodeEndNativeRequire"] = 34] = "NodeEndNativeRequire";
        LoaderEventType[LoaderEventType["CachedDataFound"] = 60] = "CachedDataFound";
        LoaderEventType[LoaderEventType["CachedDataMissed"] = 61] = "CachedDataMissed";
        LoaderEventType[LoaderEventType["CachedDataRejected"] = 62] = "CachedDataRejected";
        LoaderEventType[LoaderEventType["CachedDataCreated"] = 63] = "CachedDataCreated";
    })(LoaderEventType || (exports.LoaderEventType = LoaderEventType = {}));
    class $X {
        static get() {
            const amdLoadScript = new Map();
            const amdInvokeFactory = new Map();
            const nodeRequire = new Map();
            const nodeEval = new Map();
            function mark(map, stat) {
                if (map.has(stat.detail)) {
                    // console.warn('BAD events, DOUBLE start', stat);
                    // map.delete(stat.detail);
                    return;
                }
                map.set(stat.detail, -stat.timestamp);
            }
            function diff(map, stat) {
                const duration = map.get(stat.detail);
                if (!duration) {
                    // console.warn('BAD events, end WITHOUT start', stat);
                    // map.delete(stat.detail);
                    return;
                }
                if (duration >= 0) {
                    // console.warn('BAD events, DOUBLE end', stat);
                    // map.delete(stat.detail);
                    return;
                }
                map.set(stat.detail, duration + stat.timestamp);
            }
            let stats = [];
            if (typeof require === 'function' && typeof require.getStats === 'function') {
                stats = require.getStats().slice(0).sort((a, b) => a.timestamp - b.timestamp);
            }
            for (const stat of stats) {
                switch (stat.type) {
                    case LoaderEventType.BeginLoadingScript:
                        mark(amdLoadScript, stat);
                        break;
                    case LoaderEventType.EndLoadingScriptOK:
                    case LoaderEventType.EndLoadingScriptError:
                        diff(amdLoadScript, stat);
                        break;
                    case LoaderEventType.BeginInvokeFactory:
                        mark(amdInvokeFactory, stat);
                        break;
                    case LoaderEventType.EndInvokeFactory:
                        diff(amdInvokeFactory, stat);
                        break;
                    case LoaderEventType.NodeBeginNativeRequire:
                        mark(nodeRequire, stat);
                        break;
                    case LoaderEventType.NodeEndNativeRequire:
                        diff(nodeRequire, stat);
                        break;
                    case LoaderEventType.NodeBeginEvaluatingScript:
                        mark(nodeEval, stat);
                        break;
                    case LoaderEventType.NodeEndEvaluatingScript:
                        diff(nodeEval, stat);
                        break;
                }
            }
            let nodeRequireTotal = 0;
            nodeRequire.forEach(value => nodeRequireTotal += value);
            function to2dArray(map) {
                const res = [];
                map.forEach((value, index) => res.push([index, value]));
                return res;
            }
            return {
                amdLoad: to2dArray(amdLoadScript),
                amdInvoke: to2dArray(amdInvokeFactory),
                nodeRequire: to2dArray(nodeRequire),
                nodeEval: to2dArray(nodeEval),
                nodeRequireTotal
            };
        }
        static toMarkdownTable(header, rows) {
            let result = '';
            const lengths = [];
            header.forEach((cell, ci) => {
                lengths[ci] = cell.length;
            });
            rows.forEach(row => {
                row.forEach((cell, ci) => {
                    if (typeof cell === 'undefined') {
                        cell = row[ci] = '-';
                    }
                    const len = cell.toString().length;
                    lengths[ci] = Math.max(len, lengths[ci]);
                });
            });
            // header
            header.forEach((cell, ci) => { result += `| ${cell + ' '.repeat(lengths[ci] - cell.toString().length)} `; });
            result += '|\n';
            header.forEach((_cell, ci) => { result += `| ${'-'.repeat(lengths[ci])} `; });
            result += '|\n';
            // cells
            rows.forEach(row => {
                row.forEach((cell, ci) => {
                    if (typeof cell !== 'undefined') {
                        result += `| ${cell + ' '.repeat(lengths[ci] - cell.toString().length)} `;
                    }
                });
                result += '|\n';
            });
            return result;
        }
    }
    exports.$X = $X;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __createBinding = (this && this.__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];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (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;
};
define(__m[5/*vs/base/common/equals*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/arrays*/]), function (require, exports, arrays) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$$c = void 0;
    exports.$_c = $_c;
    exports.$ad = $ad;
    exports.$bd = $bd;
    exports.$cd = $cd;
    exports.$dd = $dd;
    exports.$ed = $ed;
    arrays = __importStar(arrays);
    /**
     * Compares two items for equality using strict equality.
    */
    const $$c = (a, b) => a === b;
    exports.$$c = $$c;
    /**
     * Checks if the items of two arrays are equal.
     * By default, strict equality is used to compare elements, but a custom equality comparer can be provided.
     */
    function $_c(itemEquals = exports.$$c) {
        return (a, b) => arrays.$yb(a, b, itemEquals);
    }
    /**
     * Two items are considered equal, if their stringified representations are equal.
    */
    function $ad() {
        return (a, b) => JSON.stringify(a) === JSON.stringify(b);
    }
    /**
     * Uses `item.equals(other)` to determine equality.
     */
    function $bd() {
        return (a, b) => a.equals(b);
    }
    function $cd(equalsOrV1, v2, equals) {
        if (equals !== undefined) {
            const v1 = equalsOrV1;
            if (v1 === undefined || v1 === null || v2 === undefined || v2 === null) {
                return v2 === v1;
            }
            return equals(v1, v2);
        }
        else {
            const equals = equalsOrV1;
            return (v1, v2) => {
                if (v1 === undefined || v1 === null || v2 === undefined || v2 === null) {
                    return v2 === v1;
                }
                return equals(v1, v2);
            };
        }
    }
    /**
     * Drills into arrays (items ordered) and objects (keys unordered) and uses strict equality on everything else.
    */
    function $dd(a, b) {
        if (a === b) {
            return true;
        }
        if (Array.isArray(a) && Array.isArray(b)) {
            if (a.length !== b.length) {
                return false;
            }
            for (let i = 0; i < a.length; i++) {
                if (!$dd(a[i], b[i])) {
                    return false;
                }
            }
            return true;
        }
        if (a && typeof a === 'object' && b && typeof b === 'object') {
            if (Object.getPrototypeOf(a) === Object.prototype && Object.getPrototypeOf(b) === Object.prototype) {
                const aObj = a;
                const bObj = b;
                const keysA = Object.keys(aObj);
                const keysB = Object.keys(bObj);
                const keysBSet = new Set(keysB);
                if (keysA.length !== keysB.length) {
                    return false;
                }
                for (const key of keysA) {
                    if (!keysBSet.has(key)) {
                        return false;
                    }
                    if (!$dd(aObj[key], bObj[key])) {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }
    /**
     * `getStructuralKey(a) === getStructuralKey(b) <=> structuralEquals(a, b)`
     * (assuming that a and b are not cyclic structures and nothing extends globalThis Array).
    */
    function $ed(t) {
        return JSON.stringify(toNormalizedJsonStructure(t));
    }
    let objectId = 0;
    const objIds = new WeakMap();
    function toNormalizedJsonStructure(t) {
        if (Array.isArray(t)) {
            return t.map(toNormalizedJsonStructure);
        }
        if (t && typeof t === 'object') {
            if (Object.getPrototypeOf(t) === Object.prototype) {
                const tObj = t;
                const res = Object.create(null);
                for (const key of Object.keys(tObj).sort()) {
                    res[key] = toNormalizedJsonStructure(tObj[key]);
                }
                return res;
            }
            else {
                let objId = objIds.get(t);
                if (objId === undefined) {
                    objId = objectId++;
                    objIds.set(t, objId);
                }
                // Random string to prevent collisions
                return objId + '----2b76a038c20c4bcc';
            }
        }
        return t;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[3/*vs/base/common/observableInternal/debugName*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$fd = void 0;
    exports.$gd = $gd;
    exports.$hd = $hd;
    class $fd {
        constructor(owner, debugNameSource, referenceFn) {
            this.owner = owner;
            this.debugNameSource = debugNameSource;
            this.referenceFn = referenceFn;
        }
        getDebugName(target) {
            return $gd(target, this);
        }
    }
    exports.$fd = $fd;
    const countPerName = new Map();
    const cachedDebugName = new WeakMap();
    function $gd(target, data) {
        const cached = cachedDebugName.get(target);
        if (cached) {
            return cached;
        }
        const dbgName = computeDebugName(target, data);
        if (dbgName) {
            let count = countPerName.get(dbgName) ?? 0;
            count++;
            countPerName.set(dbgName, count);
            const result = count === 1 ? dbgName : `${dbgName}#${count}`;
            cachedDebugName.set(target, result);
            return result;
        }
        return undefined;
    }
    function computeDebugName(self, data) {
        const cached = cachedDebugName.get(self);
        if (cached) {
            return cached;
        }
        const ownerStr = data.owner ? formatOwner(data.owner) + `.` : '';
        let result;
        const debugNameSource = data.debugNameSource;
        if (debugNameSource !== undefined) {
            if (typeof debugNameSource === 'function') {
                result = debugNameSource();
                if (result !== undefined) {
                    return ownerStr + result;
                }
            }
            else {
                return ownerStr + debugNameSource;
            }
        }
        const referenceFn = data.referenceFn;
        if (referenceFn !== undefined) {
            result = $hd(referenceFn);
            if (result !== undefined) {
                return ownerStr + result;
            }
        }
        if (data.owner !== undefined) {
            const key = findKey(data.owner, self);
            if (key !== undefined) {
                return ownerStr + key;
            }
        }
        return undefined;
    }
    function findKey(obj, value) {
        for (const key in obj) {
            if (obj[key] === value) {
                return key;
            }
        }
        return undefined;
    }
    const countPerClassName = new Map();
    const ownerId = new WeakMap();
    function formatOwner(owner) {
        const id = ownerId.get(owner);
        if (id) {
            return id;
        }
        const className = getClassName(owner);
        let count = countPerClassName.get(className) ?? 0;
        count++;
        countPerClassName.set(className, count);
        const result = count === 1 ? className : `${className}#${count}`;
        ownerId.set(owner, result);
        return result;
    }
    function getClassName(obj) {
        const ctor = obj.constructor;
        if (ctor) {
            return ctor.name;
        }
        return 'Object';
    }
    function $hd(fn) {
        const fnSrc = fn.toString();
        // Pattern: /** @description ... */
        const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//;
        const match = regexp.exec(fnSrc);
        const result = match ? match[1] : undefined;
        return result?.trim();
    }
});

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

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[7/*vs/base/common/observableInternal/autorun*/], __M([0/*require*/,1/*exports*/,22/*vs/base/common/assert*/,2/*vs/base/common/lifecycle*/,3/*vs/base/common/observableInternal/debugName*/,6/*vs/base/common/observableInternal/logging*/]), function (require, exports, assert_1, lifecycle_1, debugName_1, logging_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$ud = void 0;
    exports.$od = $od;
    exports.$pd = $pd;
    exports.$qd = $qd;
    exports.$rd = $rd;
    exports.$sd = $sd;
    exports.$td = $td;
    /**
     * Runs immediately and whenever a transaction ends and an observed observable changed.
     * {@link fn} should start with a JS Doc using `@description` to name the autorun.
     */
    function $od(fn) {
        return new $ud(new debugName_1.$fd(undefined, undefined, fn), fn, undefined, undefined);
    }
    /**
     * Runs immediately and whenever a transaction ends and an observed observable changed.
     * {@link fn} should start with a JS Doc using `@description` to name the autorun.
     */
    function $pd(options, fn) {
        return new $ud(new debugName_1.$fd(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, undefined, undefined);
    }
    /**
     * Runs immediately and whenever a transaction ends and an observed observable changed.
     * {@link fn} should start with a JS Doc using `@description` to name the autorun.
     *
     * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes.
     * Use `handleChange` to add a reported change to the change summary.
     * The run function is given the last change summary.
     * The change summary is discarded after the run function was called.
     *
     * @see $od
     */
    function $qd(options, fn) {
        return new $ud(new debugName_1.$fd(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, options.createEmptyChangeSummary, options.handleChange);
    }
    /**
     * @see $qd (but with a disposable store that is cleared before the next run or on dispose)
     */
    function $rd(options, fn) {
        const store = new lifecycle_1.$Yc();
        const disposable = $qd({
            owner: options.owner,
            debugName: options.debugName,
            debugReferenceFn: options.debugReferenceFn ?? fn,
            createEmptyChangeSummary: options.createEmptyChangeSummary,
            handleChange: options.handleChange,
        }, (reader, changeSummary) => {
            store.clear();
            fn(reader, changeSummary, store);
        });
        return (0, lifecycle_1.$Xc)(() => {
            disposable.dispose();
            store.dispose();
        });
    }
    /**
     * @see $od (but with a disposable store that is cleared before the next run or on dispose)
     */
    function $sd(fn) {
        const store = new lifecycle_1.$Yc();
        const disposable = $pd({
            owner: undefined,
            debugName: undefined,
            debugReferenceFn: fn,
        }, reader => {
            store.clear();
            fn(reader, store);
        });
        return (0, lifecycle_1.$Xc)(() => {
            disposable.dispose();
            store.dispose();
        });
    }
    function $td(observable, handler) {
        let _lastValue;
        return $pd({ debugReferenceFn: handler }, (reader) => {
            const newValue = observable.read(reader);
            const lastValue = _lastValue;
            _lastValue = newValue;
            handler({ lastValue, newValue });
        });
    }
    var AutorunState;
    (function (AutorunState) {
        /**
         * A dependency could have changed.
         * We need to explicitly ask them if at least one dependency changed.
         */
        AutorunState[AutorunState["dependenciesMightHaveChanged"] = 1] = "dependenciesMightHaveChanged";
        /**
         * A dependency changed and we need to recompute.
         */
        AutorunState[AutorunState["stale"] = 2] = "stale";
        AutorunState[AutorunState["upToDate"] = 3] = "upToDate";
    })(AutorunState || (AutorunState = {}));
    class $ud {
        get debugName() {
            return this._debugNameData.getDebugName(this) ?? '(anonymous)';
        }
        constructor(_debugNameData, _runFn, h, i) {
            this._debugNameData = _debugNameData;
            this._runFn = _runFn;
            this.h = h;
            this.i = i;
            this.a = AutorunState.stale;
            this.b = 0;
            this.c = false;
            this.e = new Set();
            this.f = new Set();
            this.g = this.h?.();
            (0, logging_1.$Qd)()?.handleAutorunCreated(this);
            this.j();
            (0, lifecycle_1.$Qc)(this);
        }
        dispose() {
            this.c = true;
            for (const o of this.e) {
                o.removeObserver(this);
            }
            this.e.clear();
            (0, lifecycle_1.$Rc)(this);
        }
        j() {
            if (this.a === AutorunState.upToDate) {
                return;
            }
            const emptySet = this.f;
            this.f = this.e;
            this.e = emptySet;
            this.a = AutorunState.upToDate;
            const isDisposed = this.c;
            try {
                if (!isDisposed) {
                    (0, logging_1.$Qd)()?.handleAutorunTriggered(this);
                    const changeSummary = this.g;
                    this.g = this.h?.();
                    this._runFn(this, changeSummary);
                }
            }
            finally {
                if (!isDisposed) {
                    (0, logging_1.$Qd)()?.handleAutorunFinished(this);
                }
                // We don't want our observed observables to think that they are (not even temporarily) not being observed.
                // Thus, we only unsubscribe from observables that are definitely not read anymore.
                for (const o of this.f) {
                    o.removeObserver(this);
                }
                this.f.clear();
            }
        }
        toString() {
            return `Autorun<${this.debugName}>`;
        }
        // IObserver implementation
        beginUpdate() {
            if (this.a === AutorunState.upToDate) {
                this.a = AutorunState.dependenciesMightHaveChanged;
            }
            this.b++;
        }
        endUpdate() {
            if (this.b === 1) {
                do {
                    if (this.a === AutorunState.dependenciesMightHaveChanged) {
                        this.a = AutorunState.upToDate;
                        for (const d of this.e) {
                            d.reportChanges();
                            if (this.a === AutorunState.stale) {
                                // The other dependencies will refresh on demand
                                break;
                            }
                        }
                    }
                    this.j();
                } while (this.a !== AutorunState.upToDate);
            }
            this.b--;
            (0, assert_1.$md)(() => this.b >= 0);
        }
        handlePossibleChange(observable) {
            if (this.a === AutorunState.upToDate && this.e.has(observable) && !this.f.has(observable)) {
                this.a = AutorunState.dependenciesMightHaveChanged;
            }
        }
        handleChange(observable, change) {
            if (this.e.has(observable) && !this.f.has(observable)) {
                const shouldReact = this.i ? this.i({
                    changedObservable: observable,
                    change,
                    didChange: (o) => o === observable,
                }, this.g) : true;
                if (shouldReact) {
                    this.a = AutorunState.stale;
                }
            }
        }
        // IReader implementation
        readObservable(observable) {
            // In case the run action disposes the autorun
            if (this.c) {
                return observable.get();
            }
            observable.addObserver(this);
            const value = observable.get();
            this.e.add(observable);
            this.f.delete(observable);
            return value;
        }
    }
    exports.$ud = $ud;
    (function ($od) {
        $od.Observer = $ud;
    })($od || (exports.$od = $od = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[4/*vs/base/common/observableInternal/base*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/equals*/,3/*vs/base/common/observableInternal/debugName*/,6/*vs/base/common/observableInternal/logging*/]), function (require, exports, equals_1, debugName_1, logging_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$be = exports.$_d = exports.$0d = exports.$5d = exports.$4d = void 0;
    exports.$1d = $1d;
    exports.$2d = $2d;
    exports.$3d = $3d;
    exports.$6d = $6d;
    exports.$7d = $7d;
    exports.$8d = $8d;
    exports.$9d = $9d;
    exports.$$d = $$d;
    exports.$ae = $ae;
    let _recomputeInitiallyAndOnChange;
    function $1d(recomputeInitiallyAndOnChange) {
        _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange;
    }
    let _keepObserved;
    function $2d(keepObserved) {
        _keepObserved = keepObserved;
    }
    let _derived;
    /**
     * @internal
     * This is to allow splitting files.
    */
    function $3d(derived) {
        _derived = derived;
    }
    class $4d {
        get TChange() { return null; }
        reportChanges() {
            this.get();
        }
        /** @sealed */
        read(reader) {
            if (reader) {
                return reader.readObservable(this);
            }
            else {
                return this.get();
            }
        }
        map(fnOrOwner, fnOrUndefined) {
            const owner = fnOrUndefined === undefined ? undefined : fnOrOwner;
            const fn = fnOrUndefined === undefined ? fnOrOwner : fnOrUndefined;
            return _derived({
                owner,
                debugName: () => {
                    const name = (0, debugName_1.$hd)(fn);
                    if (name !== undefined) {
                        return name;
                    }
                    // regexp to match `x => x.y` or `x => x?.y` where x and y can be arbitrary identifiers (uses backref):
                    const regexp = /^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/;
                    const match = regexp.exec(fn.toString());
                    if (match) {
                        return `${this.debugName}.${match[2]}`;
                    }
                    if (!owner) {
                        return `${this.debugName} (mapped)`;
                    }
                    return undefined;
                },
                debugReferenceFn: fn,
            }, (reader) => fn(this.read(reader), reader));
        }
        /**
         * @sealed
         * Converts an observable of an observable value into a direct observable of the value.
        */
        flatten() {
            return _derived({
                owner: undefined,
                debugName: () => `${this.debugName} (flattened)`,
            }, (reader) => this.read(reader).read(reader));
        }
        recomputeInitiallyAndOnChange(store, handleValue) {
            store.add(_recomputeInitiallyAndOnChange(this, handleValue));
            return this;
        }
        /**
         * Ensures that this observable is observed. This keeps the cache alive.
         * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get).
         * Use `recomputeInitiallyAndOnChange` for eager evaluation.
         */
        keepObserved(store) {
            store.add(_keepObserved(this));
            return this;
        }
        get a() {
            return this.get();
        }
    }
    exports.$4d = $4d;
    class $5d extends $4d {
        constructor() {
            super(...arguments);
            this.b = new Set();
        }
        addObserver(observer) {
            const len = this.b.size;
            this.b.add(observer);
            if (len === 0) {
                this.c();
            }
        }
        removeObserver(observer) {
            const deleted = this.b.delete(observer);
            if (deleted && this.b.size === 0) {
                this.f();
            }
        }
        c() { }
        f() { }
    }
    exports.$5d = $5d;
    /**
     * Starts a transaction in which many observables can be changed at once.
     * {@link fn} should start with a JS Doc using `@description` to give the transaction a debug name.
     * Reaction run on demand or when the transaction ends.
     */
    function $6d(fn, getDebugName) {
        const tx = new $0d(fn, getDebugName);
        try {
            fn(tx);
        }
        finally {
            tx.finish();
        }
    }
    let _globalTransaction = undefined;
    function $7d(fn) {
        if (_globalTransaction) {
            fn(_globalTransaction);
        }
        else {
            const tx = new $0d(fn, undefined);
            _globalTransaction = tx;
            try {
                fn(tx);
            }
            finally {
                tx.finish(); // During finish, more actions might be added to the transaction.
                // Which is why we only clear the global transaction after finish.
                _globalTransaction = undefined;
            }
        }
    }
    async function $8d(fn, getDebugName) {
        const tx = new $0d(fn, getDebugName);
        try {
            await fn(tx);
        }
        finally {
            tx.finish();
        }
    }
    /**
     * Allows to chain transactions.
     */
    function $9d(tx, fn, getDebugName) {
        if (!tx) {
            $6d(fn, getDebugName);
        }
        else {
            fn(tx);
        }
    }
    class $0d {
        constructor(_fn, b) {
            this._fn = _fn;
            this.b = b;
            this.a = [];
            (0, logging_1.$Qd)()?.handleBeginTransaction(this);
        }
        getDebugName() {
            if (this.b) {
                return this.b();
            }
            return (0, debugName_1.$hd)(this._fn);
        }
        updateObserver(observer, observable) {
            // When this gets called while finish is active, they will still get considered
            this.a.push({ observer, observable });
            observer.beginUpdate(observable);
        }
        finish() {
            const updatingObservers = this.a;
            for (let i = 0; i < updatingObservers.length; i++) {
                const { observer, observable } = updatingObservers[i];
                observer.endUpdate(observable);
            }
            // Prevent anyone from updating observers from now on.
            this.a = null;
            (0, logging_1.$Qd)()?.handleEndTransaction();
        }
    }
    exports.$0d = $0d;
    function $$d(nameOrOwner, initialValue) {
        let debugNameData;
        if (typeof nameOrOwner === 'string') {
            debugNameData = new debugName_1.$fd(undefined, nameOrOwner, undefined);
        }
        else {
            debugNameData = new debugName_1.$fd(nameOrOwner, undefined, undefined);
        }
        return new $_d(debugNameData, initialValue, equals_1.$$c);
    }
    class $_d extends $5d {
        get debugName() {
            return this.e.getDebugName(this) ?? 'ObservableValue';
        }
        constructor(e, initialValue, g) {
            super();
            this.e = e;
            this.g = g;
            this.d = initialValue;
        }
        get() {
            return this.d;
        }
        set(value, tx, change) {
            if (change === undefined && this.g(this.d, value)) {
                return;
            }
            let _tx;
            if (!tx) {
                tx = _tx = new $0d(() => { }, () => `Setting ${this.debugName}`);
            }
            try {
                const oldValue = this.d;
                this.h(value);
                (0, logging_1.$Qd)()?.handleObservableChanged(this, { oldValue, newValue: value, change, didChange: true, hadValue: true });
                for (const observer of this.b) {
                    tx.updateObserver(observer, this);
                    observer.handleChange(this, change);
                }
            }
            finally {
                if (_tx) {
                    _tx.finish();
                }
            }
        }
        toString() {
            return `${this.debugName}: ${this.d}`;
        }
        h(newValue) {
            this.d = newValue;
        }
    }
    exports.$_d = $_d;
    /**
     * A disposable observable. When disposed, its value is also disposed.
     * When a new value is set, the previous value is disposed.
     */
    function $ae(nameOrOwner, initialValue) {
        let debugNameData;
        if (typeof nameOrOwner === 'string') {
            debugNameData = new debugName_1.$fd(undefined, nameOrOwner, undefined);
        }
        else {
            debugNameData = new debugName_1.$fd(nameOrOwner, undefined, undefined);
        }
        return new $be(debugNameData, initialValue, equals_1.$$c);
    }
    class $be extends $_d {
        h(newValue) {
            if (this.d === newValue) {
                return;
            }
            if (this.d) {
                this.d.dispose();
            }
            this.d = newValue;
        }
        dispose() {
            this.d?.dispose();
        }
    }
    exports.$be = $be;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[8/*vs/base/common/observableInternal/derived*/], __M([0/*require*/,1/*exports*/,22/*vs/base/common/assert*/,5/*vs/base/common/equals*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/observableInternal/base*/,3/*vs/base/common/observableInternal/debugName*/,6/*vs/base/common/observableInternal/logging*/]), function (require, exports, assert_1, equals_1, lifecycle_1, base_1, debugName_1, logging_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$Zd = exports.$Yd = void 0;
    exports.$Sd = $Sd;
    exports.$Td = $Td;
    exports.$Ud = $Ud;
    exports.$Vd = $Vd;
    exports.$Wd = $Wd;
    exports.$Xd = $Xd;
    function $Sd(computeFnOrOwner, computeFn) {
        if (computeFn !== undefined) {
            return new $Yd(new debugName_1.$fd(computeFnOrOwner, undefined, computeFn), computeFn, undefined, undefined, undefined, equals_1.$$c);
        }
        return new $Yd(new debugName_1.$fd(undefined, undefined, computeFnOrOwner), computeFnOrOwner, undefined, undefined, undefined, equals_1.$$c);
    }
    function $Td(owner, computeFn, setter) {
        return new $Zd(new debugName_1.$fd(owner, undefined, computeFn), computeFn, undefined, undefined, undefined, equals_1.$$c, setter);
    }
    function $Ud(options, computeFn) {
        return new $Yd(new debugName_1.$fd(options.owner, options.debugName, options.debugReferenceFn), computeFn, undefined, undefined, options.onLastObserverRemoved, options.equalsFn ?? equals_1.$$c);
    }
    (0, base_1.$3d)($Ud);
    /**
     * Represents an observable that is derived from other observables.
     * The value is only recomputed when absolutely needed.
     *
     * {@link computeFn} should start with a JS Doc using `@description` to name the derived.
     *
     * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes.
     * Use `handleChange` to add a reported change to the change summary.
     * The compute function is given the last change summary.
     * The change summary is discarded after the compute function was called.
     *
     * @see $Sd
     */
    function $Vd(options, computeFn) {
        return new $Yd(new debugName_1.$fd(options.owner, options.debugName, undefined), computeFn, options.createEmptyChangeSummary, options.handleChange, undefined, options.equalityComparer ?? equals_1.$$c);
    }
    function $Wd(computeFnOrOwner, computeFnOrUndefined) {
        let computeFn;
        let owner;
        if (computeFnOrUndefined === undefined) {
            computeFn = computeFnOrOwner;
            owner = undefined;
        }
        else {
            owner = computeFnOrOwner;
            computeFn = computeFnOrUndefined;
        }
        const store = new lifecycle_1.$Yc();
        return new $Yd(new debugName_1.$fd(owner, undefined, computeFn), r => {
            store.clear();
            return computeFn(r, store);
        }, undefined, undefined, () => store.dispose(), equals_1.$$c);
    }
    function $Xd(computeFnOrOwner, computeFnOrUndefined) {
        let computeFn;
        let owner;
        if (computeFnOrUndefined === undefined) {
            computeFn = computeFnOrOwner;
            owner = undefined;
        }
        else {
            owner = computeFnOrOwner;
            computeFn = computeFnOrUndefined;
        }
        let store = undefined;
        return new $Yd(new debugName_1.$fd(owner, undefined, computeFn), r => {
            if (!store) {
                store = new lifecycle_1.$Yc();
            }
            else {
                store.clear();
            }
            const result = computeFn(r);
            if (result) {
                store.add(result);
            }
            return result;
        }, undefined, undefined, () => {
            if (store) {
                store.dispose();
                store = undefined;
            }
        }, equals_1.$$c);
    }
    var DerivedState;
    (function (DerivedState) {
        /** Initial state, no previous value, recomputation needed */
        DerivedState[DerivedState["initial"] = 0] = "initial";
        /**
         * A dependency could have changed.
         * We need to explicitly ask them if at least one dependency changed.
         */
        DerivedState[DerivedState["dependenciesMightHaveChanged"] = 1] = "dependenciesMightHaveChanged";
        /**
         * A dependency changed and we need to recompute.
         * After recomputation, we need to check the previous value to see if we changed as well.
         */
        DerivedState[DerivedState["stale"] = 2] = "stale";
        /**
         * No change reported, our cached value is up to date.
         */
        DerivedState[DerivedState["upToDate"] = 3] = "upToDate";
    })(DerivedState || (DerivedState = {}));
    class $Yd extends base_1.$5d {
        get debugName() {
            return this._debugNameData.getDebugName(this) ?? '(anonymous)';
        }
        constructor(_debugNameData, _computeFn, m, n, p = undefined, q) {
            super();
            this._debugNameData = _debugNameData;
            this._computeFn = _computeFn;
            this.m = m;
            this.n = n;
            this.p = p;
            this.q = q;
            this.e = DerivedState.initial;
            this.g = undefined;
            this.h = 0;
            this.j = new Set();
            this.k = new Set();
            this.l = undefined;
            this.l = this.m?.();
            (0, logging_1.$Qd)()?.handleDerivedCreated(this);
        }
        f() {
            /**
             * We are not tracking changes anymore, thus we have to assume
             * that our cache is invalid.
             */
            this.e = DerivedState.initial;
            this.g = undefined;
            for (const d of this.j) {
                d.removeObserver(this);
            }
            this.j.clear();
            this.p?.();
        }
        get() {
            if (this.b.size === 0) {
                // Without observers, we don't know when to clean up stuff.
                // Thus, we don't cache anything to prevent memory leaks.
                const result = this._computeFn(this, this.m?.());
                // Clear new dependencies
                this.f();
                return result;
            }
            else {
                do {
                    // We might not get a notification for a dependency that changed while it is updating,
                    // thus we also have to ask all our depedencies if they changed in this case.
                    if (this.e === DerivedState.dependenciesMightHaveChanged) {
                        for (const d of this.j) {
                            /** might call {@link handleChange} indirectly, which could make us stale */
                            d.reportChanges();
                            if (this.e === DerivedState.stale) {
                                // The other dependencies will refresh on demand, so early break
                                break;
                            }
                        }
                    }
                    // We called report changes of all dependencies.
                    // If we are still not stale, we can assume to be up to date again.
                    if (this.e === DerivedState.dependenciesMightHaveChanged) {
                        this.e = DerivedState.upToDate;
                    }
                    this.t();
                    // In case recomputation changed one of our dependencies, we need to recompute again.
                } while (this.e !== DerivedState.upToDate);
                return this.g;
            }
        }
        t() {
            if (this.e === DerivedState.upToDate) {
                return;
            }
            const emptySet = this.k;
            this.k = this.j;
            this.j = emptySet;
            const hadValue = this.e !== DerivedState.initial;
            const oldValue = this.g;
            this.e = DerivedState.upToDate;
            const changeSummary = this.l;
            this.l = this.m?.();
            try {
                /** might call {@link handleChange} indirectly, which could invalidate us */
                this.g = this._computeFn(this, changeSummary);
            }
            finally {
                // We don't want our observed observables to think that they are (not even temporarily) not being observed.
                // Thus, we only unsubscribe from observables that are definitely not read anymore.
                for (const o of this.k) {
                    o.removeObserver(this);
                }
                this.k.clear();
            }
            const didChange = hadValue && !(this.q(oldValue, this.g));
            (0, logging_1.$Qd)()?.handleDerivedRecomputed(this, {
                oldValue,
                newValue: this.g,
                change: undefined,
                didChange,
                hadValue,
            });
            if (didChange) {
                for (const r of this.b) {
                    r.handleChange(this, undefined);
                }
            }
        }
        toString() {
            return `LazyDerived<${this.debugName}>`;
        }
        // IObserver Implementation
        beginUpdate(_observable) {
            this.h++;
            const propagateBeginUpdate = this.h === 1;
            if (this.e === DerivedState.upToDate) {
                this.e = DerivedState.dependenciesMightHaveChanged;
                // If we propagate begin update, that will already signal a possible change.
                if (!propagateBeginUpdate) {
                    for (const r of this.b) {
                        r.handlePossibleChange(this);
                    }
                }
            }
            if (propagateBeginUpdate) {
                for (const r of this.b) {
                    r.beginUpdate(this); // This signals a possible change
                }
            }
        }
        endUpdate(_observable) {
            this.h--;
            if (this.h === 0) {
                // End update could change the observer list.
                const observers = [...this.b];
                for (const r of observers) {
                    r.endUpdate(this);
                }
            }
            (0, assert_1.$md)(() => this.h >= 0);
        }
        handlePossibleChange(observable) {
            // In all other states, observers already know that we might have changed.
            if (this.e === DerivedState.upToDate && this.j.has(observable) && !this.k.has(observable)) {
                this.e = DerivedState.dependenciesMightHaveChanged;
                for (const r of this.b) {
                    r.handlePossibleChange(this);
                }
            }
        }
        handleChange(observable, change) {
            if (this.j.has(observable) && !this.k.has(observable)) {
                const shouldReact = this.n ? this.n({
                    changedObservable: observable,
                    change,
                    didChange: (o) => o === observable,
                }, this.l) : true;
                const wasUpToDate = this.e === DerivedState.upToDate;
                if (shouldReact && (this.e === DerivedState.dependenciesMightHaveChanged || wasUpToDate)) {
                    this.e = DerivedState.stale;
                    if (wasUpToDate) {
                        for (const r of this.b) {
                            r.handlePossibleChange(this);
                        }
                    }
                }
            }
        }
        // IReader Implementation
        readObservable(observable) {
            // Subscribe before getting the value to enable caching
            observable.addObserver(this);
            /** This might call {@link handleChange} indirectly, which could invalidate us */
            const value = observable.get();
            // Which is why we only add the observable to the dependencies now.
            this.j.add(observable);
            this.k.delete(observable);
            return value;
        }
        addObserver(observer) {
            const shouldCallBeginUpdate = !this.b.has(observer) && this.h > 0;
            super.addObserver(observer);
            if (shouldCallBeginUpdate) {
                observer.beginUpdate(this);
            }
        }
        removeObserver(observer) {
            const shouldCallEndUpdate = this.b.has(observer) && this.h > 0;
            super.removeObserver(observer);
            if (shouldCallEndUpdate) {
                // Calling end update after removing the observer makes sure endUpdate cannot be called twice here.
                observer.endUpdate(this);
            }
        }
    }
    exports.$Yd = $Yd;
    class $Zd extends $Yd {
        constructor(debugNameData, computeFn, createChangeSummary, handleChange, handleLastObserverRemoved = undefined, equalityComparator, set) {
            super(debugNameData, computeFn, createChangeSummary, handleChange, handleLastObserverRemoved, equalityComparator);
            this.set = set;
        }
    }
    exports.$Zd = $Zd;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[23/*vs/base/common/observableInternal/lazyObservableValue*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/observableInternal/base*/]), function (require, exports, base_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$ie = void 0;
    /**
     * Holds off updating observers until the value is actually read.
    */
    class $ie extends base_1.$5d {
        get debugName() {
            return this.h.getDebugName(this) ?? 'LazyObservableValue';
        }
        constructor(h, initialValue, j) {
            super();
            this.h = h;
            this.j = j;
            this.e = true;
            this.g = [];
            this.l = 0;
            this.d = initialValue;
        }
        get() {
            this.k();
            return this.d;
        }
        k() {
            if (this.e) {
                return;
            }
            this.e = true;
            if (this.g.length > 0) {
                for (const observer of this.b) {
                    for (const change of this.g) {
                        observer.handleChange(this, change);
                    }
                }
                this.g.length = 0;
            }
            else {
                for (const observer of this.b) {
                    observer.handleChange(this, undefined);
                }
            }
        }
        m() {
            this.l++;
            if (this.l === 1) {
                for (const observer of this.b) {
                    observer.beginUpdate(this);
                }
            }
        }
        n() {
            this.l--;
            if (this.l === 0) {
                this.k();
                // End update could change the observer list.
                const observers = [...this.b];
                for (const r of observers) {
                    r.endUpdate(this);
                }
            }
        }
        addObserver(observer) {
            const shouldCallBeginUpdate = !this.b.has(observer) && this.l > 0;
            super.addObserver(observer);
            if (shouldCallBeginUpdate) {
                observer.beginUpdate(this);
            }
        }
        removeObserver(observer) {
            const shouldCallEndUpdate = this.b.has(observer) && this.l > 0;
            super.removeObserver(observer);
            if (shouldCallEndUpdate) {
                // Calling end update after removing the observer makes sure endUpdate cannot be called twice here.
                observer.endUpdate(this);
            }
        }
        set(value, tx, change) {
            if (change === undefined && this.j(this.d, value)) {
                return;
            }
            let _tx;
            if (!tx) {
                tx = _tx = new base_1.$0d(() => { }, () => `Setting ${this.debugName}`);
            }
            try {
                this.e = false;
                this.o(value);
                if (change !== undefined) {
                    this.g.push(change);
                }
                tx.updateObserver({
                    beginUpdate: () => this.m(),
                    endUpdate: () => this.n(),
                    handleChange: (observable, change) => { },
                    handlePossibleChange: (observable) => { },
                }, this);
                if (this.l > 1) {
                    // We already started begin/end update, so we need to manually call handlePossibleChange
                    for (const observer of this.b) {
                        observer.handlePossibleChange(this);
                    }
                }
            }
            finally {
                if (_tx) {
                    _tx.finish();
                }
            }
        }
        toString() {
            return `${this.debugName}: ${this.d}`;
        }
        o(newValue) {
            this.d = newValue;
        }
    }
    exports.$ie = $ie;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[24/*vs/base/common/observableInternal/api*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/equals*/,4/*vs/base/common/observableInternal/base*/,3/*vs/base/common/observableInternal/debugName*/,23/*vs/base/common/observableInternal/lazyObservableValue*/]), function (require, exports, equals_1, base_1, debugName_1, lazyObservableValue_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$je = $je;
    function $je(options, initialValue) {
        if (options.lazy) {
            return new lazyObservableValue_1.$ie(new debugName_1.$fd(options.owner, options.debugName, undefined), initialValue, options.equalsFn ?? equals_1.$$c);
        }
        return new base_1.$_d(new debugName_1.$fd(options.owner, options.debugName, undefined), initialValue, options.equalsFn ?? equals_1.$$c);
    }
});

define(__m[25/*vs/base/common/observableInternal/promise*/], __M([0/*require*/,1/*exports*/,7/*vs/base/common/observableInternal/autorun*/,4/*vs/base/common/observableInternal/base*/,8/*vs/base/common/observableInternal/derived*/,43/*vs/base/common/cancellation*/,3/*vs/base/common/observableInternal/debugName*/,5/*vs/base/common/equals*/,9/*vs/base/common/errors*/]), function (require, exports, autorun_1, base_1, derived_1, cancellation_1, debugName_1, equals_1, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$fe = exports.$ee = exports.$de = exports.$ce = void 0;
    exports.$ge = $ge;
    exports.$he = $he;
    class $ce {
        /**
         * The cached value.
         * Does not force a computation of the value.
         */
        get cachedValue() { return this.a; }
        constructor(b) {
            this.b = b;
            this.a = (0, base_1.$$d)(this, undefined);
        }
        /**
         * Returns the cached value.
         * Computes the value if the value has not been cached yet.
         */
        getValue() {
            let v = this.a.get();
            if (!v) {
                v = this.b();
                this.a.set(v, undefined);
            }
            return v;
        }
    }
    exports.$ce = $ce;
    /**
     * A promise whose state is observable.
     */
    class $de {
        static fromFn(fn) {
            return new $de(fn());
        }
        constructor(promise) {
            this.a = (0, base_1.$$d)(this, undefined);
            /**
             * The current state of the promise.
             * Is `undefined` if the promise didn't resolve yet.
             */
            this.promiseResult = this.a;
            this.promise = promise.then(value => {
                (0, base_1.$6d)(tx => {
                    /** @description onPromiseResolved */
                    this.a.set(new $ee(value, undefined), tx);
                });
                return value;
            }, error => {
                (0, base_1.$6d)(tx => {
                    /** @description onPromiseRejected */
                    this.a.set(new $ee(undefined, error), tx);
                });
                throw error;
            });
        }
    }
    exports.$de = $de;
    class $ee {
        constructor(
        /**
         * The value of the resolved promise.
         * Undefined if the promise rejected.
         */
        data, 
        /**
         * The error in case of a rejected promise.
         * Undefined if the promise resolved.
         */
        error) {
            this.data = data;
            this.error = error;
        }
        /**
         * Returns the value if the promise resolved, otherwise throws the error.
         */
        getDataOrThrow() {
            if (this.error) {
                throw this.error;
            }
            return this.data;
        }
    }
    exports.$ee = $ee;
    /**
     * A lazy promise whose state is observable.
     */
    class $fe {
        constructor(b) {
            this.b = b;
            this.a = new $ce(() => new $de(this.b()));
            /**
             * Does not enforce evaluation of the promise compute function.
             * Is undefined if the promise has not been computed yet.
             */
            this.cachedPromiseResult = (0, derived_1.$Sd)(this, reader => this.a.cachedValue.read(reader)?.promiseResult.read(reader));
        }
        getPromise() {
            return this.a.getValue().promise;
        }
    }
    exports.$fe = $fe;
    function $ge(observable, predicate, isError, cancellationToken) {
        if (!predicate) {
            predicate = state => state !== null && state !== undefined;
        }
        return new Promise((resolve, reject) => {
            let isImmediateRun = true;
            let shouldDispose = false;
            const stateObs = observable.map(state => {
                /** @description waitForState.state */
                return {
                    isFinished: predicate(state),
                    error: isError ? isError(state) : false,
                    state
                };
            });
            const d = (0, autorun_1.$od)(reader => {
                /** @description waitForState */
                const { isFinished, error, state } = stateObs.read(reader);
                if (isFinished || error) {
                    if (isImmediateRun) {
                        // The variable `d` is not initialized yet
                        shouldDispose = true;
                    }
                    else {
                        d.dispose();
                    }
                    if (error) {
                        reject(error === true ? state : error);
                    }
                    else {
                        resolve(state);
                    }
                }
            });
            if (cancellationToken) {
                const dc = cancellationToken.onCancellationRequested(() => {
                    d.dispose();
                    dc.dispose();
                    reject(new errors_1.$9());
                });
                if (cancellationToken.isCancellationRequested) {
                    d.dispose();
                    dc.dispose();
                    reject(new errors_1.$9());
                    return;
                }
            }
            isImmediateRun = false;
            if (shouldDispose) {
                d.dispose();
            }
        });
    }
    function $he(computeFnOrOwner, computeFnOrUndefined) {
        let computeFn;
        let owner;
        if (computeFnOrUndefined === undefined) {
            computeFn = computeFnOrOwner;
            owner = undefined;
        }
        else {
            owner = computeFnOrOwner;
            computeFn = computeFnOrUndefined;
        }
        let cancellationTokenSource = undefined;
        return new derived_1.$Yd(new debugName_1.$fd(owner, undefined, computeFn), r => {
            if (cancellationTokenSource) {
                cancellationTokenSource.dispose(true);
            }
            cancellationTokenSource = new cancellation_1.$Be();
            return computeFn(r, cancellationTokenSource.token);
        }, undefined, undefined, () => cancellationTokenSource?.dispose(), equals_1.$$c);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[26/*vs/base/common/observableInternal/utils*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,7/*vs/base/common/observableInternal/autorun*/,4/*vs/base/common/observableInternal/base*/,3/*vs/base/common/observableInternal/debugName*/,8/*vs/base/common/observableInternal/derived*/,6/*vs/base/common/observableInternal/logging*/,9/*vs/base/common/errors*/,5/*vs/base/common/equals*/]), function (require, exports, event_1, lifecycle_1, autorun_1, base_1, debugName_1, derived_1, logging_1, errors_1, equals_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$Ld = exports.$Hd = exports.$zd = void 0;
    exports.$vd = $vd;
    exports.$wd = $wd;
    exports.$xd = $xd;
    exports.$yd = $yd;
    exports.$Ad = $Ad;
    exports.$Bd = $Bd;
    exports.$Cd = $Cd;
    exports.$Dd = $Dd;
    exports.$Ed = $Ed;
    exports.$Fd = $Fd;
    exports.$Gd = $Gd;
    exports.$Id = $Id;
    exports.$Jd = $Jd;
    exports.$Kd = $Kd;
    exports.$Md = $Md;
    exports.$Nd = $Nd;
    exports.$Od = $Od;
    /**
     * Represents an efficient observable whose value never changes.
     */
    function $vd(value) {
        return new ConstObservable(value);
    }
    class ConstObservable extends base_1.$4d {
        constructor(b) {
            super();
            this.b = b;
        }
        get debugName() {
            return this.toString();
        }
        get() {
            return this.b;
        }
        addObserver(observer) {
            // NO OP
        }
        removeObserver(observer) {
            // NO OP
        }
        toString() {
            return `Const: ${this.b}`;
        }
    }
    function $wd(promise) {
        const observable = (0, base_1.$$d)('promiseValue', {});
        promise.then((value) => {
            observable.set({ value }, undefined);
        });
        return observable;
    }
    function $xd(...args) {
        let owner;
        let event;
        let getValue;
        if (args.length === 3) {
            [owner, event, getValue] = args;
        }
        else {
            [event, getValue] = args;
        }
        return new $zd(new debugName_1.$fd(owner, undefined, getValue), event, getValue, () => $zd.globalTransaction, equals_1.$$c);
    }
    function $yd(options, event, getValue) {
        return new $zd(new debugName_1.$fd(options.owner, options.debugName, options.debugReferenceFn ?? getValue), event, getValue, () => $zd.globalTransaction, options.equalsFn ?? equals_1.$$c);
    }
    class $zd extends base_1.$5d {
        constructor(j, k, _getValue, l, n) {
            super();
            this.j = j;
            this.k = k;
            this._getValue = _getValue;
            this.l = l;
            this.n = n;
            this.g = false;
            this.r = (args) => {
                const newValue = this._getValue(args);
                const oldValue = this.e;
                const didChange = !this.g || !(this.n(oldValue, newValue));
                let didRunTransaction = false;
                if (didChange) {
                    this.e = newValue;
                    if (this.g) {
                        didRunTransaction = true;
                        (0, base_1.$9d)(this.l(), (tx) => {
                            (0, logging_1.$Qd)()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: undefined, didChange, hadValue: this.g });
                            for (const o of this.b) {
                                tx.updateObserver(o, this);
                                o.handleChange(this, undefined);
                            }
                        }, () => {
                            const name = this.p();
                            return 'Event fired' + (name ? `: ${name}` : '');
                        });
                    }
                    this.g = true;
                }
                if (!didRunTransaction) {
                    (0, logging_1.$Qd)()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: undefined, didChange, hadValue: this.g });
                }
            };
        }
        p() {
            return this.j.getDebugName(this);
        }
        get debugName() {
            const name = this.p();
            return 'From Event' + (name ? `: ${name}` : '');
        }
        c() {
            this.h = this.k(this.r);
        }
        f() {
            this.h.dispose();
            this.h = undefined;
            this.g = false;
            this.e = undefined;
        }
        get() {
            if (this.h) {
                if (!this.g) {
                    this.r(undefined);
                }
                return this.e;
            }
            else {
                // no cache, as there are no subscribers to keep it updated
                const value = this._getValue(undefined);
                return value;
            }
        }
    }
    exports.$zd = $zd;
    (function ($xd) {
        $xd.Observer = $zd;
        function batchEventsGlobally(tx, fn) {
            let didSet = false;
            if ($zd.globalTransaction === undefined) {
                $zd.globalTransaction = tx;
                didSet = true;
            }
            try {
                fn();
            }
            finally {
                if (didSet) {
                    $zd.globalTransaction = undefined;
                }
            }
        }
        $xd.batchEventsGlobally = batchEventsGlobally;
    })($xd || (exports.$xd = $xd = {}));
    function $Ad(debugName, event) {
        return new FromEventObservableSignal(debugName, event);
    }
    class FromEventObservableSignal extends base_1.$5d {
        constructor(debugName, g) {
            super();
            this.debugName = debugName;
            this.g = g;
            this.j = () => {
                (0, base_1.$6d)((tx) => {
                    for (const o of this.b) {
                        tx.updateObserver(o, this);
                        o.handleChange(this, undefined);
                    }
                }, () => this.debugName);
            };
        }
        c() {
            this.e = this.g(this.j);
        }
        f() {
            this.e.dispose();
            this.e = undefined;
        }
        get() {
            // NO OP
        }
    }
    function $Bd(debugNameOrOwner) {
        if (typeof debugNameOrOwner === 'string') {
            return new ObservableSignal(debugNameOrOwner);
        }
        else {
            return new ObservableSignal(undefined, debugNameOrOwner);
        }
    }
    class ObservableSignal extends base_1.$5d {
        get debugName() {
            return new debugName_1.$fd(this.g, this.e, undefined).getDebugName(this) ?? 'Observable Signal';
        }
        toString() {
            return this.debugName;
        }
        constructor(e, g) {
            super();
            this.e = e;
            this.g = g;
        }
        trigger(tx, change) {
            if (!tx) {
                (0, base_1.$6d)(tx => {
                    this.trigger(tx, change);
                }, () => `Trigger signal ${this.debugName}`);
                return;
            }
            for (const o of this.b) {
                tx.updateObserver(o, this);
                o.handleChange(this, change);
            }
        }
        get() {
            // NO OP
        }
    }
    /**
     * @deprecated Use `debouncedObservable2` instead.
     */
    function $Cd(observable, debounceMs, disposableStore) {
        const debouncedObservable = (0, base_1.$$d)('debounced', undefined);
        let timeout = undefined;
        disposableStore.add((0, autorun_1.$od)(reader => {
            /** @description debounce */
            const value = observable.read(reader);
            if (timeout) {
                clearTimeout(timeout);
            }
            timeout = setTimeout(() => {
                (0, base_1.$6d)(tx => {
                    debouncedObservable.set(value, tx);
                });
            }, debounceMs);
        }));
        return debouncedObservable;
    }
    /**
     * Creates an observable that debounces the input observable.
     */
    function $Dd(observable, debounceMs) {
        let hasValue = false;
        let lastValue;
        let timeout = undefined;
        return $xd(cb => {
            const d = (0, autorun_1.$od)(reader => {
                const value = observable.read(reader);
                if (!hasValue) {
                    hasValue = true;
                    lastValue = value;
                }
                else {
                    if (timeout) {
                        clearTimeout(timeout);
                    }
                    timeout = setTimeout(() => {
                        lastValue = value;
                        cb();
                    }, debounceMs);
                }
            });
            return {
                dispose() {
                    d.dispose();
                    hasValue = false;
                    lastValue = undefined;
                },
            };
        }, () => {
            if (hasValue) {
                return lastValue;
            }
            else {
                return observable.get();
            }
        });
    }
    function $Ed(event, timeoutMs, disposableStore) {
        const observable = (0, base_1.$$d)('triggeredRecently', false);
        let timeout = undefined;
        disposableStore.add(event(() => {
            observable.set(true, undefined);
            if (timeout) {
                clearTimeout(timeout);
            }
            timeout = setTimeout(() => {
                observable.set(false, undefined);
            }, timeoutMs);
        }));
        return observable;
    }
    /**
     * This makes sure the observable is being observed and keeps its cache alive.
     */
    function $Fd(observable) {
        const o = new $Hd(false, undefined);
        observable.addObserver(o);
        return (0, lifecycle_1.$Xc)(() => {
            observable.removeObserver(o);
        });
    }
    (0, base_1.$2d)($Fd);
    /**
     * This converts the given observable into an autorun.
     */
    function $Gd(observable, handleValue) {
        const o = new $Hd(true, handleValue);
        observable.addObserver(o);
        if (handleValue) {
            handleValue(observable.get());
        }
        else {
            observable.reportChanges();
        }
        return (0, lifecycle_1.$Xc)(() => {
            observable.removeObserver(o);
        });
    }
    (0, base_1.$1d)($Gd);
    class $Hd {
        constructor(b, c) {
            this.b = b;
            this.c = c;
            this.a = 0;
        }
        beginUpdate(observable) {
            this.a++;
        }
        endUpdate(observable) {
            this.a--;
            if (this.a === 0 && this.b) {
                if (this.c) {
                    this.c(observable.get());
                }
                else {
                    observable.reportChanges();
                }
            }
        }
        handlePossibleChange(observable) {
            // NO OP
        }
        handleChange(observable, change) {
            // NO OP
        }
    }
    exports.$Hd = $Hd;
    function $Id(owner, computeFn) {
        let lastValue = undefined;
        const observable = (0, derived_1.$Ud)({ owner, debugReferenceFn: computeFn }, reader => {
            lastValue = computeFn(reader, lastValue);
            return lastValue;
        });
        return observable;
    }
    function $Jd(owner, computeFn) {
        let lastValue = undefined;
        const onChange = $Bd('derivedObservableWithWritableCache');
        const observable = (0, derived_1.$Sd)(owner, reader => {
            onChange.read(reader);
            lastValue = computeFn(reader, lastValue);
            return lastValue;
        });
        return Object.assign(observable, {
            clearCache: (tx) => {
                lastValue = undefined;
                onChange.trigger(tx);
            },
            setCache: (newValue, tx) => {
                lastValue = newValue;
                onChange.trigger(tx);
            }
        });
    }
    /**
     * When the items array changes, referential equal items are not mapped again.
     */
    function $Kd(owner, items, map, keySelector) {
        let m = new ArrayMap(map, keySelector);
        const self = (0, derived_1.$Ud)({
            debugReferenceFn: map,
            owner,
            onLastObserverRemoved: () => {
                m.dispose();
                m = new ArrayMap(map);
            }
        }, (reader) => {
            m.setItems(items.read(reader));
            return m.getItems();
        });
        return self;
    }
    class ArrayMap {
        constructor(c, e) {
            this.c = c;
            this.e = e;
            this.a = new Map();
            this.b = [];
        }
        dispose() {
            this.a.forEach(entry => entry.store.dispose());
            this.a.clear();
        }
        setItems(items) {
            const newItems = [];
            const itemsToRemove = new Set(this.a.keys());
            for (const item of items) {
                const key = this.e ? this.e(item) : item;
                let entry = this.a.get(key);
                if (!entry) {
                    const store = new lifecycle_1.$Yc();
                    const out = this.c(item, store);
                    entry = { out, store };
                    this.a.set(key, entry);
                }
                else {
                    itemsToRemove.delete(key);
                }
                newItems.push(entry.out);
            }
            for (const item of itemsToRemove) {
                const entry = this.a.get(item);
                entry.store.dispose();
                this.a.delete(item);
            }
            this.b = newItems;
        }
        getItems() {
            return this.b;
        }
    }
    class $Ld {
        constructor(observable) {
            this.observable = observable;
        }
        get onDidChange() {
            return event_1.Event.fromObservableLight(this.observable);
        }
        get value() {
            return this.observable.get();
        }
    }
    exports.$Ld = $Ld;
    function $Md(owner, value) {
        if (value instanceof $Ld) {
            return value.observable;
        }
        return $xd(owner, value.onDidChange, () => value.value);
    }
    /**
     * Creates an observable that has the latest changed value of the given observables.
     * Initially (and when not observed), it has the value of the last observable.
     * When observed and any of the observables change, it has the value of the last changed observable.
     * If multiple observables change in the same transaction, the last observable wins.
    */
    function $Nd(owner, observables) {
        if (observables.length === 0) {
            throw new errors_1.$gb();
        }
        let hasLastChangedValue = false;
        let lastChangedValue = undefined;
        const result = $xd(owner, cb => {
            const store = new lifecycle_1.$Yc();
            for (const o of observables) {
                store.add((0, autorun_1.$pd)({ debugName: () => (0, debugName_1.$gd)(result, new debugName_1.$fd(owner, undefined, undefined)) + '.updateLastChangedValue' }, reader => {
                    hasLastChangedValue = true;
                    lastChangedValue = o.read(reader);
                    cb();
                }));
            }
            store.add({
                dispose() {
                    hasLastChangedValue = false;
                    lastChangedValue = undefined;
                },
            });
            return store;
        }, () => {
            if (hasLastChangedValue) {
                return lastChangedValue;
            }
            else {
                return observables[observables.length - 1].get();
            }
        });
        return result;
    }
    /**
     * Works like a derived.
     * However, if the value is not undefined, it is cached and will not be recomputed anymore.
     * In that case, the derived will unsubscribe from its dependencies.
    */
    function $Od(owner, fn) {
        return $Id(owner, (reader, lastValue) => lastValue ?? fn(reader));
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[13/*vs/base/common/observable*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/observableInternal/base*/,8/*vs/base/common/observableInternal/derived*/,7/*vs/base/common/observableInternal/autorun*/,26/*vs/base/common/observableInternal/utils*/,25/*vs/base/common/observableInternal/promise*/,24/*vs/base/common/observableInternal/api*/,6/*vs/base/common/observableInternal/logging*/]), function (require, exports, base_1, derived_1, autorun_1, utils_1, promise_1, api_1, logging_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.observableValueOpts = exports.derivedWithCancellationToken = exports.waitForState = exports.PromiseResult = exports.ObservablePromise = exports.ObservableLazyPromise = exports.ObservableLazy = exports.wasEventTriggeredRecently = exports.observableSignalFromEvent = exports.observableSignal = exports.observableFromPromise = exports.observableFromEvent = exports.recomputeInitiallyAndOnChange = exports.keepObserved = exports.derivedObservableWithWritableCache = exports.derivedObservableWithCache = exports.debouncedObservable = exports.constObservable = exports.autorunWithStoreHandleChanges = exports.autorunOpts = exports.autorunWithStore = exports.autorunHandleChanges = exports.autorunDelta = exports.autorun = exports.derivedWithStore = exports.derivedHandleChanges = exports.derivedOpts = exports.derived = exports.subtransaction = exports.transaction = exports.disposableObservableValue = exports.observableValue = void 0;
    Object.defineProperty(exports, "observableValue", { enumerable: true, get: function () { return base_1.$$d; } });
    Object.defineProperty(exports, "disposableObservableValue", { enumerable: true, get: function () { return base_1.$ae; } });
    Object.defineProperty(exports, "transaction", { enumerable: true, get: function () { return base_1.$6d; } });
    Object.defineProperty(exports, "subtransaction", { enumerable: true, get: function () { return base_1.$9d; } });
    Object.defineProperty(exports, "derived", { enumerable: true, get: function () { return derived_1.$Sd; } });
    Object.defineProperty(exports, "derivedOpts", { enumerable: true, get: function () { return derived_1.$Ud; } });
    Object.defineProperty(exports, "derivedHandleChanges", { enumerable: true, get: function () { return derived_1.$Vd; } });
    Object.defineProperty(exports, "derivedWithStore", { enumerable: true, get: function () { return derived_1.$Wd; } });
    Object.defineProperty(exports, "autorun", { enumerable: true, get: function () { return autorun_1.$od; } });
    Object.defineProperty(exports, "autorunDelta", { enumerable: true, get: function () { return autorun_1.$td; } });
    Object.defineProperty(exports, "autorunHandleChanges", { enumerable: true, get: function () { return autorun_1.$qd; } });
    Object.defineProperty(exports, "autorunWithStore", { enumerable: true, get: function () { return autorun_1.$sd; } });
    Object.defineProperty(exports, "autorunOpts", { enumerable: true, get: function () { return autorun_1.$pd; } });
    Object.defineProperty(exports, "autorunWithStoreHandleChanges", { enumerable: true, get: function () { return autorun_1.$rd; } });
    Object.defineProperty(exports, "constObservable", { enumerable: true, get: function () { return utils_1.$vd; } });
    Object.defineProperty(exports, "debouncedObservable", { enumerable: true, get: function () { return utils_1.$Cd; } });
    Object.defineProperty(exports, "derivedObservableWithCache", { enumerable: true, get: function () { return utils_1.$Id; } });
    Object.defineProperty(exports, "derivedObservableWithWritableCache", { enumerable: true, get: function () { return utils_1.$Jd; } });
    Object.defineProperty(exports, "keepObserved", { enumerable: true, get: function () { return utils_1.$Fd; } });
    Object.defineProperty(exports, "recomputeInitiallyAndOnChange", { enumerable: true, get: function () { return utils_1.$Gd; } });
    Object.defineProperty(exports, "observableFromEvent", { enumerable: true, get: function () { return utils_1.$xd; } });
    Object.defineProperty(exports, "observableFromPromise", { enumerable: true, get: function () { return utils_1.$wd; } });
    Object.defineProperty(exports, "observableSignal", { enumerable: true, get: function () { return utils_1.$Bd; } });
    Object.defineProperty(exports, "observableSignalFromEvent", { enumerable: true, get: function () { return utils_1.$Ad; } });
    Object.defineProperty(exports, "wasEventTriggeredRecently", { enumerable: true, get: function () { return utils_1.$Ed; } });
    Object.defineProperty(exports, "ObservableLazy", { enumerable: true, get: function () { return promise_1.$ce; } });
    Object.defineProperty(exports, "ObservableLazyPromise", { enumerable: true, get: function () { return promise_1.$fe; } });
    Object.defineProperty(exports, "ObservablePromise", { enumerable: true, get: function () { return promise_1.$de; } });
    Object.defineProperty(exports, "PromiseResult", { enumerable: true, get: function () { return promise_1.$ee; } });
    Object.defineProperty(exports, "waitForState", { enumerable: true, get: function () { return promise_1.$ge; } });
    Object.defineProperty(exports, "derivedWithCancellationToken", { enumerable: true, get: function () { return promise_1.$he; } });
    Object.defineProperty(exports, "observableValueOpts", { enumerable: true, get: function () { return api_1.$je; } });
    // Remove "//" in the next line to enable logging
    const enableLogging = false;
    if (enableLogging) {
        (0, logging_1.$Pd)(new logging_1.$Rd());
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[28/*vs/base/common/stream*/], __M([0/*require*/,1/*exports*/,9/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/]), function (require, exports, errors_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$De = $De;
    exports.$Ee = $Ee;
    exports.$Fe = $Fe;
    exports.$Ge = $Ge;
    exports.$He = $He;
    exports.$Ie = $Ie;
    exports.$Je = $Je;
    exports.$Ke = $Ke;
    exports.$Le = $Le;
    exports.$Me = $Me;
    exports.$Ne = $Ne;
    exports.$Oe = $Oe;
    exports.$Pe = $Pe;
    exports.$Qe = $Qe;
    exports.$Re = $Re;
    function $De(obj) {
        const candidate = obj;
        if (!candidate) {
            return false;
        }
        return typeof candidate.read === 'function';
    }
    function $Ee(obj) {
        const candidate = obj;
        if (!candidate) {
            return false;
        }
        return [candidate.on, candidate.pause, candidate.resume, candidate.destroy].every(fn => typeof fn === 'function');
    }
    function $Fe(obj) {
        const candidate = obj;
        if (!candidate) {
            return false;
        }
        return $Ee(candidate.stream) && Array.isArray(candidate.buffer) && typeof candidate.ended === 'boolean';
    }
    function $Ge(reducer, options) {
        return new WriteableStreamImpl(reducer, options);
    }
    class WriteableStreamImpl {
        constructor(e, f) {
            this.e = e;
            this.f = f;
            this.a = {
                flowing: false,
                ended: false,
                destroyed: false
            };
            this.b = {
                data: [],
                error: []
            };
            this.c = {
                data: [],
                error: [],
                end: []
            };
            this.d = [];
        }
        pause() {
            if (this.a.destroyed) {
                return;
            }
            this.a.flowing = false;
        }
        resume() {
            if (this.a.destroyed) {
                return;
            }
            if (!this.a.flowing) {
                this.a.flowing = true;
                // emit buffered events
                this.j();
                this.k();
                this.l();
            }
        }
        write(data) {
            if (this.a.destroyed) {
                return;
            }
            // flowing: directly send the data to listeners
            if (this.a.flowing) {
                this.g(data);
            }
            // not yet flowing: buffer data until flowing
            else {
                this.b.data.push(data);
                // highWaterMark: if configured, signal back when buffer reached limits
                if (typeof this.f?.highWaterMark === 'number' && this.b.data.length > this.f.highWaterMark) {
                    return new Promise(resolve => this.d.push(resolve));
                }
            }
        }
        error(error) {
            if (this.a.destroyed) {
                return;
            }
            // flowing: directly send the error to listeners
            if (this.a.flowing) {
                this.h(error);
            }
            // not yet flowing: buffer errors until flowing
            else {
                this.b.error.push(error);
            }
        }
        end(result) {
            if (this.a.destroyed) {
                return;
            }
            // end with data if provided
            if (typeof result !== 'undefined') {
                this.write(result);
            }
            // flowing: send end event to listeners
            if (this.a.flowing) {
                this.i();
                this.destroy();
            }
            // not yet flowing: remember state
            else {
                this.a.ended = true;
            }
        }
        g(data) {
            this.c.data.slice(0).forEach(listener => listener(data)); // slice to avoid listener mutation from delivering event
        }
        h(error) {
            if (this.c.error.length === 0) {
                (0, errors_1.$4)(error); // nobody listened to this error so we log it as unexpected
            }
            else {
                this.c.error.slice(0).forEach(listener => listener(error)); // slice to avoid listener mutation from delivering event
            }
        }
        i() {
            this.c.end.slice(0).forEach(listener => listener()); // slice to avoid listener mutation from delivering event
        }
        on(event, callback) {
            if (this.a.destroyed) {
                return;
            }
            switch (event) {
                case 'data':
                    this.c.data.push(callback);
                    // switch into flowing mode as soon as the first 'data'
                    // listener is added and we are not yet in flowing mode
                    this.resume();
                    break;
                case 'end':
                    this.c.end.push(callback);
                    // emit 'end' event directly if we are flowing
                    // and the end has already been reached
                    //
                    // finish() when it went through
                    if (this.a.flowing && this.l()) {
                        this.destroy();
                    }
                    break;
                case 'error':
                    this.c.error.push(callback);
                    // emit buffered 'error' events unless done already
                    // now that we know that we have at least one listener
                    if (this.a.flowing) {
                        this.k();
                    }
                    break;
            }
        }
        removeListener(event, callback) {
            if (this.a.destroyed) {
                return;
            }
            let listeners = undefined;
            switch (event) {
                case 'data':
                    listeners = this.c.data;
                    break;
                case 'end':
                    listeners = this.c.end;
                    break;
                case 'error':
                    listeners = this.c.error;
                    break;
            }
            if (listeners) {
                const index = listeners.indexOf(callback);
                if (index >= 0) {
                    listeners.splice(index, 1);
                }
            }
        }
        j() {
            if (this.b.data.length > 0) {
                const fullDataBuffer = this.e(this.b.data);
                this.g(fullDataBuffer);
                this.b.data.length = 0;
                // When the buffer is empty, resolve all pending writers
                const pendingWritePromises = [...this.d];
                this.d.length = 0;
                pendingWritePromises.forEach(pendingWritePromise => pendingWritePromise());
            }
        }
        k() {
            if (this.c.error.length > 0) {
                for (const error of this.b.error) {
                    this.h(error);
                }
                this.b.error.length = 0;
            }
        }
        l() {
            if (this.a.ended) {
                this.i();
                return this.c.end.length > 0;
            }
            return false;
        }
        destroy() {
            if (!this.a.destroyed) {
                this.a.destroyed = true;
                this.a.ended = true;
                this.b.data.length = 0;
                this.b.error.length = 0;
                this.c.data.length = 0;
                this.c.error.length = 0;
                this.c.end.length = 0;
                this.d.length = 0;
            }
        }
    }
    /**
     * Helper to fully read a T readable into a T.
     */
    function $He(readable, reducer) {
        const chunks = [];
        let chunk;
        while ((chunk = readable.read()) !== null) {
            chunks.push(chunk);
        }
        return reducer(chunks);
    }
    /**
     * Helper to read a T readable up to a maximum of chunks. If the limit is
     * reached, will return a readable instead to ensure all data can still
     * be read.
     */
    function $Ie(readable, reducer, maxChunks) {
        const chunks = [];
        let chunk = undefined;
        while ((chunk = readable.read()) !== null && chunks.length < maxChunks) {
            chunks.push(chunk);
        }
        // If the last chunk is null, it means we reached the end of
        // the readable and return all the data at once
        if (chunk === null && chunks.length > 0) {
            return reducer(chunks);
        }
        // Otherwise, we still have a chunk, it means we reached the maxChunks
        // value and as such we return a new Readable that first returns
        // the existing read chunks and then continues with reading from
        // the underlying readable.
        return {
            read: () => {
                // First consume chunks from our array
                if (chunks.length > 0) {
                    return chunks.shift();
                }
                // Then ensure to return our last read chunk
                if (typeof chunk !== 'undefined') {
                    const lastReadChunk = chunk;
                    // explicitly use undefined here to indicate that we consumed
                    // the chunk, which could have either been null or valued.
                    chunk = undefined;
                    return lastReadChunk;
                }
                // Finally delegate back to the Readable
                return readable.read();
            }
        };
    }
    function $Je(stream, reducer) {
        return new Promise((resolve, reject) => {
            const chunks = [];
            $Ke(stream, {
                onData: chunk => {
                    if (reducer) {
                        chunks.push(chunk);
                    }
                },
                onError: error => {
                    if (reducer) {
                        reject(error);
                    }
                    else {
                        resolve(undefined);
                    }
                },
                onEnd: () => {
                    if (reducer) {
                        resolve(reducer(chunks));
                    }
                    else {
                        resolve(undefined);
                    }
                }
            });
        });
    }
    /**
     * Helper to listen to all events of a T stream in proper order.
     */
    function $Ke(stream, listener, token) {
        stream.on('error', error => {
            if (!token?.isCancellationRequested) {
                listener.onError(error);
            }
        });
        stream.on('end', () => {
            if (!token?.isCancellationRequested) {
                listener.onEnd();
            }
        });
        // Adding the `data` listener will turn the stream
        // into flowing mode. As such it is important to
        // add this listener last (DO NOT CHANGE!)
        stream.on('data', data => {
            if (!token?.isCancellationRequested) {
                listener.onData(data);
            }
        });
    }
    /**
     * Helper to peek up to `maxChunks` into a stream. The return type signals if
     * the stream has ended or not. If not, caller needs to add a `data` listener
     * to continue reading.
     */
    function $Le(stream, maxChunks) {
        return new Promise((resolve, reject) => {
            const streamListeners = new lifecycle_1.$Yc();
            const buffer = [];
            // Data Listener
            const dataListener = (chunk) => {
                // Add to buffer
                buffer.push(chunk);
                // We reached maxChunks and thus need to return
                if (buffer.length > maxChunks) {
                    // Dispose any listeners and ensure to pause the
                    // stream so that it can be consumed again by caller
                    streamListeners.dispose();
                    stream.pause();
                    return resolve({ stream, buffer, ended: false });
                }
            };
            // Error Listener
            const errorListener = (error) => {
                streamListeners.dispose();
                return reject(error);
            };
            // End Listener
            const endListener = () => {
                streamListeners.dispose();
                return resolve({ stream, buffer, ended: true });
            };
            streamListeners.add((0, lifecycle_1.$Xc)(() => stream.removeListener('error', errorListener)));
            stream.on('error', errorListener);
            streamListeners.add((0, lifecycle_1.$Xc)(() => stream.removeListener('end', endListener)));
            stream.on('end', endListener);
            // Important: leave the `data` listener last because
            // this can turn the stream into flowing mode and we
            // want `error` events to be received as well.
            streamListeners.add((0, lifecycle_1.$Xc)(() => stream.removeListener('data', dataListener)));
            stream.on('data', dataListener);
        });
    }
    /**
     * Helper to create a readable stream from an existing T.
     */
    function $Me(t, reducer) {
        const stream = $Ge(reducer);
        stream.end(t);
        return stream;
    }
    /**
     * Helper to create an empty stream
     */
    function $Ne() {
        const stream = $Ge(() => { throw new Error('not supported'); });
        stream.end();
        return stream;
    }
    /**
     * Helper to convert a T into a Readable<T>.
     */
    function $Oe(t) {
        let consumed = false;
        return {
            read: () => {
                if (consumed) {
                    return null;
                }
                consumed = true;
                return t;
            }
        };
    }
    /**
     * Helper to transform a readable stream into another stream.
     */
    function $Pe(stream, transformer, reducer) {
        const target = $Ge(reducer);
        $Ke(stream, {
            onData: data => target.write(transformer.data(data)),
            onError: error => target.error(transformer.error ? transformer.error(error) : error),
            onEnd: () => target.end()
        });
        return target;
    }
    /**
     * Helper to take an existing readable that will
     * have a prefix injected to the beginning.
     */
    function $Qe(prefix, readable, reducer) {
        let prefixHandled = false;
        return {
            read: () => {
                const chunk = readable.read();
                // Handle prefix only once
                if (!prefixHandled) {
                    prefixHandled = true;
                    // If we have also a read-result, make
                    // sure to reduce it to a single result
                    if (chunk !== null) {
                        return reducer([prefix, chunk]);
                    }
                    // Otherwise, just return prefix directly
                    return prefix;
                }
                return chunk;
            }
        };
    }
    /**
     * Helper to take an existing stream that will
     * have a prefix injected to the beginning.
     */
    function $Re(prefix, stream, reducer) {
        let prefixHandled = false;
        const target = $Ge(reducer);
        $Ke(stream, {
            onData: data => {
                // Handle prefix only once
                if (!prefixHandled) {
                    prefixHandled = true;
                    return target.write(reducer([prefix, data]));
                }
                return target.write(data);
            },
            onError: error => target.error(error),
            onEnd: () => {
                // Handle prefix only once
                if (!prefixHandled) {
                    prefixHandled = true;
                    target.write(prefix);
                }
                target.end();
            }
        });
        return target;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/























define(__m[14/*vs/base/common/buffer*/], __M([0/*require*/,1/*exports*/,44/*vs/base/common/lazy*/,28/*vs/base/common/stream*/]), function (require, exports, lazy_1, streams) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$Se = void 0;
    exports.$Te = $Te;
    exports.$Ue = $Ue;
    exports.$Ve = $Ve;
    exports.$We = $We;
    exports.$Xe = $Xe;
    exports.$Ye = $Ye;
    exports.$Ze = $Ze;
    exports.$1e = $1e;
    exports.$2e = $2e;
    exports.$3e = $3e;
    exports.$4e = $4e;
    exports.$5e = $5e;
    exports.$6e = $6e;
    exports.$7e = $7e;
    exports.$8e = $8e;
    exports.$9e = $9e;
    exports.$0e = $0e;
    exports.$$e = $$e;
    exports.$_e = $_e;
    exports.$af = $af;
    streams = __importStar(streams);
    const hasBuffer = (typeof Buffer !== 'undefined');
    const indexOfTable = new lazy_1.$Y(() => new Uint8Array(256));
    let textEncoder;
    let textDecoder;
    class $Se {
        /**
         * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
         * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
         */
        static alloc(byteLength) {
            if (hasBuffer) {
                return new $Se(Buffer.allocUnsafe(byteLength));
            }
            else {
                return new $Se(new Uint8Array(byteLength));
            }
        }
        /**
         * When running in a nodejs context, if `actual` is not a nodejs Buffer, the backing store for
         * the returned `VSBuffer` instance might use a nodejs Buffer allocated from node's Buffer pool,
         * which is not transferrable.
         */
        static wrap(actual) {
            if (hasBuffer && !(Buffer.isBuffer(actual))) {
                // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
                // Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array
                actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength);
            }
            return new $Se(actual);
        }
        /**
         * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
         * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
         */
        static fromString(source, options) {
            const dontUseNodeBuffer = options?.dontUseNodeBuffer || false;
            if (!dontUseNodeBuffer && hasBuffer) {
                return new $Se(Buffer.from(source));
            }
            else {
                if (!textEncoder) {
                    textEncoder = new TextEncoder();
                }
                return new $Se(textEncoder.encode(source));
            }
        }
        /**
         * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
         * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
         */
        static fromByteArray(source) {
            const result = $Se.alloc(source.length);
            for (let i = 0, len = source.length; i < len; i++) {
                result.buffer[i] = source[i];
            }
            return result;
        }
        /**
         * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
         * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
         */
        static concat(buffers, totalLength) {
            if (typeof totalLength === 'undefined') {
                totalLength = 0;
                for (let i = 0, len = buffers.length; i < len; i++) {
                    totalLength += buffers[i].byteLength;
                }
            }
            const ret = $Se.alloc(totalLength);
            let offset = 0;
            for (let i = 0, len = buffers.length; i < len; i++) {
                const element = buffers[i];
                ret.set(element, offset);
                offset += element.byteLength;
            }
            return ret;
        }
        constructor(buffer) {
            this.buffer = buffer;
            this.byteLength = this.buffer.byteLength;
        }
        /**
         * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
         * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
         */
        clone() {
            const result = $Se.alloc(this.byteLength);
            result.set(this);
            return result;
        }
        toString() {
            if (hasBuffer) {
                return this.buffer.toString();
            }
            else {
                if (!textDecoder) {
                    textDecoder = new TextDecoder();
                }
                return textDecoder.decode(this.buffer);
            }
        }
        slice(start, end) {
            // IMPORTANT: use subarray instead of slice because TypedArray#slice
            // creates shallow copy and NodeBuffer#slice doesn't. The use of subarray
            // ensures the same, performance, behaviour.
            return new $Se(this.buffer.subarray(start, end));
        }
        set(array, offset) {
            if (array instanceof $Se) {
                this.buffer.set(array.buffer, offset);
            }
            else if (array instanceof Uint8Array) {
                this.buffer.set(array, offset);
            }
            else if (array instanceof ArrayBuffer) {
                this.buffer.set(new Uint8Array(array), offset);
            }
            else if (ArrayBuffer.isView(array)) {
                this.buffer.set(new Uint8Array(array.buffer, array.byteOffset, array.byteLength), offset);
            }
            else {
                throw new Error(`Unknown argument 'array'`);
            }
        }
        readUInt32BE(offset) {
            return $We(this.buffer, offset);
        }
        writeUInt32BE(value, offset) {
            $Xe(this.buffer, value, offset);
        }
        readUInt32LE(offset) {
            return $Ye(this.buffer, offset);
        }
        writeUInt32LE(value, offset) {
            $Ze(this.buffer, value, offset);
        }
        readUInt8(offset) {
            return $1e(this.buffer, offset);
        }
        writeUInt8(value, offset) {
            $2e(this.buffer, value, offset);
        }
        indexOf(subarray, offset = 0) {
            return $Te(this.buffer, subarray instanceof $Se ? subarray.buffer : subarray, offset);
        }
    }
    exports.$Se = $Se;
    /**
     * Like String.indexOf, but works on Uint8Arrays.
     * Uses the boyer-moore-horspool algorithm to be reasonably speedy.
     */
    function $Te(haystack, needle, offset = 0) {
        const needleLen = needle.byteLength;
        const haystackLen = haystack.byteLength;
        if (needleLen === 0) {
            return 0;
        }
        if (needleLen === 1) {
            return haystack.indexOf(needle[0]);
        }
        if (needleLen > haystackLen - offset) {
            return -1;
        }
        // find index of the subarray using boyer-moore-horspool algorithm
        const table = indexOfTable.value;
        table.fill(needle.length);
        for (let i = 0; i < needle.length; i++) {
            table[needle[i]] = needle.length - i - 1;
        }
        let i = offset + needle.length - 1;
        let j = i;
        let result = -1;
        while (i < haystackLen) {
            if (haystack[i] === needle[j]) {
                if (j === 0) {
                    result = i;
                    break;
                }
                i--;
                j--;
            }
            else {
                i += Math.max(needle.length - j, table[haystack[i]]);
                j = needle.length - 1;
            }
        }
        return result;
    }
    function $Ue(source, offset) {
        return (((source[offset + 0] << 0) >>> 0) |
            ((source[offset + 1] << 8) >>> 0));
    }
    function $Ve(destination, value, offset) {
        destination[offset + 0] = (value & 0b11111111);
        value = value >>> 8;
        destination[offset + 1] = (value & 0b11111111);
    }
    function $We(source, offset) {
        return (source[offset] * 2 ** 24
            + source[offset + 1] * 2 ** 16
            + source[offset + 2] * 2 ** 8
            + source[offset + 3]);
    }
    function $Xe(destination, value, offset) {
        destination[offset + 3] = value;
        value = value >>> 8;
        destination[offset + 2] = value;
        value = value >>> 8;
        destination[offset + 1] = value;
        value = value >>> 8;
        destination[offset] = value;
    }
    function $Ye(source, offset) {
        return (((source[offset + 0] << 0) >>> 0) |
            ((source[offset + 1] << 8) >>> 0) |
            ((source[offset + 2] << 16) >>> 0) |
            ((source[offset + 3] << 24) >>> 0));
    }
    function $Ze(destination, value, offset) {
        destination[offset + 0] = (value & 0b11111111);
        value = value >>> 8;
        destination[offset + 1] = (value & 0b11111111);
        value = value >>> 8;
        destination[offset + 2] = (value & 0b11111111);
        value = value >>> 8;
        destination[offset + 3] = (value & 0b11111111);
    }
    function $1e(source, offset) {
        return source[offset];
    }
    function $2e(destination, value, offset) {
        destination[offset] = value;
    }
    function $3e(readable) {
        return streams.$He(readable, chunks => $Se.concat(chunks));
    }
    function $4e(buffer) {
        return streams.$Oe(buffer);
    }
    function $5e(stream) {
        return streams.$Je(stream, chunks => $Se.concat(chunks));
    }
    async function $6e(bufferedStream) {
        if (bufferedStream.ended) {
            return $Se.concat(bufferedStream.buffer);
        }
        return $Se.concat([
            // Include already read chunks...
            ...bufferedStream.buffer,
            // ...and all additional chunks
            await $5e(bufferedStream.stream)
        ]);
    }
    function $7e(buffer) {
        return streams.$Me(buffer, chunks => $Se.concat(chunks));
    }
    function $8e(stream) {
        return streams.$Pe(stream, { data: data => typeof data === 'string' ? $Se.fromString(data) : $Se.wrap(data) }, chunks => $Se.concat(chunks));
    }
    function $9e(options) {
        return streams.$Ge(chunks => $Se.concat(chunks), options);
    }
    function $0e(prefix, readable) {
        return streams.$Qe(prefix, readable, chunks => $Se.concat(chunks));
    }
    function $$e(prefix, stream) {
        return streams.$Re(prefix, stream, chunks => $Se.concat(chunks));
    }
    /** Decodes base64 to a uint8 array. URL-encoded and unpadded base64 is allowed. */
    function $_e(encoded) {
        let building = 0;
        let remainder = 0;
        let bufi = 0;
        // The simpler way to do this is `Uint8Array.from(atob(str), c => c.charCodeAt(0))`,
        // but that's about 10-20x slower than this function in current Chromium versions.
        const buffer = new Uint8Array(Math.floor(encoded.length / 4 * 3));
        const append = (value) => {
            switch (remainder) {
                case 3:
                    buffer[bufi++] = building | value;
                    remainder = 0;
                    break;
                case 2:
                    buffer[bufi++] = building | (value >>> 2);
                    building = value << 6;
                    remainder = 3;
                    break;
                case 1:
                    buffer[bufi++] = building | (value >>> 4);
                    building = value << 4;
                    remainder = 2;
                    break;
                default:
                    building = value << 2;
                    remainder = 1;
            }
        };
        for (let i = 0; i < encoded.length; i++) {
            const code = encoded.charCodeAt(i);
            // See https://datatracker.ietf.org/doc/html/rfc4648#section-4
            // This branchy code is about 3x faster than an indexOf on a base64 char string.
            if (code >= 65 && code <= 90) {
                append(code - 65); // A-Z starts ranges from char code 65 to 90
            }
            else if (code >= 97 && code <= 122) {
                append(code - 97 + 26); // a-z starts ranges from char code 97 to 122, starting at byte 26
            }
            else if (code >= 48 && code <= 57) {
                append(code - 48 + 52); // 0-9 starts ranges from char code 48 to 58, starting at byte 52
            }
            else if (code === 43 || code === 45) {
                append(62); // "+" or "-" for URLS
            }
            else if (code === 47 || code === 95) {
                append(63); // "/" or "_" for URLS
            }
            else if (code === 61) {
                break; // "="
            }
            else {
                throw new SyntaxError(`Unexpected base64 character ${encoded[i]}`);
            }
        }
        const unpadded = bufi;
        while (remainder > 0) {
            append(0);
        }
        // slice is needed to account for overestimation due to padding
        return $Se.wrap(buffer).slice(0, unpadded);
    }
    const base64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    const base64UrlSafeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
    /** Encodes a buffer to a base64 string. */
    function $af({ buffer }, padded = true, urlSafe = false) {
        const dictionary = urlSafe ? base64UrlSafeAlphabet : base64Alphabet;
        let output = '';
        const remainder = buffer.byteLength % 3;
        let i = 0;
        for (; i < buffer.byteLength - remainder; i += 3) {
            const a = buffer[i + 0];
            const b = buffer[i + 1];
            const c = buffer[i + 2];
            output += dictionary[a >>> 2];
            output += dictionary[(a << 4 | b >>> 4) & 0b111111];
            output += dictionary[(b << 2 | c >>> 6) & 0b111111];
            output += dictionary[c & 0b111111];
        }
        if (remainder === 1) {
            const a = buffer[i + 0];
            output += dictionary[a >>> 2];
            output += dictionary[(a << 4) & 0b111111];
            if (padded) {
                output += '==';
            }
        }
        else if (remainder === 2) {
            const a = buffer[i + 0];
            const b = buffer[i + 1];
            output += dictionary[a >>> 2];
            output += dictionary[(a << 4 | b >>> 4) & 0b111111];
            output += dictionary[(b << 2) & 0b111111];
            if (padded) {
                output += '=';
            }
        }
        return output;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[15/*vs/editor/common/core/eolCounter*/], __M([0/*require*/,1/*exports*/,45/*vs/base/common/charCode*/]), function (require, exports, charCode_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StringEOL = void 0;
    exports.$Hu = $Hu;
    var StringEOL;
    (function (StringEOL) {
        StringEOL[StringEOL["Unknown"] = 0] = "Unknown";
        StringEOL[StringEOL["Invalid"] = 3] = "Invalid";
        StringEOL[StringEOL["LF"] = 1] = "LF";
        StringEOL[StringEOL["CRLF"] = 2] = "CRLF";
    })(StringEOL || (exports.StringEOL = StringEOL = {}));
    function $Hu(text) {
        let eolCount = 0;
        let firstLineLength = 0;
        let lastLineStart = 0;
        let eol = StringEOL.Unknown;
        for (let i = 0, len = text.length; i < len; i++) {
            const chr = text.charCodeAt(i);
            if (chr === charCode_1.CharCode.CarriageReturn) {
                if (eolCount === 0) {
                    firstLineLength = i;
                }
                eolCount++;
                if (i + 1 < len && text.charCodeAt(i + 1) === charCode_1.CharCode.LineFeed) {
                    // \r\n... case
                    eol |= StringEOL.CRLF;
                    i++; // skip \n
                }
                else {
                    // \r... case
                    eol |= StringEOL.Invalid;
                }
                lastLineStart = i + 1;
            }
            else if (chr === charCode_1.CharCode.LineFeed) {
                // \n... case
                eol |= StringEOL.LF;
                if (eolCount === 0) {
                    firstLineLength = i;
                }
                eolCount++;
                lastLineStart = i + 1;
            }
        }
        if (eolCount === 0) {
            firstLineLength = text.length;
        }
        return [eolCount, firstLineLength, text.length - lastLineStart, eol];
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[29/*vs/editor/common/model/fixedArray*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/arrays*/]), function (require, exports, arrays_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$ND = void 0;
    /**
     * An array that avoids being sparse by always
     * filling up unused indices with a default value.
     */
    class $ND {
        constructor(b) {
            this.b = b;
            this.a = [];
        }
        get(index) {
            if (index < this.a.length) {
                return this.a[index];
            }
            return this.b;
        }
        set(index, value) {
            while (index >= this.a.length) {
                this.a[this.a.length] = this.b;
            }
            this.a[index] = value;
        }
        replace(index, oldLength, newLength) {
            if (index >= this.a.length) {
                return;
            }
            if (oldLength === 0) {
                this.insert(index, newLength);
                return;
            }
            else if (newLength === 0) {
                this.delete(index, oldLength);
                return;
            }
            const before = this.a.slice(0, index);
            const after = this.a.slice(index + oldLength);
            const insertArr = arrayFill(newLength, this.b);
            this.a = before.concat(insertArr, after);
        }
        delete(deleteIndex, deleteCount) {
            if (deleteCount === 0 || deleteIndex >= this.a.length) {
                return;
            }
            this.a.splice(deleteIndex, deleteCount);
        }
        insert(insertIndex, insertCount) {
            if (insertCount === 0 || insertIndex >= this.a.length) {
                return;
            }
            const arr = [];
            for (let i = 0; i < insertCount; i++) {
                arr[i] = this.b;
            }
            this.a = (0, arrays_1.$Zb)(this.a, insertIndex, arr);
        }
    }
    exports.$ND = $ND;
    function arrayFill(length, value) {
        const arr = [];
        for (let i = 0; i < length; i++) {
            arr[i] = value;
        }
        return arr;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[10/*vs/editor/common/tokens/lineTokens*/], __M([0/*require*/,1/*exports*/,11/*vs/editor/common/encodedTokenAttributes*/]), function (require, exports, encodedTokenAttributes_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$Iu = void 0;
    exports.$Ju = $Ju;
    class $Iu {
        static { this.defaultTokenMetadata = ((encodedTokenAttributes_1.FontStyle.None << encodedTokenAttributes_1.MetadataConsts.FONT_STYLE_OFFSET)
            | (encodedTokenAttributes_1.ColorId.DefaultForeground << encodedTokenAttributes_1.MetadataConsts.FOREGROUND_OFFSET)
            | (encodedTokenAttributes_1.ColorId.DefaultBackground << encodedTokenAttributes_1.MetadataConsts.BACKGROUND_OFFSET)) >>> 0; }
        static createEmpty(lineContent, decoder) {
            const defaultMetadata = $Iu.defaultTokenMetadata;
            const tokens = new Uint32Array(2);
            tokens[0] = lineContent.length;
            tokens[1] = defaultMetadata;
            return new $Iu(tokens, lineContent, decoder);
        }
        static createFromTextAndMetadata(data, decoder) {
            let offset = 0;
            let fullText = '';
            const tokens = new Array();
            for (const { text, metadata } of data) {
                tokens.push(offset + text.length, metadata);
                offset += text.length;
                fullText += text;
            }
            return new $Iu(new Uint32Array(tokens), fullText, decoder);
        }
        constructor(tokens, text, decoder) {
            this._lineTokensBrand = undefined;
            this.a = tokens;
            this.b = (this.a.length >>> 1);
            this.c = text;
            this.languageIdCodec = decoder;
        }
        equals(other) {
            if (other instanceof $Iu) {
                return this.slicedEquals(other, 0, this.b);
            }
            return false;
        }
        slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) {
            if (this.c !== other.c) {
                return false;
            }
            if (this.b !== other.b) {
                return false;
            }
            const from = (sliceFromTokenIndex << 1);
            const to = from + (sliceTokenCount << 1);
            for (let i = from; i < to; i++) {
                if (this.a[i] !== other.a[i]) {
                    return false;
                }
            }
            return true;
        }
        getLineContent() {
            return this.c;
        }
        getCount() {
            return this.b;
        }
        getStartOffset(tokenIndex) {
            if (tokenIndex > 0) {
                return this.a[(tokenIndex - 1) << 1];
            }
            return 0;
        }
        getMetadata(tokenIndex) {
            const metadata = this.a[(tokenIndex << 1) + 1];
            return metadata;
        }
        getLanguageId(tokenIndex) {
            const metadata = this.a[(tokenIndex << 1) + 1];
            const languageId = encodedTokenAttributes_1.$Du.getLanguageId(metadata);
            return this.languageIdCodec.decodeLanguageId(languageId);
        }
        getStandardTokenType(tokenIndex) {
            const metadata = this.a[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.$Du.getTokenType(metadata);
        }
        getForeground(tokenIndex) {
            const metadata = this.a[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.$Du.getForeground(metadata);
        }
        getClassName(tokenIndex) {
            const metadata = this.a[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.$Du.getClassNameFromMetadata(metadata);
        }
        getInlineStyle(tokenIndex, colorMap) {
            const metadata = this.a[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.$Du.getInlineStyleFromMetadata(metadata, colorMap);
        }
        getPresentation(tokenIndex) {
            const metadata = this.a[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.$Du.getPresentationFromMetadata(metadata);
        }
        getEndOffset(tokenIndex) {
            return this.a[tokenIndex << 1];
        }
        /**
         * Find the token containing offset `offset`.
         * @param offset The search offset
         * @return The index of the token containing the offset.
         */
        findTokenIndexAtOffset(offset) {
            return $Iu.findIndexInTokensArray(this.a, offset);
        }
        inflate() {
            return this;
        }
        sliceAndInflate(startOffset, endOffset, deltaOffset) {
            return new SliceLineTokens(this, startOffset, endOffset, deltaOffset);
        }
        static convertToEndOffset(tokens, lineTextLength) {
            const tokenCount = (tokens.length >>> 1);
            const lastTokenIndex = tokenCount - 1;
            for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) {
                tokens[tokenIndex << 1] = tokens[(tokenIndex + 1) << 1];
            }
            tokens[lastTokenIndex << 1] = lineTextLength;
        }
        static findIndexInTokensArray(tokens, desiredIndex) {
            if (tokens.length <= 2) {
                return 0;
            }
            let low = 0;
            let high = (tokens.length >>> 1) - 1;
            while (low < high) {
                const mid = low + Math.floor((high - low) / 2);
                const endOffset = tokens[(mid << 1)];
                if (endOffset === desiredIndex) {
                    return mid + 1;
                }
                else if (endOffset < desiredIndex) {
                    low = mid + 1;
                }
                else if (endOffset > desiredIndex) {
                    high = mid;
                }
            }
            return low;
        }
        /**
         * @pure
         * @param insertTokens Must be sorted by offset.
        */
        withInserted(insertTokens) {
            if (insertTokens.length === 0) {
                return this;
            }
            let nextOriginalTokenIdx = 0;
            let nextInsertTokenIdx = 0;
            let text = '';
            const newTokens = new Array();
            let originalEndOffset = 0;
            while (true) {
                const nextOriginalTokenEndOffset = nextOriginalTokenIdx < this.b ? this.a[nextOriginalTokenIdx << 1] : -1;
                const nextInsertToken = nextInsertTokenIdx < insertTokens.length ? insertTokens[nextInsertTokenIdx] : null;
                if (nextOriginalTokenEndOffset !== -1 && (nextInsertToken === null || nextOriginalTokenEndOffset <= nextInsertToken.offset)) {
                    // original token ends before next insert token
                    text += this.c.substring(originalEndOffset, nextOriginalTokenEndOffset);
                    const metadata = this.a[(nextOriginalTokenIdx << 1) + 1];
                    newTokens.push(text.length, metadata);
                    nextOriginalTokenIdx++;
                    originalEndOffset = nextOriginalTokenEndOffset;
                }
                else if (nextInsertToken) {
                    if (nextInsertToken.offset > originalEndOffset) {
                        // insert token is in the middle of the next token.
                        text += this.c.substring(originalEndOffset, nextInsertToken.offset);
                        const metadata = this.a[(nextOriginalTokenIdx << 1) + 1];
                        newTokens.push(text.length, metadata);
                        originalEndOffset = nextInsertToken.offset;
                    }
                    text += nextInsertToken.text;
                    newTokens.push(text.length, nextInsertToken.tokenMetadata);
                    nextInsertTokenIdx++;
                }
                else {
                    break;
                }
            }
            return new $Iu(new Uint32Array(newTokens), text, this.languageIdCodec);
        }
        getTokenText(tokenIndex) {
            const startOffset = this.getStartOffset(tokenIndex);
            const endOffset = this.getEndOffset(tokenIndex);
            const text = this.c.substring(startOffset, endOffset);
            return text;
        }
        forEach(callback) {
            const tokenCount = this.getCount();
            for (let tokenIndex = 0; tokenIndex < tokenCount; tokenIndex++) {
                callback(tokenIndex);
            }
        }
    }
    exports.$Iu = $Iu;
    class SliceLineTokens {
        constructor(source, startOffset, endOffset, deltaOffset) {
            this.a = source;
            this.b = startOffset;
            this.c = endOffset;
            this.d = deltaOffset;
            this.e = source.findTokenIndexAtOffset(startOffset);
            this.languageIdCodec = source.languageIdCodec;
            this.f = 0;
            for (let i = this.e, len = source.getCount(); i < len; i++) {
                const tokenStartOffset = source.getStartOffset(i);
                if (tokenStartOffset >= endOffset) {
                    break;
                }
                this.f++;
            }
        }
        getMetadata(tokenIndex) {
            return this.a.getMetadata(this.e + tokenIndex);
        }
        getLanguageId(tokenIndex) {
            return this.a.getLanguageId(this.e + tokenIndex);
        }
        getLineContent() {
            return this.a.getLineContent().substring(this.b, this.c);
        }
        equals(other) {
            if (other instanceof SliceLineTokens) {
                return (this.b === other.b
                    && this.c === other.c
                    && this.d === other.d
                    && this.a.slicedEquals(other.a, this.e, this.f));
            }
            return false;
        }
        getCount() {
            return this.f;
        }
        getStandardTokenType(tokenIndex) {
            return this.a.getStandardTokenType(this.e + tokenIndex);
        }
        getForeground(tokenIndex) {
            return this.a.getForeground(this.e + tokenIndex);
        }
        getEndOffset(tokenIndex) {
            const tokenEndOffset = this.a.getEndOffset(this.e + tokenIndex);
            return Math.min(this.c, tokenEndOffset) - this.b + this.d;
        }
        getClassName(tokenIndex) {
            return this.a.getClassName(this.e + tokenIndex);
        }
        getInlineStyle(tokenIndex, colorMap) {
            return this.a.getInlineStyle(this.e + tokenIndex, colorMap);
        }
        getPresentation(tokenIndex) {
            return this.a.getPresentation(this.e + tokenIndex);
        }
        findTokenIndexAtOffset(offset) {
            return this.a.findTokenIndexAtOffset(offset + this.b - this.d) - this.e;
        }
        getTokenText(tokenIndex) {
            const adjustedTokenIndex = this.e + tokenIndex;
            const tokenStartOffset = this.a.getStartOffset(adjustedTokenIndex);
            const tokenEndOffset = this.a.getEndOffset(adjustedTokenIndex);
            let text = this.a.getTokenText(adjustedTokenIndex);
            if (tokenStartOffset < this.b) {
                text = text.substring(this.b - tokenStartOffset);
            }
            if (tokenEndOffset > this.c) {
                text = text.substring(0, text.length - (tokenEndOffset - this.c));
            }
            return text;
        }
        forEach(callback) {
            for (let tokenIndex = 0; tokenIndex < this.getCount(); tokenIndex++) {
                callback(tokenIndex);
            }
        }
    }
    function $Ju(model, position) {
        const lineNumber = position.lineNumber;
        if (!model.tokenization.isCheapToTokenize(lineNumber)) {
            return undefined;
        }
        model.tokenization.forceTokenization(lineNumber);
        const lineTokens = model.tokenization.getLineTokens(lineNumber);
        const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        const tokenType = lineTokens.getStandardTokenType(tokenIndex);
        return tokenType;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[30/*vs/editor/common/tokens/contiguousTokensEditing*/], __M([0/*require*/,1/*exports*/,10/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, lineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$Lu = exports.$Ku = void 0;
    exports.$Mu = $Mu;
    exports.$Ku = (new Uint32Array(0)).buffer;
    class $Lu {
        static deleteBeginning(lineTokens, toChIndex) {
            if (lineTokens === null || lineTokens === exports.$Ku) {
                return lineTokens;
            }
            return $Lu.delete(lineTokens, 0, toChIndex);
        }
        static deleteEnding(lineTokens, fromChIndex) {
            if (lineTokens === null || lineTokens === exports.$Ku) {
                return lineTokens;
            }
            const tokens = $Mu(lineTokens);
            const lineTextLength = tokens[tokens.length - 2];
            return $Lu.delete(lineTokens, fromChIndex, lineTextLength);
        }
        static delete(lineTokens, fromChIndex, toChIndex) {
            if (lineTokens === null || lineTokens === exports.$Ku || fromChIndex === toChIndex) {
                return lineTokens;
            }
            const tokens = $Mu(lineTokens);
            const tokensCount = (tokens.length >>> 1);
            // special case: deleting everything
            if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {
                return exports.$Ku;
            }
            const fromTokenIndex = lineTokens_1.$Iu.findIndexInTokensArray(tokens, fromChIndex);
            const fromTokenStartOffset = (fromTokenIndex > 0 ? tokens[(fromTokenIndex - 1) << 1] : 0);
            const fromTokenEndOffset = tokens[fromTokenIndex << 1];
            if (toChIndex < fromTokenEndOffset) {
                // the delete range is inside a single token
                const delta = (toChIndex - fromChIndex);
                for (let i = fromTokenIndex; i < tokensCount; i++) {
                    tokens[i << 1] -= delta;
                }
                return lineTokens;
            }
            let dest;
            let lastEnd;
            if (fromTokenStartOffset !== fromChIndex) {
                tokens[fromTokenIndex << 1] = fromChIndex;
                dest = ((fromTokenIndex + 1) << 1);
                lastEnd = fromChIndex;
            }
            else {
                dest = (fromTokenIndex << 1);
                lastEnd = fromTokenStartOffset;
            }
            const delta = (toChIndex - fromChIndex);
            for (let tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) {
                const tokenEndOffset = tokens[tokenIndex << 1] - delta;
                if (tokenEndOffset > lastEnd) {
                    tokens[dest++] = tokenEndOffset;
                    tokens[dest++] = tokens[(tokenIndex << 1) + 1];
                    lastEnd = tokenEndOffset;
                }
            }
            if (dest === tokens.length) {
                // nothing to trim
                return lineTokens;
            }
            const tmp = new Uint32Array(dest);
            tmp.set(tokens.subarray(0, dest), 0);
            return tmp.buffer;
        }
        static append(lineTokens, _otherTokens) {
            if (_otherTokens === exports.$Ku) {
                return lineTokens;
            }
            if (lineTokens === exports.$Ku) {
                return _otherTokens;
            }
            if (lineTokens === null) {
                return lineTokens;
            }
            if (_otherTokens === null) {
                // cannot determine combined line length...
                return null;
            }
            const myTokens = $Mu(lineTokens);
            const otherTokens = $Mu(_otherTokens);
            const otherTokensCount = (otherTokens.length >>> 1);
            const result = new Uint32Array(myTokens.length + otherTokens.length);
            result.set(myTokens, 0);
            let dest = myTokens.length;
            const delta = myTokens[myTokens.length - 2];
            for (let i = 0; i < otherTokensCount; i++) {
                result[dest++] = otherTokens[(i << 1)] + delta;
                result[dest++] = otherTokens[(i << 1) + 1];
            }
            return result.buffer;
        }
        static insert(lineTokens, chIndex, textLength) {
            if (lineTokens === null || lineTokens === exports.$Ku) {
                // nothing to do
                return lineTokens;
            }
            const tokens = $Mu(lineTokens);
            const tokensCount = (tokens.length >>> 1);
            let fromTokenIndex = lineTokens_1.$Iu.findIndexInTokensArray(tokens, chIndex);
            if (fromTokenIndex > 0) {
                const fromTokenStartOffset = tokens[(fromTokenIndex - 1) << 1];
                if (fromTokenStartOffset === chIndex) {
                    fromTokenIndex--;
                }
            }
            for (let tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) {
                tokens[tokenIndex << 1] += textLength;
            }
            return lineTokens;
        }
    }
    exports.$Lu = $Lu;
    function $Mu(arr) {
        if (arr instanceof Uint32Array) {
            return arr;
        }
        else {
            return new Uint32Array(arr);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/























define(__m[31/*vs/editor/common/tokens/contiguousMultilineTokens*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/arrays*/,14/*vs/base/common/buffer*/,46/*vs/editor/common/core/position*/,15/*vs/editor/common/core/eolCounter*/,30/*vs/editor/common/tokens/contiguousTokensEditing*/,16/*vs/editor/common/core/lineRange*/]), function (require, exports, arrays, buffer_1, position_1, eolCounter_1, contiguousTokensEditing_1, lineRange_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$Nu = void 0;
    arrays = __importStar(arrays);
    /**
     * Represents contiguous tokens over a contiguous range of lines.
     */
    class $Nu {
        static deserialize(buff, offset, result) {
            const view32 = new Uint32Array(buff.buffer);
            const startLineNumber = (0, buffer_1.$We)(buff, offset);
            offset += 4;
            const count = (0, buffer_1.$We)(buff, offset);
            offset += 4;
            const tokens = [];
            for (let i = 0; i < count; i++) {
                const byteCount = (0, buffer_1.$We)(buff, offset);
                offset += 4;
                tokens.push(view32.subarray(offset / 4, offset / 4 + byteCount / 4));
                offset += byteCount;
            }
            result.push(new $Nu(startLineNumber, tokens));
            return offset;
        }
        /**
         * (Inclusive) start line number for these tokens.
         */
        get startLineNumber() {
            return this.a;
        }
        /**
         * (Inclusive) end line number for these tokens.
         */
        get endLineNumber() {
            return this.a + this.b.length - 1;
        }
        constructor(startLineNumber, tokens) {
            this.a = startLineNumber;
            this.b = tokens;
        }
        getLineRange() {
            return new lineRange_1.$6t(this.a, this.a + this.b.length);
        }
        /**
         * @see {@link b}
         */
        getLineTokens(lineNumber) {
            return this.b[lineNumber - this.a];
        }
        appendLineTokens(lineTokens) {
            this.b.push(lineTokens);
        }
        serializeSize() {
            let result = 0;
            result += 4; // 4 bytes for the start line number
            result += 4; // 4 bytes for the line count
            for (let i = 0; i < this.b.length; i++) {
                const lineTokens = this.b[i];
                if (!(lineTokens instanceof Uint32Array)) {
                    throw new Error(`Not supported!`);
                }
                result += 4; // 4 bytes for the byte count
                result += lineTokens.byteLength;
            }
            return result;
        }
        serialize(destination, offset) {
            (0, buffer_1.$Xe)(destination, this.a, offset);
            offset += 4;
            (0, buffer_1.$Xe)(destination, this.b.length, offset);
            offset += 4;
            for (let i = 0; i < this.b.length; i++) {
                const lineTokens = this.b[i];
                if (!(lineTokens instanceof Uint32Array)) {
                    throw new Error(`Not supported!`);
                }
                (0, buffer_1.$Xe)(destination, lineTokens.byteLength, offset);
                offset += 4;
                destination.set(new Uint8Array(lineTokens.buffer), offset);
                offset += lineTokens.byteLength;
            }
            return offset;
        }
        applyEdit(range, text) {
            const [eolCount, firstLineLength] = (0, eolCounter_1.$Hu)(text);
            this.c(range);
            this.d(new position_1.$Vt(range.startLineNumber, range.startColumn), eolCount, firstLineLength);
        }
        c(range) {
            if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
                // Nothing to delete
                return;
            }
            const firstLineIndex = range.startLineNumber - this.a;
            const lastLineIndex = range.endLineNumber - this.a;
            if (lastLineIndex < 0) {
                // this deletion occurs entirely before this block, so we only need to adjust line numbers
                const deletedLinesCount = lastLineIndex - firstLineIndex;
                this.a -= deletedLinesCount;
                return;
            }
            if (firstLineIndex >= this.b.length) {
                // this deletion occurs entirely after this block, so there is nothing to do
                return;
            }
            if (firstLineIndex < 0 && lastLineIndex >= this.b.length) {
                // this deletion completely encompasses this block
                this.a = 0;
                this.b = [];
                return;
            }
            if (firstLineIndex === lastLineIndex) {
                // a delete on a single line
                this.b[firstLineIndex] = contiguousTokensEditing_1.$Lu.delete(this.b[firstLineIndex], range.startColumn - 1, range.endColumn - 1);
                return;
            }
            if (firstLineIndex >= 0) {
                // The first line survives
                this.b[firstLineIndex] = contiguousTokensEditing_1.$Lu.deleteEnding(this.b[firstLineIndex], range.startColumn - 1);
                if (lastLineIndex < this.b.length) {
                    // The last line survives
                    const lastLineTokens = contiguousTokensEditing_1.$Lu.deleteBeginning(this.b[lastLineIndex], range.endColumn - 1);
                    // Take remaining text on last line and append it to remaining text on first line
                    this.b[firstLineIndex] = contiguousTokensEditing_1.$Lu.append(this.b[firstLineIndex], lastLineTokens);
                    // Delete middle lines
                    this.b.splice(firstLineIndex + 1, lastLineIndex - firstLineIndex);
                }
                else {
                    // The last line does not survive
                    // Take remaining text on last line and append it to remaining text on first line
                    this.b[firstLineIndex] = contiguousTokensEditing_1.$Lu.append(this.b[firstLineIndex], null);
                    // Delete lines
                    this.b = this.b.slice(0, firstLineIndex + 1);
                }
            }
            else {
                // The first line does not survive
                const deletedBefore = -firstLineIndex;
                this.a -= deletedBefore;
                // Remove beginning from last line
                this.b[lastLineIndex] = contiguousTokensEditing_1.$Lu.deleteBeginning(this.b[lastLineIndex], range.endColumn - 1);
                // Delete lines
                this.b = this.b.slice(lastLineIndex);
            }
        }
        d(position, eolCount, firstLineLength) {
            if (eolCount === 0 && firstLineLength === 0) {
                // Nothing to insert
                return;
            }
            const lineIndex = position.lineNumber - this.a;
            if (lineIndex < 0) {
                // this insertion occurs before this block, so we only need to adjust line numbers
                this.a += eolCount;
                return;
            }
            if (lineIndex >= this.b.length) {
                // this insertion occurs after this block, so there is nothing to do
                return;
            }
            if (eolCount === 0) {
                // Inserting text on one line
                this.b[lineIndex] = contiguousTokensEditing_1.$Lu.insert(this.b[lineIndex], position.column - 1, firstLineLength);
                return;
            }
            this.b[lineIndex] = contiguousTokensEditing_1.$Lu.deleteEnding(this.b[lineIndex], position.column - 1);
            this.b[lineIndex] = contiguousTokensEditing_1.$Lu.insert(this.b[lineIndex], position.column - 1, firstLineLength);
            this.e(position.lineNumber, eolCount);
        }
        e(insertIndex, insertCount) {
            if (insertCount === 0) {
                return;
            }
            const lineTokens = [];
            for (let i = 0; i < insertCount; i++) {
                lineTokens[i] = null;
            }
            this.b = arrays.$Zb(this.b, insertIndex, lineTokens);
        }
    }
    exports.$Nu = $Nu;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[17/*vs/editor/common/tokens/contiguousMultilineTokensBuilder*/], __M([0/*require*/,1/*exports*/,14/*vs/base/common/buffer*/,31/*vs/editor/common/tokens/contiguousMultilineTokens*/]), function (require, exports, buffer_1, contiguousMultilineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$OD = void 0;
    class $OD {
        static deserialize(buff) {
            let offset = 0;
            const count = (0, buffer_1.$We)(buff, offset);
            offset += 4;
            const result = [];
            for (let i = 0; i < count; i++) {
                offset = contiguousMultilineTokens_1.$Nu.deserialize(buff, offset, result);
            }
            return result;
        }
        constructor() {
            this.a = [];
        }
        add(lineNumber, lineTokens) {
            if (this.a.length > 0) {
                const last = this.a[this.a.length - 1];
                if (last.endLineNumber + 1 === lineNumber) {
                    // append
                    last.appendLineTokens(lineTokens);
                    return;
                }
            }
            this.a.push(new contiguousMultilineTokens_1.$Nu(lineNumber, [lineTokens]));
        }
        finalize() {
            return this.a;
        }
        serialize() {
            const size = this.b();
            const result = new Uint8Array(size);
            this.c(result);
            return result;
        }
        b() {
            let result = 0;
            result += 4; // 4 bytes for the count
            for (let i = 0; i < this.a.length; i++) {
                result += this.a[i].serializeSize();
            }
            return result;
        }
        c(destination) {
            let offset = 0;
            (0, buffer_1.$Xe)(destination, this.a.length, offset);
            offset += 4;
            for (let i = 0; i < this.a.length; i++) {
                offset = this.a[i].serialize(destination, offset);
            }
        }
    }
    exports.$OD = $OD;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/























define(__m[18/*vs/amdX*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/amd*/,47/*vs/base/common/network*/,19/*vs/base/common/platform*/,48/*vs/base/common/types*/,32/*vs/base/common/uri*/]), function (require, exports, amd_1, network_1, platform, types_1, uri_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$zq = $zq;
    exports.$Aq = $Aq;
    platform = __importStar(platform);
    class DefineCall {
        constructor(id, dependencies, callback) {
            this.id = id;
            this.dependencies = dependencies;
            this.callback = callback;
        }
    }
    class AMDModuleImporter {
        static { this.INSTANCE = new AMDModuleImporter(); }
        constructor() {
            this.a = (typeof self === 'object' && self.constructor && self.constructor.name === 'DedicatedWorkerGlobalScope');
            this.b = typeof document === 'object';
            this.c = [];
            this.d = false;
        }
        g() {
            if (this.d) {
                return;
            }
            this.d = true;
            globalThis.define = (id, dependencies, callback) => {
                if (typeof id !== 'string') {
                    callback = dependencies;
                    dependencies = id;
                    id = null;
                }
                if (typeof dependencies !== 'object' || !Array.isArray(dependencies)) {
                    callback = dependencies;
                    dependencies = null;
                }
                // if (!dependencies) {
                // 	dependencies = ['require', 'exports', 'module'];
                // }
                this.c.push(new DefineCall(id, dependencies, callback));
            };
            globalThis.define.amd = true;
            if (this.b) {
                // eslint-disable-next-line no-restricted-globals
                this.f = globalThis._VSCODE_WEB_PACKAGE_TTP ?? window.trustedTypes?.createPolicy('amdLoader', {
                    createScriptURL(value) {
                        // eslint-disable-next-line no-restricted-globals
                        if (value.startsWith(window.location.origin)) {
                            return value;
                        }
                        if (value.startsWith(`${network_1.Schemas.vscodeFileResource}://${network_1.$4g}`)) {
                            return value;
                        }
                        throw new Error(`[trusted_script_src] Invalid script url: ${value}`);
                    }
                });
            }
            else if (this.a) {
                this.f = globalThis._VSCODE_WEB_PACKAGE_TTP ?? globalThis.trustedTypes?.createPolicy('amdLoader', {
                    createScriptURL(value) {
                        return value;
                    }
                });
            }
        }
        async load(scriptSrc) {
            this.g();
            const defineCall = await (this.a ? this.i(scriptSrc) : this.b ? this.h(scriptSrc) : this.j(scriptSrc));
            if (!defineCall) {
                // throw new Error(`Did not receive a define call from script ${scriptSrc}`);
                console.warn(`Did not receive a define call from script ${scriptSrc}`);
                return undefined;
            }
            // TODO require, module
            const exports = {};
            const dependencyObjs = [];
            const dependencyModules = [];
            if (Array.isArray(defineCall.dependencies)) {
                for (const mod of defineCall.dependencies) {
                    if (mod === 'exports') {
                        dependencyObjs.push(exports);
                    }
                    else {
                        dependencyModules.push(mod);
                    }
                }
            }
            if (dependencyModules.length > 0) {
                throw new Error(`Cannot resolve dependencies for script ${scriptSrc}. The dependencies are: ${dependencyModules.join(', ')}`);
            }
            if (typeof defineCall.callback === 'function') {
                return defineCall.callback(...dependencyObjs) ?? exports;
            }
            else {
                return defineCall.callback;
            }
        }
        h(scriptSrc) {
            return new Promise((resolve, reject) => {
                const scriptElement = document.createElement('script');
                scriptElement.setAttribute('async', 'async');
                scriptElement.setAttribute('type', 'text/javascript');
                const unbind = () => {
                    scriptElement.removeEventListener('load', loadEventListener);
                    scriptElement.removeEventListener('error', errorEventListener);
                };
                const loadEventListener = (e) => {
                    unbind();
                    resolve(this.c.pop());
                };
                const errorEventListener = (e) => {
                    unbind();
                    reject(e);
                };
                scriptElement.addEventListener('load', loadEventListener);
                scriptElement.addEventListener('error', errorEventListener);
                if (this.f) {
                    scriptSrc = this.f.createScriptURL(scriptSrc);
                }
                scriptElement.setAttribute('src', scriptSrc);
                // eslint-disable-next-line no-restricted-globals
                window.document.getElementsByTagName('head')[0].appendChild(scriptElement);
            });
        }
        async i(scriptSrc) {
            if (this.f) {
                scriptSrc = this.f.createScriptURL(scriptSrc);
            }
            if (amd_1.$V) {
                await new Promise((resolve_1, reject_1) => { require([scriptSrc], resolve_1, reject_1); }).then(__importStar);
            }
            else {
                importScripts(scriptSrc);
            }
            return this.c.pop();
        }
        async j(scriptSrc) {
            try {
                const fs = globalThis._VSCODE_NODE_MODULES['fs'];
                const vm = globalThis._VSCODE_NODE_MODULES['vm'];
                const module = globalThis._VSCODE_NODE_MODULES['module'];
                const filePath = uri_1.URI.parse(scriptSrc).fsPath;
                const content = fs.readFileSync(filePath).toString();
                const scriptSource = module.wrap(content.replace(/^#!.*/, ''));
                const script = new vm.Script(scriptSource);
                const compileWrapper = script.runInThisContext();
                compileWrapper.apply();
                return this.c.pop();
            }
            catch (error) {
                throw error;
            }
        }
    }
    const cache = new Map();
    /**
     * Utility for importing an AMD node module. This util supports AMD and ESM contexts and should be used while the ESM adoption
     * is on its way.
     *
     * e.g. pass in `vscode-textmate/release/main.js`
     */
    async function $zq(nodeModuleName, pathInsideNodeModule, isBuilt) {
        if (amd_1.$V) {
            if (isBuilt === undefined) {
                const product = globalThis._VSCODE_PRODUCT_JSON;
                isBuilt = Boolean((product ?? globalThis.vscode?.context?.configuration()?.product)?.commit);
            }
            const nodeModulePath = pathInsideNodeModule ? `${nodeModuleName}/${pathInsideNodeModule}` : nodeModuleName;
            if (cache.has(nodeModulePath)) {
                return cache.get(nodeModulePath);
            }
            let scriptSrc;
            if (/^\w[\w\d+.-]*:\/\//.test(nodeModulePath)) {
                // looks like a URL
                // bit of a special case for: src/vs/workbench/services/languageDetection/browser/languageDetectionSimpleWorker.ts
                scriptSrc = nodeModulePath;
            }
            else {
                const useASAR = (amd_1.$W && isBuilt && !platform.$r);
                const actualNodeModulesPath = (useASAR ? network_1.$2g : network_1.$1g);
                const resourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
                scriptSrc = network_1.$5g.asBrowserUri(resourcePath).toString(true);
            }
            const result = AMDModuleImporter.INSTANCE.load(scriptSrc);
            cache.set(nodeModulePath, result);
            return result;
        }
        else {
            return await new Promise((resolve_2, reject_2) => { require([nodeModuleName], resolve_2, reject_2); }).then(__importStar);
        }
    }
    function $Aq(nodeModuleName, pathInsideNodeModule) {
        (0, types_1.$tg)(amd_1.$V);
        const product = globalThis._VSCODE_PRODUCT_JSON;
        const isBuilt = Boolean((product ?? globalThis.vscode?.context?.configuration()?.product)?.commit);
        const useASAR = (amd_1.$W && isBuilt && !platform.$r);
        const nodeModulePath = `${nodeModuleName}/${pathInsideNodeModule}`;
        const actualNodeModulesPath = (useASAR ? network_1.$2g : network_1.$1g);
        const resourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
        return network_1.$5g.asBrowserUri(resourcePath).toString(true);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[20/*vs/editor/common/languages/nullTokenize*/], __M([0/*require*/,1/*exports*/,33/*vs/editor/common/languages*/,11/*vs/editor/common/encodedTokenAttributes*/]), function (require, exports, languages_1, encodedTokenAttributes_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$KD = void 0;
    exports.$LD = $LD;
    exports.$MD = $MD;
    exports.$KD = new class {
        clone() {
            return this;
        }
        equals(other) {
            return (this === other);
        }
    };
    function $LD(languageId, state) {
        return new languages_1.$Qu([new languages_1.$Pu(0, '', languageId)], state);
    }
    function $MD(languageId, state) {
        const tokens = new Uint32Array(2);
        tokens[0] = 0;
        tokens[1] = ((languageId << encodedTokenAttributes_1.MetadataConsts.LANGUAGEID_OFFSET)
            | (encodedTokenAttributes_1.StandardTokenType.Other << encodedTokenAttributes_1.MetadataConsts.TOKEN_TYPE_OFFSET)
            | (encodedTokenAttributes_1.FontStyle.None << encodedTokenAttributes_1.MetadataConsts.FONT_STYLE_OFFSET)
            | (encodedTokenAttributes_1.ColorId.DefaultForeground << encodedTokenAttributes_1.MetadataConsts.FOREGROUND_OFFSET)
            | (encodedTokenAttributes_1.ColorId.DefaultBackground << encodedTokenAttributes_1.MetadataConsts.BACKGROUND_OFFSET)) >>> 0;
        return new languages_1.$Ru(tokens, state === null ? exports.$KD : state);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[34/*vs/editor/common/model/textModelTokens*/], __M([0/*require*/,1/*exports*/,35/*vs/base/common/async*/,9/*vs/base/common/errors*/,19/*vs/base/common/platform*/,36/*vs/base/common/stopwatch*/,15/*vs/editor/common/core/eolCounter*/,16/*vs/editor/common/core/lineRange*/,49/*vs/editor/common/core/offsetRange*/,11/*vs/editor/common/encodedTokenAttributes*/,20/*vs/editor/common/languages/nullTokenize*/,29/*vs/editor/common/model/fixedArray*/,17/*vs/editor/common/tokens/contiguousMultilineTokensBuilder*/,10/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, async_1, errors_1, platform_1, stopwatch_1, eolCounter_1, lineRange_1, offsetRange_1, encodedTokenAttributes_1, nullTokenize_1, fixedArray_1, contiguousMultilineTokensBuilder_1, lineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$UD = exports.$TD = exports.$SD = exports.$RD = exports.$QD = exports.$PD = void 0;
    var Constants;
    (function (Constants) {
        Constants[Constants["CHEAP_TOKENIZATION_LENGTH_LIMIT"] = 2048] = "CHEAP_TOKENIZATION_LENGTH_LIMIT";
    })(Constants || (Constants = {}));
    class $PD {
        constructor(lineCount, tokenizationSupport) {
            this.tokenizationSupport = tokenizationSupport;
            this.a = this.tokenizationSupport.getInitialState();
            this.store = new $RD(lineCount);
        }
        getStartState(lineNumber) {
            return this.store.getStartState(lineNumber, this.a);
        }
        getFirstInvalidLine() {
            return this.store.getFirstInvalidLine(this.a);
        }
    }
    exports.$PD = $PD;
    class $QD extends $PD {
        constructor(lineCount, tokenizationSupport, _textModel, _languageIdCodec) {
            super(lineCount, tokenizationSupport);
            this._textModel = _textModel;
            this._languageIdCodec = _languageIdCodec;
        }
        updateTokensUntilLine(builder, lineNumber) {
            const languageId = this._textModel.getLanguageId();
            while (true) {
                const lineToTokenize = this.getFirstInvalidLine();
                if (!lineToTokenize || lineToTokenize.lineNumber > lineNumber) {
                    break;
                }
                const text = this._textModel.getLineContent(lineToTokenize.lineNumber);
                const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text, true, lineToTokenize.startState);
                builder.add(lineToTokenize.lineNumber, r.tokens);
                this.store.setEndState(lineToTokenize.lineNumber, r.endState);
            }
        }
        /** assumes state is up to date */
        getTokenTypeIfInsertingCharacter(position, character) {
            // TODO@hediet: use tokenizeLineWithEdit
            const lineStartState = this.getStartState(position.lineNumber);
            if (!lineStartState) {
                return encodedTokenAttributes_1.StandardTokenType.Other;
            }
            const languageId = this._textModel.getLanguageId();
            const lineContent = this._textModel.getLineContent(position.lineNumber);
            // Create the text as if `character` was inserted
            const text = (lineContent.substring(0, position.column - 1)
                + character
                + lineContent.substring(position.column - 1));
            const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text, true, lineStartState);
            const lineTokens = new lineTokens_1.$Iu(r.tokens, text, this._languageIdCodec);
            if (lineTokens.getCount() === 0) {
                return encodedTokenAttributes_1.StandardTokenType.Other;
            }
            const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
            return lineTokens.getStandardTokenType(tokenIndex);
        }
        /** assumes state is up to date */
        tokenizeLineWithEdit(position, length, newText) {
            const lineNumber = position.lineNumber;
            const column = position.column;
            const lineStartState = this.getStartState(lineNumber);
            if (!lineStartState) {
                return null;
            }
            const curLineContent = this._textModel.getLineContent(lineNumber);
            const newLineContent = curLineContent.substring(0, column - 1)
                + newText + curLineContent.substring(column - 1 + length);
            const languageId = this._textModel.getLanguageIdAtPosition(lineNumber, 0);
            const result = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, newLineContent, true, lineStartState);
            const lineTokens = new lineTokens_1.$Iu(result.tokens, newLineContent, this._languageIdCodec);
            return lineTokens;
        }
        hasAccurateTokensForLine(lineNumber) {
            const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
            return (lineNumber < firstInvalidLineNumber);
        }
        isCheapToTokenize(lineNumber) {
            const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
            if (lineNumber < firstInvalidLineNumber) {
                return true;
            }
            if (lineNumber === firstInvalidLineNumber
                && this._textModel.getLineLength(lineNumber) < Constants.CHEAP_TOKENIZATION_LENGTH_LIMIT) {
                return true;
            }
            return false;
        }
        /**
         * The result is not cached.
         */
        tokenizeHeuristically(builder, startLineNumber, endLineNumber) {
            if (endLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
                // nothing to do
                return { heuristicTokens: false };
            }
            if (startLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
                // tokenization has reached the viewport start...
                this.updateTokensUntilLine(builder, endLineNumber);
                return { heuristicTokens: false };
            }
            let state = this.b(startLineNumber);
            const languageId = this._textModel.getLanguageId();
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const text = this._textModel.getLineContent(lineNumber);
                const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text, true, state);
                builder.add(lineNumber, r.tokens);
                state = r.endState;
            }
            return { heuristicTokens: true };
        }
        b(lineNumber) {
            let nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(lineNumber);
            const likelyRelevantLines = [];
            let initialState = null;
            for (let i = lineNumber - 1; nonWhitespaceColumn > 1 && i >= 1; i--) {
                const newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i);
                // Ignore lines full of whitespace
                if (newNonWhitespaceIndex === 0) {
                    continue;
                }
                if (newNonWhitespaceIndex < nonWhitespaceColumn) {
                    likelyRelevantLines.push(this._textModel.getLineContent(i));
                    nonWhitespaceColumn = newNonWhitespaceIndex;
                    initialState = this.getStartState(i);
                    if (initialState) {
                        break;
                    }
                }
            }
            if (!initialState) {
                initialState = this.tokenizationSupport.getInitialState();
            }
            likelyRelevantLines.reverse();
            const languageId = this._textModel.getLanguageId();
            let state = initialState;
            for (const line of likelyRelevantLines) {
                const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, line, false, state);
                state = r.endState;
            }
            return state;
        }
    }
    exports.$QD = $QD;
    /**
     * **Invariant:**
     * If the text model is retokenized from line 1 to {@link getFirstInvalidEndStateLineNumber}() - 1,
     * then the recomputed end state for line l will be equal to {@link getEndState}(l).
     */
    class $RD {
        constructor(d) {
            this.d = d;
            this.a = new $SD();
            this.b = new $TD();
            this.b.addRange(new offsetRange_1.$4t(1, d + 1));
        }
        getEndState(lineNumber) {
            return this.a.getEndState(lineNumber);
        }
        /**
         * @returns if the end state has changed.
         */
        setEndState(lineNumber, state) {
            if (!state) {
                throw new errors_1.$gb('Cannot set null/undefined state');
            }
            this.b.delete(lineNumber);
            const r = this.a.setEndState(lineNumber, state);
            if (r && lineNumber < this.d) {
                // because the state changed, we cannot trust the next state anymore and have to invalidate it.
                this.b.addRange(new offsetRange_1.$4t(lineNumber + 1, lineNumber + 2));
            }
            return r;
        }
        acceptChange(range, newLineCount) {
            this.d += newLineCount - range.length;
            this.a.acceptChange(range, newLineCount);
            this.b.addRangeAndResize(new offsetRange_1.$4t(range.startLineNumber, range.endLineNumberExclusive), newLineCount);
        }
        acceptChanges(changes) {
            for (const c of changes) {
                const [eolCount] = (0, eolCounter_1.$Hu)(c.text);
                this.acceptChange(new lineRange_1.$6t(c.range.startLineNumber, c.range.endLineNumber + 1), eolCount + 1);
            }
        }
        invalidateEndStateRange(range) {
            this.b.addRange(new offsetRange_1.$4t(range.startLineNumber, range.endLineNumberExclusive));
        }
        getFirstInvalidEndStateLineNumber() { return this.b.min; }
        getFirstInvalidEndStateLineNumberOrMax() {
            return this.getFirstInvalidEndStateLineNumber() || Number.MAX_SAFE_INTEGER;
        }
        allStatesValid() { return this.b.min === null; }
        getStartState(lineNumber, initialState) {
            if (lineNumber === 1) {
                return initialState;
            }
            return this.getEndState(lineNumber - 1);
        }
        getFirstInvalidLine(initialState) {
            const lineNumber = this.getFirstInvalidEndStateLineNumber();
            if (lineNumber === null) {
                return null;
            }
            const startState = this.getStartState(lineNumber, initialState);
            if (!startState) {
                throw new errors_1.$gb('Start state must be defined');
            }
            return { lineNumber, startState };
        }
    }
    exports.$RD = $RD;
    class $SD {
        constructor() {
            this.a = new fixedArray_1.$ND(null);
        }
        getEndState(lineNumber) {
            return this.a.get(lineNumber);
        }
        setEndState(lineNumber, state) {
            const oldState = this.a.get(lineNumber);
            if (oldState && oldState.equals(state)) {
                return false;
            }
            this.a.set(lineNumber, state);
            return true;
        }
        acceptChange(range, newLineCount) {
            let length = range.length;
            if (newLineCount > 0 && length > 0) {
                // Keep the last state, even though it is unrelated.
                // But if the new state happens to agree with this last state, then we know we can stop tokenizing.
                length--;
                newLineCount--;
            }
            this.a.replace(range.startLineNumber, length, newLineCount);
        }
        acceptChanges(changes) {
            for (const c of changes) {
                const [eolCount] = (0, eolCounter_1.$Hu)(c.text);
                this.acceptChange(new lineRange_1.$6t(c.range.startLineNumber, c.range.endLineNumber + 1), eolCount + 1);
            }
        }
    }
    exports.$SD = $SD;
    class $TD {
        constructor() {
            this.a = [];
        }
        getRanges() {
            return this.a;
        }
        get min() {
            if (this.a.length === 0) {
                return null;
            }
            return this.a[0].start;
        }
        removeMin() {
            if (this.a.length === 0) {
                return null;
            }
            const range = this.a[0];
            if (range.start + 1 === range.endExclusive) {
                this.a.shift();
            }
            else {
                this.a[0] = new offsetRange_1.$4t(range.start + 1, range.endExclusive);
            }
            return range.start;
        }
        delete(value) {
            const idx = this.a.findIndex(r => r.contains(value));
            if (idx !== -1) {
                const range = this.a[idx];
                if (range.start === value) {
                    if (range.endExclusive === value + 1) {
                        this.a.splice(idx, 1);
                    }
                    else {
                        this.a[idx] = new offsetRange_1.$4t(value + 1, range.endExclusive);
                    }
                }
                else {
                    if (range.endExclusive === value + 1) {
                        this.a[idx] = new offsetRange_1.$4t(range.start, value);
                    }
                    else {
                        this.a.splice(idx, 1, new offsetRange_1.$4t(range.start, value), new offsetRange_1.$4t(value + 1, range.endExclusive));
                    }
                }
            }
        }
        addRange(range) {
            offsetRange_1.$4t.addRange(range, this.a);
        }
        addRangeAndResize(range, newLength) {
            let idxFirstMightBeIntersecting = 0;
            while (!(idxFirstMightBeIntersecting >= this.a.length || range.start <= this.a[idxFirstMightBeIntersecting].endExclusive)) {
                idxFirstMightBeIntersecting++;
            }
            let idxFirstIsAfter = idxFirstMightBeIntersecting;
            while (!(idxFirstIsAfter >= this.a.length || range.endExclusive < this.a[idxFirstIsAfter].start)) {
                idxFirstIsAfter++;
            }
            const delta = newLength - range.length;
            for (let i = idxFirstIsAfter; i < this.a.length; i++) {
                this.a[i] = this.a[i].delta(delta);
            }
            if (idxFirstMightBeIntersecting === idxFirstIsAfter) {
                const newRange = new offsetRange_1.$4t(range.start, range.start + newLength);
                if (!newRange.isEmpty) {
                    this.a.splice(idxFirstMightBeIntersecting, 0, newRange);
                }
            }
            else {
                const start = Math.min(range.start, this.a[idxFirstMightBeIntersecting].start);
                const endEx = Math.max(range.endExclusive, this.a[idxFirstIsAfter - 1].endExclusive);
                const newRange = new offsetRange_1.$4t(start, endEx + delta);
                if (!newRange.isEmpty) {
                    this.a.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting, newRange);
                }
                else {
                    this.a.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting);
                }
            }
        }
        toString() {
            return this.a.map(r => r.toString()).join(' + ');
        }
    }
    exports.$TD = $TD;
    function safeTokenize(languageIdCodec, languageId, tokenizationSupport, text, hasEOL, state) {
        let r = null;
        if (tokenizationSupport) {
            try {
                r = tokenizationSupport.tokenizeEncoded(text, hasEOL, state.clone());
            }
            catch (e) {
                (0, errors_1.$4)(e);
            }
        }
        if (!r) {
            r = (0, nullTokenize_1.$MD)(languageIdCodec.encodeLanguageId(languageId), state);
        }
        lineTokens_1.$Iu.convertToEndOffset(r.tokens, text.length);
        return r;
    }
    class $UD {
        constructor(b, d) {
            this.b = b;
            this.d = d;
            this.a = false;
            this.f = false;
        }
        dispose() {
            this.a = true;
        }
        handleChanges() {
            this.g();
        }
        g() {
            if (this.f || !this.b._textModel.isAttachedToEditor() || !this.k()) {
                return;
            }
            this.f = true;
            (0, async_1.$1h)((deadline) => {
                this.f = false;
                this.h(deadline);
            });
        }
        /**
         * Tokenize until the deadline occurs, but try to yield every 1-2ms.
         */
        h(deadline) {
            // Read the time remaining from the `deadline` immediately because it is unclear
            // if the `deadline` object will be valid after execution leaves this function.
            const endTime = Date.now() + deadline.timeRemaining();
            const execute = () => {
                if (this.a || !this.b._textModel.isAttachedToEditor() || !this.k()) {
                    // disposed in the meantime or detached or finished
                    return;
                }
                this.j();
                if (Date.now() < endTime) {
                    // There is still time before reaching the deadline, so yield to the browser and then
                    // continue execution
                    (0, platform_1.$E)(execute);
                }
                else {
                    // The deadline has been reached, so schedule a new idle callback if necessary
                    this.g();
                }
            };
            execute();
        }
        /**
         * Tokenize for at least 1ms.
         */
        j() {
            const lineCount = this.b._textModel.getLineCount();
            const builder = new contiguousMultilineTokensBuilder_1.$OD();
            const sw = stopwatch_1.$ke.create(false);
            do {
                if (sw.elapsed() > 1) {
                    // the comparison is intentionally > 1 and not >= 1 to ensure that
                    // a full millisecond has elapsed, given how microseconds are rounded
                    // to milliseconds
                    break;
                }
                const tokenizedLineNumber = this.l(builder);
                if (tokenizedLineNumber >= lineCount) {
                    break;
                }
            } while (this.k());
            this.d.setTokens(builder.finalize());
            this.checkFinished();
        }
        k() {
            if (!this.b) {
                return false;
            }
            return !this.b.store.allStatesValid();
        }
        l(builder) {
            const firstInvalidLine = this.b?.getFirstInvalidLine();
            if (!firstInvalidLine) {
                return this.b._textModel.getLineCount() + 1;
            }
            this.b.updateTokensUntilLine(builder, firstInvalidLine.lineNumber);
            return firstInvalidLine.lineNumber;
        }
        checkFinished() {
            if (this.a) {
                return;
            }
            if (this.b.store.allStatesValid()) {
                this.d.backgroundTokenizationFinished();
            }
        }
        requestTokens(startLineNumber, endLineNumberExclusive) {
            this.b.store.invalidateEndStateRange(new lineRange_1.$6t(startLineNumber, endLineNumberExclusive));
        }
    }
    exports.$UD = $UD;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[37/*vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateWorkerHost*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$GPb = void 0;
    class $GPb {
        static { this.CHANNEL_NAME = 'textMateWorkerHost'; }
        static getChannel(workerServer) {
            return workerServer.getChannel($GPb.CHANNEL_NAME);
        }
        static setChannel(workerClient, obj) {
            workerClient.setChannel($GPb.CHANNEL_NAME, obj);
        }
    }
    exports.$GPb = $GPb;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[38/*vs/workbench/services/textMate/browser/tokenizationSupport/textMateTokenizationSupport*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,36/*vs/base/common/stopwatch*/,11/*vs/editor/common/encodedTokenAttributes*/,33/*vs/editor/common/languages*/]), function (require, exports, event_1, lifecycle_1, stopwatch_1, encodedTokenAttributes_1, languages_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$APb = void 0;
    class $APb extends lifecycle_1.$Zc {
        constructor(c, f, g, h, j, m, n) {
            super();
            this.c = c;
            this.f = f;
            this.g = g;
            this.h = h;
            this.j = j;
            this.m = m;
            this.n = n;
            this.a = [];
            this.b = this.B(new event_1.$qe());
            this.onDidEncounterLanguage = this.b.event;
        }
        get backgroundTokenizerShouldOnlyVerifyTokens() {
            return this.j();
        }
        getInitialState() {
            return this.f;
        }
        tokenize(line, hasEOL, state) {
            throw new Error('Not supported!');
        }
        createBackgroundTokenizer(textModel, store) {
            if (this.h) {
                return this.h(textModel, store);
            }
            return undefined;
        }
        tokenizeEncoded(line, hasEOL, state) {
            const isRandomSample = Math.random() * 10_000 < 1;
            const shouldMeasure = this.n || isRandomSample;
            const sw = shouldMeasure ? new stopwatch_1.$ke(true) : undefined;
            const textMateResult = this.c.tokenizeLine2(line, state, 500);
            if (shouldMeasure) {
                const timeMS = sw.elapsed();
                if (isRandomSample || timeMS > 32) {
                    this.m(timeMS, line.length, isRandomSample);
                }
            }
            if (textMateResult.stoppedEarly) {
                console.warn(`Time limit reached when tokenizing line: ${line.substring(0, 100)}`);
                // return the state at the beginning of the line
                return new languages_1.$Ru(textMateResult.tokens, state);
            }
            if (this.g) {
                const seenLanguages = this.a;
                const tokens = textMateResult.tokens;
                // Must check if any of the embedded languages was hit
                for (let i = 0, len = (tokens.length >>> 1); i < len; i++) {
                    const metadata = tokens[(i << 1) + 1];
                    const languageId = encodedTokenAttributes_1.$Du.getLanguageId(metadata);
                    if (!seenLanguages[languageId]) {
                        seenLanguages[languageId] = true;
                        this.b.fire(languageId);
                    }
                }
            }
            let endState;
            // try to save an object if possible
            if (state.equals(textMateResult.ruleStack)) {
                endState = state;
            }
            else {
                endState = textMateResult.ruleStack;
            }
            return new languages_1.$Ru(textMateResult.tokens, endState);
        }
    }
    exports.$APb = $APb;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[39/*vs/workbench/services/textMate/browser/tokenizationSupport/tokenizationSupportWithLineLimit*/], __M([0/*require*/,1/*exports*/,20/*vs/editor/common/languages/nullTokenize*/,2/*vs/base/common/lifecycle*/,13/*vs/base/common/observable*/]), function (require, exports, nullTokenize_1, lifecycle_1, observable_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$BPb = void 0;
    class $BPb extends lifecycle_1.$Zc {
        get backgroundTokenizerShouldOnlyVerifyTokens() {
            return this.b.backgroundTokenizerShouldOnlyVerifyTokens;
        }
        constructor(a, b, disposable, c) {
            super();
            this.a = a;
            this.b = b;
            this.c = c;
            this.B((0, observable_1.keepObserved)(this.c));
            this.B(disposable);
        }
        getInitialState() {
            return this.b.getInitialState();
        }
        tokenize(line, hasEOL, state) {
            throw new Error('Not supported!');
        }
        tokenizeEncoded(line, hasEOL, state) {
            // Do not attempt to tokenize if a line is too long
            if (line.length >= this.c.get()) {
                return (0, nullTokenize_1.$MD)(this.a, state);
            }
            return this.b.tokenizeEncoded(line, hasEOL, state);
        }
        createBackgroundTokenizer(textModel, store) {
            if (this.b.createBackgroundTokenizer) {
                return this.b.createBackgroundTokenizer(textModel, store);
            }
            else {
                return undefined;
            }
        }
    }
    exports.$BPb = $BPb;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[40/*vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateWorkerTokenizer*/], __M([0/*require*/,1/*exports*/,18/*vs/amdX*/,35/*vs/base/common/async*/,13/*vs/base/common/observable*/,19/*vs/base/common/platform*/,16/*vs/editor/common/core/lineRange*/,50/*vs/editor/common/model/mirrorTextModel*/,34/*vs/editor/common/model/textModelTokens*/,17/*vs/editor/common/tokens/contiguousMultilineTokensBuilder*/,10/*vs/editor/common/tokens/lineTokens*/,38/*vs/workbench/services/textMate/browser/tokenizationSupport/textMateTokenizationSupport*/,39/*vs/workbench/services/textMate/browser/tokenizationSupport/tokenizationSupportWithLineLimit*/,2/*vs/base/common/lifecycle*/]), function (require, exports, amdX_1, async_1, observable_1, platform_1, lineRange_1, mirrorTextModel_1, textModelTokens_1, contiguousMultilineTokensBuilder_1, lineTokens_1, textMateTokenizationSupport_1, tokenizationSupportWithLineLimit_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$FPb = void 0;
    class $FPb extends mirrorTextModel_1.$yw {
        constructor(uri, lines, eol, versionId, s, t, u, maxTokenizationLineLength) {
            super(uri, lines, eol, versionId);
            this.s = s;
            this.t = t;
            this.u = u;
            this.m = null;
            this.n = false;
            this.o = (0, observable_1.observableValue)(this, -1);
            this.q = new async_1.$Wh(() => this.w(), 10);
            this.o.set(maxTokenizationLineLength, undefined);
            this.v();
        }
        dispose() {
            this.n = true;
            super.dispose();
        }
        onLanguageId(languageId, encodedLanguageId) {
            this.t = languageId;
            this.u = encodedLanguageId;
            this.v();
        }
        onEvents(e) {
            super.onEvents(e);
            this.m?.store.acceptChanges(e.changes);
            this.q.schedule();
        }
        acceptMaxTokenizationLineLength(maxTokenizationLineLength) {
            this.o.set(maxTokenizationLineLength, undefined);
        }
        retokenize(startLineNumber, endLineNumberExclusive) {
            if (this.m) {
                this.m.store.invalidateEndStateRange(new lineRange_1.$6t(startLineNumber, endLineNumberExclusive));
                this.q.schedule();
            }
        }
        async v() {
            this.m = null;
            const languageId = this.t;
            const encodedLanguageId = this.u;
            const r = await this.s.getOrCreateGrammar(languageId, encodedLanguageId);
            if (this.n || languageId !== this.t || encodedLanguageId !== this.u || !r) {
                return;
            }
            if (r.grammar) {
                const tokenizationSupport = new tokenizationSupportWithLineLimit_1.$BPb(this.u, new textMateTokenizationSupport_1.$APb(r.grammar, r.initialState, false, undefined, () => false, (timeMs, lineLength, isRandomSample) => {
                    this.s.reportTokenizationTime(timeMs, languageId, r.sourceExtensionId, lineLength, isRandomSample);
                }, false), lifecycle_1.$Zc.None, this.o);
                this.m = new textModelTokens_1.$PD(this.b.length, tokenizationSupport);
            }
            else {
                this.m = null;
            }
            this.w();
        }
        async w() {
            if (this.n || !this.m) {
                return;
            }
            if (!this.p) {
                const { diffStateStacksRefEq } = await (0, amdX_1.$zq)('vscode-textmate', 'release/main.js');
                this.p = diffStateStacksRefEq;
            }
            const startTime = new Date().getTime();
            while (true) {
                let tokenizedLines = 0;
                const tokenBuilder = new contiguousMultilineTokensBuilder_1.$OD();
                const stateDeltaBuilder = new StateDeltaBuilder();
                while (true) {
                    const lineToTokenize = this.m.getFirstInvalidLine();
                    if (lineToTokenize === null || tokenizedLines > 200) {
                        break;
                    }
                    tokenizedLines++;
                    const text = this.b[lineToTokenize.lineNumber - 1];
                    const r = this.m.tokenizationSupport.tokenizeEncoded(text, true, lineToTokenize.startState);
                    if (this.m.store.setEndState(lineToTokenize.lineNumber, r.endState)) {
                        const delta = this.p(lineToTokenize.startState, r.endState);
                        stateDeltaBuilder.setState(lineToTokenize.lineNumber, delta);
                    }
                    else {
                        stateDeltaBuilder.setState(lineToTokenize.lineNumber, null);
                    }
                    lineTokens_1.$Iu.convertToEndOffset(r.tokens, text.length);
                    tokenBuilder.add(lineToTokenize.lineNumber, r.tokens);
                    const deltaMs = new Date().getTime() - startTime;
                    if (deltaMs > 20) {
                        // yield to check for changes
                        break;
                    }
                }
                if (tokenizedLines === 0) {
                    break;
                }
                const stateDeltas = stateDeltaBuilder.getStateDeltas();
                this.s.setTokensAndStates(this.d, tokenBuilder.serialize(), stateDeltas);
                const deltaMs = new Date().getTime() - startTime;
                if (deltaMs > 20) {
                    // yield to check for changes
                    (0, platform_1.$E)(() => this.w());
                    return;
                }
            }
        }
    }
    exports.$FPb = $FPb;
    class StateDeltaBuilder {
        constructor() {
            this.a = -1;
            this.b = [];
        }
        setState(lineNumber, stackDiff) {
            if (lineNumber === this.a + 1) {
                this.b[this.b.length - 1].stateDeltas.push(stackDiff);
            }
            else {
                this.b.push({ startLineNumber: lineNumber, stateDeltas: [stackDiff] });
            }
            this.a = lineNumber;
        }
        getStateDeltas() {
            return this.b;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/























define(__m[41/*vs/workbench/services/textMate/common/TMScopeRegistry*/], __M([0/*require*/,1/*exports*/,51/*vs/base/common/resources*/]), function (require, exports, resources) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$CPb = void 0;
    resources = __importStar(resources);
    class $CPb {
        constructor() {
            this.a = Object.create(null);
        }
        reset() {
            this.a = Object.create(null);
        }
        register(def) {
            if (this.a[def.scopeName]) {
                const existingRegistration = this.a[def.scopeName];
                if (!resources.$eh(existingRegistration.location, def.location)) {
                    console.warn(`Overwriting grammar scope name to file mapping for scope ${def.scopeName}.\n` +
                        `Old grammar file: ${existingRegistration.location.toString()}.\n` +
                        `New grammar file: ${def.location.toString()}`);
                }
            }
            this.a[def.scopeName] = def;
        }
        getGrammarDefinition(scopeName) {
            return this.a[scopeName] || null;
        }
    }
    exports.$CPb = $CPb;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[42/*vs/workbench/services/textMate/common/TMGrammarFactory*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,41/*vs/workbench/services/textMate/common/TMScopeRegistry*/]), function (require, exports, lifecycle_1, TMScopeRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.$EPb = exports.$DPb = void 0;
    exports.$DPb = 'No TM Grammar registered for this language.';
    class $EPb extends lifecycle_1.$Zc {
        constructor(host, grammarDefinitions, vscodeTextmate, onigLib) {
            super();
            this.a = host;
            this.b = vscodeTextmate.INITIAL;
            this.c = new TMScopeRegistry_1.$CPb();
            this.f = {};
            this.g = {};
            this.h = new Map();
            this.j = this.B(new vscodeTextmate.Registry({
                onigLib: onigLib,
                loadGrammar: async (scopeName) => {
                    const grammarDefinition = this.c.getGrammarDefinition(scopeName);
                    if (!grammarDefinition) {
                        this.a.logTrace(`No grammar found for scope ${scopeName}`);
                        return null;
                    }
                    const location = grammarDefinition.location;
                    try {
                        const content = await this.a.readFile(location);
                        return vscodeTextmate.parseRawGrammar(content, location.path);
                    }
                    catch (e) {
                        this.a.logError(`Unable to load and parse grammar for scope ${scopeName} from ${location}`, e);
                        return null;
                    }
                },
                getInjections: (scopeName) => {
                    const scopeParts = scopeName.split('.');
                    let injections = [];
                    for (let i = 1; i <= scopeParts.length; i++) {
                        const subScopeName = scopeParts.slice(0, i).join('.');
                        injections = [...injections, ...(this.f[subScopeName] || [])];
                    }
                    return injections;
                }
            }));
            for (const validGrammar of grammarDefinitions) {
                this.c.register(validGrammar);
                if (validGrammar.injectTo) {
                    for (const injectScope of validGrammar.injectTo) {
                        let injections = this.f[injectScope];
                        if (!injections) {
                            this.f[injectScope] = injections = [];
                        }
                        injections.push(validGrammar.scopeName);
                    }
                    if (validGrammar.embeddedLanguages) {
                        for (const injectScope of validGrammar.injectTo) {
                            let injectedEmbeddedLanguages = this.g[injectScope];
                            if (!injectedEmbeddedLanguages) {
                                this.g[injectScope] = injectedEmbeddedLanguages = [];
                            }
                            injectedEmbeddedLanguages.push(validGrammar.embeddedLanguages);
                        }
                    }
                }
                if (validGrammar.language) {
                    this.h.set(validGrammar.language, validGrammar.scopeName);
                }
            }
        }
        has(languageId) {
            return this.h.has(languageId);
        }
        setTheme(theme, colorMap) {
            this.j.setTheme(theme, colorMap);
        }
        getColorMap() {
            return this.j.getColorMap();
        }
        async createGrammar(languageId, encodedLanguageId) {
            const scopeName = this.h.get(languageId);
            if (typeof scopeName !== 'string') {
                // No TM grammar defined
                throw new Error(exports.$DPb);
            }
            const grammarDefinition = this.c.getGrammarDefinition(scopeName);
            if (!grammarDefinition) {
                // No TM grammar defined
                throw new Error(exports.$DPb);
            }
            const embeddedLanguages = grammarDefinition.embeddedLanguages;
            if (this.g[scopeName]) {
                const injectedEmbeddedLanguages = this.g[scopeName];
                for (const injected of injectedEmbeddedLanguages) {
                    for (const scope of Object.keys(injected)) {
                        embeddedLanguages[scope] = injected[scope];
                    }
                }
            }
            const containsEmbeddedLanguages = (Object.keys(embeddedLanguages).length > 0);
            let grammar;
            try {
                grammar = await this.j.loadGrammarWithConfiguration(scopeName, encodedLanguageId, {
                    embeddedLanguages,
                    tokenTypes: grammarDefinition.tokenTypes,
                    balancedBracketSelectors: grammarDefinition.balancedBracketSelectors,
                    unbalancedBracketSelectors: grammarDefinition.unbalancedBracketSelectors,
                });
            }
            catch (err) {
                if (err.message && err.message.startsWith('No grammar provided for')) {
                    // No TM grammar defined
                    throw new Error(exports.$DPb);
                }
                throw err;
            }
            return {
                languageId: languageId,
                grammar: grammar,
                initialState: this.b,
                containsEmbeddedLanguages: containsEmbeddedLanguages,
                sourceExtensionId: grammarDefinition.sourceExtensionId,
            };
        }
    }
    exports.$EPb = $EPb;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[52/*vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateTokenizationWorker.worker*/], __M([0/*require*/,1/*exports*/,32/*vs/base/common/uri*/,42/*vs/workbench/services/textMate/common/TMGrammarFactory*/,40/*vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateWorkerTokenizer*/,18/*vs/amdX*/,37/*vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateWorkerHost*/]), function (require, exports, uri_1, TMGrammarFactory_1, textMateWorkerTokenizer_1, amdX_1, textMateWorkerHost_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextMateTokenizationWorker = void 0;
    exports.create = create;
    /**
     * Defines the worker entry point. Must be exported and named `create`.
     * @skipMangle
     */
    function create(workerServer) {
        return new TextMateTokenizationWorker(workerServer);
    }
    class TextMateTokenizationWorker {
        constructor(workerServer) {
            this.b = new Map();
            this.c = [];
            this.d = Promise.resolve(null);
            this.a = textMateWorkerHost_1.$GPb.getChannel(workerServer);
        }
        async $init(_createData) {
            const grammarDefinitions = _createData.grammarDefinitions.map((def) => {
                return {
                    location: uri_1.URI.revive(def.location),
                    language: def.language,
                    scopeName: def.scopeName,
                    embeddedLanguages: def.embeddedLanguages,
                    tokenTypes: def.tokenTypes,
                    injectTo: def.injectTo,
                    balancedBracketSelectors: def.balancedBracketSelectors,
                    unbalancedBracketSelectors: def.unbalancedBracketSelectors,
                    sourceExtensionId: def.sourceExtensionId,
                };
            });
            this.d = this.f(grammarDefinitions, _createData.onigurumaWASMUri);
        }
        async f(grammarDefinitions, onigurumaWASMUri) {
            const vscodeTextmate = await (0, amdX_1.$zq)('vscode-textmate', 'release/main.js');
            const vscodeOniguruma = await (0, amdX_1.$zq)('vscode-oniguruma', 'release/main.js');
            const response = await fetch(onigurumaWASMUri);
            // Using the response directly only works if the server sets the MIME type 'application/wasm'.
            // Otherwise, a TypeError is thrown when using the streaming compiler.
            // We therefore use the non-streaming compiler :(.
            const bytes = await response.arrayBuffer();
            await vscodeOniguruma.loadWASM(bytes);
            const onigLib = Promise.resolve({
                createOnigScanner: (sources) => vscodeOniguruma.createOnigScanner(sources),
                createOnigString: (str) => vscodeOniguruma.createOnigString(str)
            });
            return new TMGrammarFactory_1.$EPb({
                logTrace: (msg) => { },
                logError: (msg, err) => console.error(msg, err),
                readFile: (resource) => this.a.$readFile(resource)
            }, grammarDefinitions, vscodeTextmate, onigLib);
        }
        // These methods are called by the renderer
        $acceptNewModel(data) {
            const uri = uri_1.URI.revive(data.uri);
            const that = this;
            this.b.set(data.controllerId, new textMateWorkerTokenizer_1.$FPb(uri, data.lines, data.EOL, data.versionId, {
                async getOrCreateGrammar(languageId, encodedLanguageId) {
                    const grammarFactory = await that.d;
                    if (!grammarFactory) {
                        return Promise.resolve(null);
                    }
                    if (!that.c[encodedLanguageId]) {
                        that.c[encodedLanguageId] = grammarFactory.createGrammar(languageId, encodedLanguageId);
                    }
                    return that.c[encodedLanguageId];
                },
                setTokensAndStates(versionId, tokens, stateDeltas) {
                    that.a.$setTokensAndStates(data.controllerId, versionId, tokens, stateDeltas);
                },
                reportTokenizationTime(timeMs, languageId, sourceExtensionId, lineLength, isRandomSample) {
                    that.a.$reportTokenizationTime(timeMs, languageId, sourceExtensionId, lineLength, isRandomSample);
                },
            }, data.languageId, data.encodedLanguageId, data.maxTokenizationLineLength));
        }
        $acceptModelChanged(controllerId, e) {
            this.b.get(controllerId).onEvents(e);
        }
        $retokenize(controllerId, startLineNumber, endLineNumberExclusive) {
            this.b.get(controllerId).retokenize(startLineNumber, endLineNumberExclusive);
        }
        $acceptModelLanguageChanged(controllerId, newLanguageId, newEncodedLanguageId) {
            this.b.get(controllerId).onLanguageId(newLanguageId, newEncodedLanguageId);
        }
        $acceptRemovedModel(controllerId) {
            const model = this.b.get(controllerId);
            if (model) {
                model.dispose();
                this.b.delete(controllerId);
            }
        }
        async $acceptTheme(theme, colorMap) {
            const grammarFactory = await this.d;
            grammarFactory?.setTheme(theme, colorMap);
        }
        $acceptMaxTokenizationLineLength(controllerId, value) {
            this.b.get(controllerId).acceptMaxTokenizationLineLength(value);
        }
    }
    exports.TextMateTokenizationWorker = TextMateTokenizationWorker;
});

}).call(this);
//# sourceMappingURL=textMateTokenizationWorker.worker.js.map
