import { c as createSourceFile, f as deepFreeze, g as deepClone, a as createDiagnostic, N as NoTarget, h as doIO, o as omitUndefined, r as reportDiagnostic, S as SyntaxKind, m as mutate, D as DuplicateTracker, l as loadFile, j as resolveTspMain, k as MANIFEST, L as ListenerFlow, d as createRekeyableMap, n as mapEquals, p as deepEquals, q as findProjectRoot, b as isDefined, i as isArray, s as getNormalizedRealPath, t as getSourceFileKindFromExt } from './index-rzprlTNi.js';
export { I as IdentifierKind, Q as Queue, T as TwoLevelMap, w as cadlVersion, u as paramMessage, v as typespecVersion } from './index-rzprlTNi.js';
import { g as getDirectoryPath, r as resolvePath, j as joinPaths, i as isPathAbsolute, n as normalizePath, a as getBaseFileName, h as hasTrailingDirectorySeparator, b as getAnyExtensionFromPath, e as ensureTrailingDirectorySeparator } from './path-utils-DDA4_T0g.js';
export { c as altDirectorySeparator, d as directorySeparator, w as ensurePathIsNonModuleName, q as getNormalizedAbsolutePath, s as getNormalizedAbsolutePathWithoutRoot, p as getNormalizedPathComponents, m as getPathComponents, t as getPathFromPathComponents, x as getRelativePathFromDirectory, l as getRootLength, f as isAnyDirectorySeparator, k as isUrl, v as normalizeSlashes, o as reducePathComponents, u as removeTrailingDirectorySeparator } from './path-utils-DDA4_T0g.js';
import { Y as YAMLMap, d as isMap, f as YAMLSeq, g as isSeq, s as stringifyString, S as Scalar, o as omap, p as pairs, h as set, M as MAP, j as SCALAR, k as SEQ, l as createStringifyContext, m as indentComment, n as isNode, q as stringify, t as lineComment, u as NODE_TYPE, v as DOC, w as Directives, x as anchorNames, y as findNewAnchor, A as Alias, z as createNode, B as isCollection, F as Pair, G as isEmptyPath, H as isScalar, I as collectionFromPath, J as toJS, K as applyReviver, L as createNodeAnchors, O as isPair, Q as Lexer, T as tokenType, U as createDiagnosticCollector, V as createJSONSchemaValidator, W as getLocationInYamlScript, X as ignoreDiagnostics, Z as getTypeName, c as compilerAssert, _ as parse$2, $ as visitChildren, a0 as getSourceLocation, a1 as typespecPrinter, a2 as gu, a3 as fi$1, i as isTemplateDeclaration, a4 as isTemplateDeclarationOrInstance, a5 as defineCodeFix, a6 as isWhiteSpace, a7 as getLocationContext, a8 as isValue, a9 as finishTypeForProgram, aa as isNeverType, ab as getParentTemplateNode, ac as isTemplateInstance, ad as createChecker, ae as getLibraryUrlsLoaded, af as isImportStatement, a as createAssetEmitter, ag as parseStandaloneTypeReference, ah as createBinder, ai as reportDeprecated, aj as setDocData, ak as getDocDataInternal, al as getMaxLengthAsNumeric, am as setMinLength, an as getMinLengthAsNumeric, ao as setMaxLength, ap as isArrayModelType, aq as getMaxItemsAsNumeric, ar as setMinItems, as as getMinItemsAsNumeric, at as setMaxItems, au as getMaxValueAsNumeric, av as getMaxValueExclusiveAsNumeric, aw as setMinValue, ax as getMinValueAsNumeric, ay as getMinValueExclusiveAsNumeric, az as setMaxValue, aA as setMinValueExclusive, aB as setMaxValueExclusive, aC as markDeprecated, aD as getDeprecationDetails, aE as getDiscriminatedUnion, aF as setDiscriminator, aG as commonjsGlobal, aH as getAugmentedNamespace, aI as createScanner, aJ as Token, aK as TokenFlags, aL as isKeyword, aM as isPunctuation, aN as formatDiagnostic, aO as printIdentifier, aP as getEntityName, aQ as getFullyQualifiedSymbolName, aR as isStdNamespace, aS as isType, aT as getDocData, aU as getFirstAncestor, aV as positionInRange, aW as skipWhiteSpace, aX as skipTrivia, aY as getNodeAtPosition, aZ as getPositionBeforeTrivia, a_ as getNodeAtPositionDetail, a$ as f0 } from './usage-resolver-DPDuvzLR.js';
export { bB as Keywords, bh as Numeric, bo as ProjectionError, bA as TokenDisplay, bv as UsageFlags, br as assertType, ba as createCadlLibrary, bb as createRule, bc as createTypeSpecLibrary, bd as defineLinter, be as definePackageFlags, e as emitFile, bs as explainStringTemplateNotSerializable, bx as exprIsBareIdentifier, bk as filterModelProperties, b0 as getDiscriminatedTypes, b1 as getDiscriminator, bj as getEffectiveModelType, bz as getIdentifierContext, b2 as getMaxItems, b3 as getMaxLength, b4 as getMaxValue, b5 as getMaxValueExclusive, b6 as getMinItems, b7 as getMinLength, b8 as getMinValue, b9 as getMinValueExclusive, bu as getNamespaceFullName, bl as getOverriddenProperty, by as hasParseError, bD as isComment, bP as isDeclaredInNamespace, bN as isDeclaredType, bn as isDeprecated, bI as isErrorType, bO as isGlobalNamespace, bE as isModifier, bL as isNullType, bi as isNumeric, bM as isRecordModelType, bF as isStatementKeyword, bC as isTrivia, bK as isUnknownType, bJ as isVoidType, bp as logDiagnostics, bq as logVerboseTestOutput, bw as resolveUsages, bf as setCadlNamespace, bg as setTypeSpecNamespace, bH as skipContinuousIdentifier, bG as skipTriviaBackward, bt as stringTemplateToString, bm as walkPropertiesInherited } from './usage-resolver-DPDuvzLR.js';
import { resolveModule } from './module-resolver.js';
export { ResolveModuleError } from './module-resolver.js';

const map = {
    collection: 'map',
    default: true,
    nodeClass: YAMLMap,
    tag: 'tag:yaml.org,2002:map',
    resolve(map, onError) {
        if (!isMap(map))
            onError('Expected a mapping for this tag');
        return map;
    },
    createNode: (schema, obj, ctx) => YAMLMap.from(schema, obj, ctx)
};

const seq = {
    collection: 'seq',
    default: true,
    nodeClass: YAMLSeq,
    tag: 'tag:yaml.org,2002:seq',
    resolve(seq, onError) {
        if (!isSeq(seq))
            onError('Expected a sequence for this tag');
        return seq;
    },
    createNode: (schema, obj, ctx) => YAMLSeq.from(schema, obj, ctx)
};

const string$2 = {
    identify: value => typeof value === 'string',
    default: true,
    tag: 'tag:yaml.org,2002:str',
    resolve: str => str,
    stringify(item, ctx, onComment, onChompKeep) {
        ctx = Object.assign({ actualString: true }, ctx);
        return stringifyString(item, ctx, onComment, onChompKeep);
    }
};

const nullTag = {
    identify: value => value == null,
    createNode: () => new Scalar(null),
    default: true,
    tag: 'tag:yaml.org,2002:null',
    test: /^(?:~|[Nn]ull|NULL)?$/,
    resolve: () => new Scalar(null),
    stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)
        ? source
        : ctx.options.nullStr
};

const boolTag = {
    identify: value => typeof value === 'boolean',
    default: true,
    tag: 'tag:yaml.org,2002:bool',
    test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
    resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'),
    stringify({ source, value }, ctx) {
        if (source && boolTag.test.test(source)) {
            const sv = source[0] === 't' || source[0] === 'T';
            if (value === sv)
                return source;
        }
        return value ? ctx.options.trueStr : ctx.options.falseStr;
    }
};

function stringifyNumber({ format, minFractionDigits, tag, value }) {
    if (typeof value === 'bigint')
        return String(value);
    const num = typeof value === 'number' ? value : Number(value);
    if (!isFinite(num))
        return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';
    let n = JSON.stringify(value);
    if (!format &&
        minFractionDigits &&
        (!tag || tag === 'tag:yaml.org,2002:float') &&
        /^\d/.test(n)) {
        let i = n.indexOf('.');
        if (i < 0) {
            i = n.length;
            n += '.';
        }
        let d = minFractionDigits - (n.length - i - 1);
        while (d-- > 0)
            n += '0';
    }
    return n;
}

const floatNaN$1 = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
    resolve: str => str.slice(-3).toLowerCase() === 'nan'
        ? NaN
        : str[0] === '-'
            ? Number.NEGATIVE_INFINITY
            : Number.POSITIVE_INFINITY,
    stringify: stringifyNumber
};
const floatExp$1 = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    format: 'EXP',
    test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
    resolve: str => parseFloat(str),
    stringify(node) {
        const num = Number(node.value);
        return isFinite(num) ? num.toExponential() : stringifyNumber(node);
    }
};
const float$1 = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
    resolve(str) {
        const node = new Scalar(parseFloat(str));
        const dot = str.indexOf('.');
        if (dot !== -1 && str[str.length - 1] === '0')
            node.minFractionDigits = str.length - dot - 1;
        return node;
    },
    stringify: stringifyNumber
};

const intIdentify$2 = (value) => typeof value === 'bigint' || Number.isInteger(value);
const intResolve$1 = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));
function intStringify$1(node, radix, prefix) {
    const { value } = node;
    if (intIdentify$2(value) && value >= 0)
        return prefix + value.toString(radix);
    return stringifyNumber(node);
}
const intOct$1 = {
    identify: value => intIdentify$2(value) && value >= 0,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'OCT',
    test: /^0o[0-7]+$/,
    resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt),
    stringify: node => intStringify$1(node, 8, '0o')
};
const int$1 = {
    identify: intIdentify$2,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    test: /^[-+]?[0-9]+$/,
    resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt),
    stringify: stringifyNumber
};
const intHex$1 = {
    identify: value => intIdentify$2(value) && value >= 0,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'HEX',
    test: /^0x[0-9a-fA-F]+$/,
    resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt),
    stringify: node => intStringify$1(node, 16, '0x')
};

const schema$2 = [
    map,
    seq,
    string$2,
    nullTag,
    boolTag,
    intOct$1,
    int$1,
    intHex$1,
    floatNaN$1,
    floatExp$1,
    float$1
];

function intIdentify$1(value) {
    return typeof value === 'bigint' || Number.isInteger(value);
}
const stringifyJSON = ({ value }) => JSON.stringify(value);
const jsonScalars = [
    {
        identify: value => typeof value === 'string',
        default: true,
        tag: 'tag:yaml.org,2002:str',
        resolve: str => str,
        stringify: stringifyJSON
    },
    {
        identify: value => value == null,
        createNode: () => new Scalar(null),
        default: true,
        tag: 'tag:yaml.org,2002:null',
        test: /^null$/,
        resolve: () => null,
        stringify: stringifyJSON
    },
    {
        identify: value => typeof value === 'boolean',
        default: true,
        tag: 'tag:yaml.org,2002:bool',
        test: /^true|false$/,
        resolve: str => str === 'true',
        stringify: stringifyJSON
    },
    {
        identify: intIdentify$1,
        default: true,
        tag: 'tag:yaml.org,2002:int',
        test: /^-?(?:0|[1-9][0-9]*)$/,
        resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
        stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
    },
    {
        identify: value => typeof value === 'number',
        default: true,
        tag: 'tag:yaml.org,2002:float',
        test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
        resolve: str => parseFloat(str),
        stringify: stringifyJSON
    }
];
const jsonError = {
    default: true,
    tag: '',
    test: /^/,
    resolve(str, onError) {
        onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
        return str;
    }
};
const schema$1 = [map, seq].concat(jsonScalars, jsonError);

const binary = {
    identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array
    default: false,
    tag: 'tag:yaml.org,2002:binary',
    /**
     * Returns a Buffer in node and an Uint8Array in browsers
     *
     * To use the resulting buffer as an image, you'll want to do something like:
     *
     *   const blob = new Blob([buffer], { type: 'image/jpeg' })
     *   document.querySelector('#photo').src = URL.createObjectURL(blob)
     */
    resolve(src, onError) {
        if (typeof Buffer === 'function') {
            return Buffer.from(src, 'base64');
        }
        else if (typeof atob === 'function') {
            // On IE 11, atob() can't handle newlines
            const str = atob(src.replace(/[\n\r]/g, ''));
            const buffer = new Uint8Array(str.length);
            for (let i = 0; i < str.length; ++i)
                buffer[i] = str.charCodeAt(i);
            return buffer;
        }
        else {
            onError('This environment does not support reading binary tags; either Buffer or atob is required');
            return src;
        }
    },
    stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
        const buf = value; // checked earlier by binary.identify()
        let str;
        if (typeof Buffer === 'function') {
            str =
                buf instanceof Buffer
                    ? buf.toString('base64')
                    : Buffer.from(buf.buffer).toString('base64');
        }
        else if (typeof btoa === 'function') {
            let s = '';
            for (let i = 0; i < buf.length; ++i)
                s += String.fromCharCode(buf[i]);
            str = btoa(s);
        }
        else {
            throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
        }
        if (!type)
            type = Scalar.BLOCK_LITERAL;
        if (type !== Scalar.QUOTE_DOUBLE) {
            const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
            const n = Math.ceil(str.length / lineWidth);
            const lines = new Array(n);
            for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
                lines[i] = str.substr(o, lineWidth);
            }
            str = lines.join(type === Scalar.BLOCK_LITERAL ? '\n' : ' ');
        }
        return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
    }
};

function boolStringify({ value, source }, ctx) {
    const boolObj = value ? trueTag : falseTag;
    if (source && boolObj.test.test(source))
        return source;
    return value ? ctx.options.trueStr : ctx.options.falseStr;
}
const trueTag = {
    identify: value => value === true,
    default: true,
    tag: 'tag:yaml.org,2002:bool',
    test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
    resolve: () => new Scalar(true),
    stringify: boolStringify
};
const falseTag = {
    identify: value => value === false,
    default: true,
    tag: 'tag:yaml.org,2002:bool',
    test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
    resolve: () => new Scalar(false),
    stringify: boolStringify
};

const floatNaN = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
    resolve: (str) => str.slice(-3).toLowerCase() === 'nan'
        ? NaN
        : str[0] === '-'
            ? Number.NEGATIVE_INFINITY
            : Number.POSITIVE_INFINITY,
    stringify: stringifyNumber
};
const floatExp = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    format: 'EXP',
    test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
    resolve: (str) => parseFloat(str.replace(/_/g, '')),
    stringify(node) {
        const num = Number(node.value);
        return isFinite(num) ? num.toExponential() : stringifyNumber(node);
    }
};
const float = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
    resolve(str) {
        const node = new Scalar(parseFloat(str.replace(/_/g, '')));
        const dot = str.indexOf('.');
        if (dot !== -1) {
            const f = str.substring(dot + 1).replace(/_/g, '');
            if (f[f.length - 1] === '0')
                node.minFractionDigits = f.length;
        }
        return node;
    },
    stringify: stringifyNumber
};

const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
function intResolve(str, offset, radix, { intAsBigInt }) {
    const sign = str[0];
    if (sign === '-' || sign === '+')
        offset += 1;
    str = str.substring(offset).replace(/_/g, '');
    if (intAsBigInt) {
        switch (radix) {
            case 2:
                str = `0b${str}`;
                break;
            case 8:
                str = `0o${str}`;
                break;
            case 16:
                str = `0x${str}`;
                break;
        }
        const n = BigInt(str);
        return sign === '-' ? BigInt(-1) * n : n;
    }
    const n = parseInt(str, radix);
    return sign === '-' ? -1 * n : n;
}
function intStringify(node, radix, prefix) {
    const { value } = node;
    if (intIdentify(value)) {
        const str = value.toString(radix);
        return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
    }
    return stringifyNumber(node);
}
const intBin = {
    identify: intIdentify,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'BIN',
    test: /^[-+]?0b[0-1_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
    stringify: node => intStringify(node, 2, '0b')
};
const intOct = {
    identify: intIdentify,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'OCT',
    test: /^[-+]?0[0-7_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
    stringify: node => intStringify(node, 8, '0')
};
const int = {
    identify: intIdentify,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    test: /^[-+]?[0-9][0-9_]*$/,
    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
    stringify: stringifyNumber
};
const intHex = {
    identify: intIdentify,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'HEX',
    test: /^[-+]?0x[0-9a-fA-F_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
    stringify: node => intStringify(node, 16, '0x')
};

/** Internal types handle bigint as number, because TS can't figure it out. */
function parseSexagesimal(str, asBigInt) {
    const sign = str[0];
    const parts = sign === '-' || sign === '+' ? str.substring(1) : str;
    const num = (n) => asBigInt ? BigInt(n) : Number(n);
    const res = parts
        .replace(/_/g, '')
        .split(':')
        .reduce((res, p) => res * num(60) + num(p), num(0));
    return (sign === '-' ? num(-1) * res : res);
}
/**
 * hhhh:mm:ss.sss
 *
 * Internal types handle bigint as number, because TS can't figure it out.
 */
function stringifySexagesimal(node) {
    let { value } = node;
    let num = (n) => n;
    if (typeof value === 'bigint')
        num = n => BigInt(n);
    else if (isNaN(value) || !isFinite(value))
        return stringifyNumber(node);
    let sign = '';
    if (value < 0) {
        sign = '-';
        value *= num(-1);
    }
    const _60 = num(60);
    const parts = [value % _60]; // seconds, including ms
    if (value < 60) {
        parts.unshift(0); // at least one : is required
    }
    else {
        value = (value - parts[0]) / _60;
        parts.unshift(value % _60); // minutes
        if (value >= 60) {
            value = (value - parts[0]) / _60;
            parts.unshift(value); // hours
        }
    }
    return (sign +
        parts
            .map(n => String(n).padStart(2, '0'))
            .join(':')
            .replace(/000000\d*$/, '') // % 60 may introduce error
    );
}
const intTime = {
    identify: value => typeof value === 'bigint' || Number.isInteger(value),
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'TIME',
    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
    resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
    stringify: stringifySexagesimal
};
const floatTime = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    format: 'TIME',
    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
    resolve: str => parseSexagesimal(str, false),
    stringify: stringifySexagesimal
};
const timestamp = {
    identify: value => value instanceof Date,
    default: true,
    tag: 'tag:yaml.org,2002:timestamp',
    // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
    // may be omitted altogether, resulting in a date format. In such a case, the time part is
    // assumed to be 00:00:00Z (start of day, UTC).
    test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
        '(?:' + // time is optional
        '(?:t|T|[ \\t]+)' + // t | T | whitespace
        '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
        '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
        ')?$'),
    resolve(str) {
        const match = str.match(timestamp.test);
        if (!match)
            throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');
        const [, year, month, day, hour, minute, second] = match.map(Number);
        const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;
        let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
        const tz = match[8];
        if (tz && tz !== 'Z') {
            let d = parseSexagesimal(tz, false);
            if (Math.abs(d) < 30)
                d *= 60;
            date -= 60000 * d;
        }
        return new Date(date);
    },
    stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
};

const schema = [
    map,
    seq,
    string$2,
    nullTag,
    trueTag,
    falseTag,
    intBin,
    intOct,
    int,
    intHex,
    floatNaN,
    floatExp,
    float,
    binary,
    omap,
    pairs,
    set,
    intTime,
    floatTime,
    timestamp
];

const schemas = new Map([
    ['core', schema$2],
    ['failsafe', [map, seq, string$2]],
    ['json', schema$1],
    ['yaml11', schema],
    ['yaml-1.1', schema]
]);
const tagsByName = {
    binary,
    bool: boolTag,
    float: float$1,
    floatExp: floatExp$1,
    floatNaN: floatNaN$1,
    floatTime,
    int: int$1,
    intHex: intHex$1,
    intOct: intOct$1,
    intTime,
    map,
    null: nullTag,
    omap,
    pairs,
    seq,
    set,
    timestamp
};
const coreKnownTags = {
    'tag:yaml.org,2002:binary': binary,
    'tag:yaml.org,2002:omap': omap,
    'tag:yaml.org,2002:pairs': pairs,
    'tag:yaml.org,2002:set': set,
    'tag:yaml.org,2002:timestamp': timestamp
};
function getTags$1(customTags, schemaName) {
    let tags = schemas.get(schemaName);
    if (!tags) {
        if (Array.isArray(customTags))
            tags = [];
        else {
            const keys = Array.from(schemas.keys())
                .filter(key => key !== 'yaml11')
                .map(key => JSON.stringify(key))
                .join(', ');
            throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
        }
    }
    if (Array.isArray(customTags)) {
        for (const tag of customTags)
            tags = tags.concat(tag);
    }
    else if (typeof customTags === 'function') {
        tags = customTags(tags.slice());
    }
    return tags.map(tag => {
        if (typeof tag !== 'string')
            return tag;
        const tagObj = tagsByName[tag];
        if (tagObj)
            return tagObj;
        const keys = Object.keys(tagsByName)
            .map(key => JSON.stringify(key))
            .join(', ');
        throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
    });
}

const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
class Schema {
    constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
        this.compat = Array.isArray(compat)
            ? getTags$1(compat, 'compat')
            : compat
                ? getTags$1(null, compat)
                : null;
        this.merge = !!merge;
        this.name = (typeof schema === 'string' && schema) || 'core';
        this.knownTags = resolveKnownTags ? coreKnownTags : {};
        this.tags = getTags$1(customTags, this.name);
        this.toStringOptions = toStringDefaults ?? null;
        Object.defineProperty(this, MAP, { value: map });
        Object.defineProperty(this, SCALAR, { value: string$2 });
        Object.defineProperty(this, SEQ, { value: seq });
        // Used by createMap()
        this.sortMapEntries =
            typeof sortMapEntries === 'function'
                ? sortMapEntries
                : sortMapEntries === true
                    ? sortMapEntriesByKey
                    : null;
    }
    clone() {
        const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
        copy.tags = this.tags.slice();
        return copy;
    }
}

function stringifyDocument(doc, options) {
    const lines = [];
    let hasDirectives = options.directives === true;
    if (options.directives !== false && doc.directives) {
        const dir = doc.directives.toString(doc);
        if (dir) {
            lines.push(dir);
            hasDirectives = true;
        }
        else if (doc.directives.docStart)
            hasDirectives = true;
    }
    if (hasDirectives)
        lines.push('---');
    const ctx = createStringifyContext(doc, options);
    const { commentString } = ctx.options;
    if (doc.commentBefore) {
        if (lines.length !== 1)
            lines.unshift('');
        const cs = commentString(doc.commentBefore);
        lines.unshift(indentComment(cs, ''));
    }
    let chompKeep = false;
    let contentComment = null;
    if (doc.contents) {
        if (isNode(doc.contents)) {
            if (doc.contents.spaceBefore && hasDirectives)
                lines.push('');
            if (doc.contents.commentBefore) {
                const cs = commentString(doc.contents.commentBefore);
                lines.push(indentComment(cs, ''));
            }
            // top-level block scalars need to be indented if followed by a comment
            ctx.forceBlockIndent = !!doc.comment;
            contentComment = doc.contents.comment;
        }
        const onChompKeep = contentComment ? undefined : () => (chompKeep = true);
        let body = stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);
        if (contentComment)
            body += lineComment(body, '', commentString(contentComment));
        if ((body[0] === '|' || body[0] === '>') &&
            lines[lines.length - 1] === '---') {
            // Top-level block scalars with a preceding doc marker ought to use the
            // same line for their header.
            lines[lines.length - 1] = `--- ${body}`;
        }
        else
            lines.push(body);
    }
    else {
        lines.push(stringify(doc.contents, ctx));
    }
    if (doc.directives?.docEnd) {
        if (doc.comment) {
            const cs = commentString(doc.comment);
            if (cs.includes('\n')) {
                lines.push('...');
                lines.push(indentComment(cs, ''));
            }
            else {
                lines.push(`... ${cs}`);
            }
        }
        else {
            lines.push('...');
        }
    }
    else {
        let dc = doc.comment;
        if (dc && chompKeep)
            dc = dc.replace(/^\n+/, '');
        if (dc) {
            if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
                lines.push('');
            lines.push(indentComment(commentString(dc), ''));
        }
    }
    return lines.join('\n') + '\n';
}

class Document {
    constructor(value, replacer, options) {
        /** A comment before this Document */
        this.commentBefore = null;
        /** A comment immediately after this Document */
        this.comment = null;
        /** Errors encountered during parsing. */
        this.errors = [];
        /** Warnings encountered during parsing. */
        this.warnings = [];
        Object.defineProperty(this, NODE_TYPE, { value: DOC });
        let _replacer = null;
        if (typeof replacer === 'function' || Array.isArray(replacer)) {
            _replacer = replacer;
        }
        else if (options === undefined && replacer) {
            options = replacer;
            replacer = undefined;
        }
        const opt = Object.assign({
            intAsBigInt: false,
            keepSourceTokens: false,
            logLevel: 'warn',
            prettyErrors: true,
            strict: true,
            uniqueKeys: true,
            version: '1.2'
        }, options);
        this.options = opt;
        let { version } = opt;
        if (options?._directives) {
            this.directives = options._directives.atDocument();
            if (this.directives.yaml.explicit)
                version = this.directives.yaml.version;
        }
        else
            this.directives = new Directives({ version });
        this.setSchema(version, options);
        // @ts-expect-error We can't really know that this matches Contents.
        this.contents =
            value === undefined ? null : this.createNode(value, _replacer, options);
    }
    /**
     * Create a deep copy of this Document and its contents.
     *
     * Custom Node values that inherit from `Object` still refer to their original instances.
     */
    clone() {
        const copy = Object.create(Document.prototype, {
            [NODE_TYPE]: { value: DOC }
        });
        copy.commentBefore = this.commentBefore;
        copy.comment = this.comment;
        copy.errors = this.errors.slice();
        copy.warnings = this.warnings.slice();
        copy.options = Object.assign({}, this.options);
        if (this.directives)
            copy.directives = this.directives.clone();
        copy.schema = this.schema.clone();
        // @ts-expect-error We can't really know that this matches Contents.
        copy.contents = isNode(this.contents)
            ? this.contents.clone(copy.schema)
            : this.contents;
        if (this.range)
            copy.range = this.range.slice();
        return copy;
    }
    /** Adds a value to the document. */
    add(value) {
        if (assertCollection(this.contents))
            this.contents.add(value);
    }
    /** Adds a value to the document. */
    addIn(path, value) {
        if (assertCollection(this.contents))
            this.contents.addIn(path, value);
    }
    /**
     * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
     *
     * If `node` already has an anchor, `name` is ignored.
     * Otherwise, the `node.anchor` value will be set to `name`,
     * or if an anchor with that name is already present in the document,
     * `name` will be used as a prefix for a new unique anchor.
     * If `name` is undefined, the generated anchor will use 'a' as a prefix.
     */
    createAlias(node, name) {
        if (!node.anchor) {
            const prev = anchorNames(this);
            node.anchor =
                // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
                !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;
        }
        return new Alias(node.anchor);
    }
    createNode(value, replacer, options) {
        let _replacer = undefined;
        if (typeof replacer === 'function') {
            value = replacer.call({ '': value }, '', value);
            _replacer = replacer;
        }
        else if (Array.isArray(replacer)) {
            const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;
            const asStr = replacer.filter(keyToStr).map(String);
            if (asStr.length > 0)
                replacer = replacer.concat(asStr);
            _replacer = replacer;
        }
        else if (options === undefined && replacer) {
            options = replacer;
            replacer = undefined;
        }
        const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
        const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this, 
        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
        anchorPrefix || 'a');
        const ctx = {
            aliasDuplicateObjects: aliasDuplicateObjects ?? true,
            keepUndefined: keepUndefined ?? false,
            onAnchor,
            onTagObj,
            replacer: _replacer,
            schema: this.schema,
            sourceObjects
        };
        const node = createNode(value, tag, ctx);
        if (flow && isCollection(node))
            node.flow = true;
        setAnchors();
        return node;
    }
    /**
     * Convert a key and a value into a `Pair` using the current schema,
     * recursively wrapping all values as `Scalar` or `Collection` nodes.
     */
    createPair(key, value, options = {}) {
        const k = this.createNode(key, null, options);
        const v = this.createNode(value, null, options);
        return new Pair(k, v);
    }
    /**
     * Removes a value from the document.
     * @returns `true` if the item was found and removed.
     */
    delete(key) {
        return assertCollection(this.contents) ? this.contents.delete(key) : false;
    }
    /**
     * Removes a value from the document.
     * @returns `true` if the item was found and removed.
     */
    deleteIn(path) {
        if (isEmptyPath(path)) {
            if (this.contents == null)
                return false;
            // @ts-expect-error Presumed impossible if Strict extends false
            this.contents = null;
            return true;
        }
        return assertCollection(this.contents)
            ? this.contents.deleteIn(path)
            : false;
    }
    /**
     * Returns item at `key`, or `undefined` if not found. By default unwraps
     * scalar values from their surrounding node; to disable set `keepScalar` to
     * `true` (collections are always returned intact).
     */
    get(key, keepScalar) {
        return isCollection(this.contents)
            ? this.contents.get(key, keepScalar)
            : undefined;
    }
    /**
     * Returns item at `path`, or `undefined` if not found. By default unwraps
     * scalar values from their surrounding node; to disable set `keepScalar` to
     * `true` (collections are always returned intact).
     */
    getIn(path, keepScalar) {
        if (isEmptyPath(path))
            return !keepScalar && isScalar(this.contents)
                ? this.contents.value
                : this.contents;
        return isCollection(this.contents)
            ? this.contents.getIn(path, keepScalar)
            : undefined;
    }
    /**
     * Checks if the document includes a value with the key `key`.
     */
    has(key) {
        return isCollection(this.contents) ? this.contents.has(key) : false;
    }
    /**
     * Checks if the document includes a value at `path`.
     */
    hasIn(path) {
        if (isEmptyPath(path))
            return this.contents !== undefined;
        return isCollection(this.contents) ? this.contents.hasIn(path) : false;
    }
    /**
     * Sets a value in this document. For `!!set`, `value` needs to be a
     * boolean to add/remove the item from the set.
     */
    set(key, value) {
        if (this.contents == null) {
            // @ts-expect-error We can't really know that this matches Contents.
            this.contents = collectionFromPath(this.schema, [key], value);
        }
        else if (assertCollection(this.contents)) {
            this.contents.set(key, value);
        }
    }
    /**
     * Sets a value in this document. For `!!set`, `value` needs to be a
     * boolean to add/remove the item from the set.
     */
    setIn(path, value) {
        if (isEmptyPath(path)) {
            // @ts-expect-error We can't really know that this matches Contents.
            this.contents = value;
        }
        else if (this.contents == null) {
            // @ts-expect-error We can't really know that this matches Contents.
            this.contents = collectionFromPath(this.schema, Array.from(path), value);
        }
        else if (assertCollection(this.contents)) {
            this.contents.setIn(path, value);
        }
    }
    /**
     * Change the YAML version and schema used by the document.
     * A `null` version disables support for directives, explicit tags, anchors, and aliases.
     * It also requires the `schema` option to be given as a `Schema` instance value.
     *
     * Overrides all previously set schema options.
     */
    setSchema(version, options = {}) {
        if (typeof version === 'number')
            version = String(version);
        let opt;
        switch (version) {
            case '1.1':
                if (this.directives)
                    this.directives.yaml.version = '1.1';
                else
                    this.directives = new Directives({ version: '1.1' });
                opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' };
                break;
            case '1.2':
            case 'next':
                if (this.directives)
                    this.directives.yaml.version = version;
                else
                    this.directives = new Directives({ version });
                opt = { merge: false, resolveKnownTags: true, schema: 'core' };
                break;
            case null:
                if (this.directives)
                    delete this.directives;
                opt = null;
                break;
            default: {
                const sv = JSON.stringify(version);
                throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
            }
        }
        // Not using `instanceof Schema` to allow for duck typing
        if (options.schema instanceof Object)
            this.schema = options.schema;
        else if (opt)
            this.schema = new Schema(Object.assign(opt, options));
        else
            throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
    }
    // json & jsonArg are only used from toJSON()
    toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
        const ctx = {
            anchors: new Map(),
            doc: this,
            keep: !json,
            mapAsMap: mapAsMap === true,
            mapKeyWarned: false,
            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
        };
        const res = toJS(this.contents, jsonArg ?? '', ctx);
        if (typeof onAnchor === 'function')
            for (const { count, res } of ctx.anchors.values())
                onAnchor(res, count);
        return typeof reviver === 'function'
            ? applyReviver(reviver, { '': res }, '', res)
            : res;
    }
    /**
     * A JSON representation of the document `contents`.
     *
     * @param jsonArg Used by `JSON.stringify` to indicate the array index or
     *   property name.
     */
    toJSON(jsonArg, onAnchor) {
        return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
    }
    /** A YAML representation of the document. */
    toString(options = {}) {
        if (this.errors.length > 0)
            throw new Error('Document with errors cannot be stringified');
        if ('indent' in options &&
            (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
            const s = JSON.stringify(options.indent);
            throw new Error(`"indent" option must be a positive integer, not ${s}`);
        }
        return stringifyDocument(this, options);
    }
}
function assertCollection(contents) {
    if (isCollection(contents))
        return true;
    throw new Error('Expected a YAML collection as document contents');
}

class YAMLError extends Error {
    constructor(name, pos, code, message) {
        super();
        this.name = name;
        this.code = code;
        this.message = message;
        this.pos = pos;
    }
}
class YAMLParseError extends YAMLError {
    constructor(pos, code, message) {
        super('YAMLParseError', pos, code, message);
    }
}
class YAMLWarning extends YAMLError {
    constructor(pos, code, message) {
        super('YAMLWarning', pos, code, message);
    }
}
const prettifyError = (src, lc) => (error) => {
    if (error.pos[0] === -1)
        return;
    error.linePos = error.pos.map(pos => lc.linePos(pos));
    const { line, col } = error.linePos[0];
    error.message += ` at line ${line}, column ${col}`;
    let ci = col - 1;
    let lineStr = src
        .substring(lc.lineStarts[line - 1], lc.lineStarts[line])
        .replace(/[\n\r]+$/, '');
    // Trim to max 80 chars, keeping col position near the middle
    if (ci >= 60 && lineStr.length > 80) {
        const trimStart = Math.min(ci - 39, lineStr.length - 79);
        lineStr = '…' + lineStr.substring(trimStart);
        ci -= trimStart - 1;
    }
    if (lineStr.length > 80)
        lineStr = lineStr.substring(0, 79) + '…';
    // Include previous line in context if pointing at line start
    if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
        // Regexp won't match if start is trimmed
        let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
        if (prev.length > 80)
            prev = prev.substring(0, 79) + '…\n';
        lineStr = prev + lineStr;
    }
    if (/[^ ]/.test(lineStr)) {
        let count = 1;
        const end = error.linePos[1];
        if (end && end.line === line && end.col > col) {
            count = Math.max(1, Math.min(end.col - col, 80 - ci));
        }
        const pointer = ' '.repeat(ci) + '^'.repeat(count);
        error.message += `:\n\n${lineStr}\n${pointer}\n`;
    }
};

function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
    let spaceBefore = false;
    let atNewline = startOnNewline;
    let hasSpace = startOnNewline;
    let comment = '';
    let commentSep = '';
    let hasNewline = false;
    let hasNewlineAfterProp = false;
    let reqSpace = false;
    let tab = null;
    let anchor = null;
    let tag = null;
    let comma = null;
    let found = null;
    let start = null;
    for (const token of tokens) {
        if (reqSpace) {
            if (token.type !== 'space' &&
                token.type !== 'newline' &&
                token.type !== 'comma')
                onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
            reqSpace = false;
        }
        if (tab) {
            if (atNewline && token.type !== 'comment' && token.type !== 'newline') {
                onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
            }
            tab = null;
        }
        switch (token.type) {
            case 'space':
                // At the doc level, tabs at line start may be parsed
                // as leading white space rather than indentation.
                // In a flow collection, only the parser handles indent.
                if (!flow &&
                    (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&
                    token.source.includes('\t')) {
                    tab = token;
                }
                hasSpace = true;
                break;
            case 'comment': {
                if (!hasSpace)
                    onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
                const cb = token.source.substring(1) || ' ';
                if (!comment)
                    comment = cb;
                else
                    comment += commentSep + cb;
                commentSep = '';
                atNewline = false;
                break;
            }
            case 'newline':
                if (atNewline) {
                    if (comment)
                        comment += token.source;
                    else
                        spaceBefore = true;
                }
                else
                    commentSep += token.source;
                atNewline = true;
                hasNewline = true;
                if (anchor || tag)
                    hasNewlineAfterProp = true;
                hasSpace = true;
                break;
            case 'anchor':
                if (anchor)
                    onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');
                if (token.source.endsWith(':'))
                    onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);
                anchor = token;
                if (start === null)
                    start = token.offset;
                atNewline = false;
                hasSpace = false;
                reqSpace = true;
                break;
            case 'tag': {
                if (tag)
                    onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');
                tag = token;
                if (start === null)
                    start = token.offset;
                atNewline = false;
                hasSpace = false;
                reqSpace = true;
                break;
            }
            case indicator:
                // Could here handle preceding comments differently
                if (anchor || tag)
                    onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);
                if (found)
                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);
                found = token;
                atNewline =
                    indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';
                hasSpace = false;
                break;
            case 'comma':
                if (flow) {
                    if (comma)
                        onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);
                    comma = token;
                    atNewline = false;
                    hasSpace = false;
                    break;
                }
            // else fallthrough
            default:
                onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);
                atNewline = false;
                hasSpace = false;
        }
    }
    const last = tokens[tokens.length - 1];
    const end = last ? last.offset + last.source.length : offset;
    if (reqSpace &&
        next &&
        next.type !== 'space' &&
        next.type !== 'newline' &&
        next.type !== 'comma' &&
        (next.type !== 'scalar' || next.source !== '')) {
        onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
    }
    if (tab &&
        ((atNewline && tab.indent <= parentIndent) ||
            next?.type === 'block-map' ||
            next?.type === 'block-seq'))
        onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
    return {
        comma,
        found,
        spaceBefore,
        comment,
        hasNewline,
        hasNewlineAfterProp,
        anchor,
        tag,
        end,
        start: start ?? end
    };
}

function containsNewline(key) {
    if (!key)
        return null;
    switch (key.type) {
        case 'alias':
        case 'scalar':
        case 'double-quoted-scalar':
        case 'single-quoted-scalar':
            if (key.source.includes('\n'))
                return true;
            if (key.end)
                for (const st of key.end)
                    if (st.type === 'newline')
                        return true;
            return false;
        case 'flow-collection':
            for (const it of key.items) {
                for (const st of it.start)
                    if (st.type === 'newline')
                        return true;
                if (it.sep)
                    for (const st of it.sep)
                        if (st.type === 'newline')
                            return true;
                if (containsNewline(it.key) || containsNewline(it.value))
                    return true;
            }
            return false;
        default:
            return true;
    }
}

function flowIndentCheck(indent, fc, onError) {
    if (fc?.type === 'flow-collection') {
        const end = fc.end[0];
        if (end.indent === indent &&
            (end.source === ']' || end.source === '}') &&
            containsNewline(fc)) {
            const msg = 'Flow end indicator should be more indented than parent';
            onError(end, 'BAD_INDENT', msg, true);
        }
    }
}

function mapIncludes(ctx, items, search) {
    const { uniqueKeys } = ctx.options;
    if (uniqueKeys === false)
        return false;
    const isEqual = typeof uniqueKeys === 'function'
        ? uniqueKeys
        : (a, b) => a === b ||
            (isScalar(a) &&
                isScalar(b) &&
                a.value === b.value &&
                !(a.value === '<<' && ctx.schema.merge));
    return items.some(pair => isEqual(pair.key, search));
}

const startColMsg = 'All mapping items must start at the same column';
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
    const NodeClass = tag?.nodeClass ?? YAMLMap;
    const map = new NodeClass(ctx.schema);
    if (ctx.atRoot)
        ctx.atRoot = false;
    let offset = bm.offset;
    let commentEnd = null;
    for (const collItem of bm.items) {
        const { start, key, sep, value } = collItem;
        // key properties
        const keyProps = resolveProps(start, {
            indicator: 'explicit-key-ind',
            next: key ?? sep?.[0],
            offset,
            onError,
            parentIndent: bm.indent,
            startOnNewline: true
        });
        const implicitKey = !keyProps.found;
        if (implicitKey) {
            if (key) {
                if (key.type === 'block-seq')
                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');
                else if ('indent' in key && key.indent !== bm.indent)
                    onError(offset, 'BAD_INDENT', startColMsg);
            }
            if (!keyProps.anchor && !keyProps.tag && !sep) {
                commentEnd = keyProps.end;
                if (keyProps.comment) {
                    if (map.comment)
                        map.comment += '\n' + keyProps.comment;
                    else
                        map.comment = keyProps.comment;
                }
                continue;
            }
            if (keyProps.hasNewlineAfterProp || containsNewline(key)) {
                onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');
            }
        }
        else if (keyProps.found?.indent !== bm.indent) {
            onError(offset, 'BAD_INDENT', startColMsg);
        }
        // key value
        const keyStart = keyProps.end;
        const keyNode = key
            ? composeNode(ctx, key, keyProps, onError)
            : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
        if (ctx.schema.compat)
            flowIndentCheck(bm.indent, key, onError);
        if (mapIncludes(ctx, map.items, keyNode))
            onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
        // value properties
        const valueProps = resolveProps(sep ?? [], {
            indicator: 'map-value-ind',
            next: value,
            offset: keyNode.range[2],
            onError,
            parentIndent: bm.indent,
            startOnNewline: !key || key.type === 'block-scalar'
        });
        offset = valueProps.end;
        if (valueProps.found) {
            if (implicitKey) {
                if (value?.type === 'block-map' && !valueProps.hasNewline)
                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');
                if (ctx.options.strict &&
                    keyProps.start < valueProps.found.offset - 1024)
                    onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');
            }
            // value value
            const valueNode = value
                ? composeNode(ctx, value, valueProps, onError)
                : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
            if (ctx.schema.compat)
                flowIndentCheck(bm.indent, value, onError);
            offset = valueNode.range[2];
            const pair = new Pair(keyNode, valueNode);
            if (ctx.options.keepSourceTokens)
                pair.srcToken = collItem;
            map.items.push(pair);
        }
        else {
            // key with no value
            if (implicitKey)
                onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');
            if (valueProps.comment) {
                if (keyNode.comment)
                    keyNode.comment += '\n' + valueProps.comment;
                else
                    keyNode.comment = valueProps.comment;
            }
            const pair = new Pair(keyNode);
            if (ctx.options.keepSourceTokens)
                pair.srcToken = collItem;
            map.items.push(pair);
        }
    }
    if (commentEnd && commentEnd < offset)
        onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');
    map.range = [bm.offset, offset, commentEnd ?? offset];
    return map;
}

function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
    const NodeClass = tag?.nodeClass ?? YAMLSeq;
    const seq = new NodeClass(ctx.schema);
    if (ctx.atRoot)
        ctx.atRoot = false;
    let offset = bs.offset;
    let commentEnd = null;
    for (const { start, value } of bs.items) {
        const props = resolveProps(start, {
            indicator: 'seq-item-ind',
            next: value,
            offset,
            onError,
            parentIndent: bs.indent,
            startOnNewline: true
        });
        if (!props.found) {
            if (props.anchor || props.tag || value) {
                if (value && value.type === 'block-seq')
                    onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');
                else
                    onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');
            }
            else {
                commentEnd = props.end;
                if (props.comment)
                    seq.comment = props.comment;
                continue;
            }
        }
        const node = value
            ? composeNode(ctx, value, props, onError)
            : composeEmptyNode(ctx, props.end, start, null, props, onError);
        if (ctx.schema.compat)
            flowIndentCheck(bs.indent, value, onError);
        offset = node.range[2];
        seq.items.push(node);
    }
    seq.range = [bs.offset, offset, commentEnd ?? offset];
    return seq;
}

function resolveEnd(end, offset, reqSpace, onError) {
    let comment = '';
    if (end) {
        let hasSpace = false;
        let sep = '';
        for (const token of end) {
            const { source, type } = token;
            switch (type) {
                case 'space':
                    hasSpace = true;
                    break;
                case 'comment': {
                    if (reqSpace && !hasSpace)
                        onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
                    const cb = source.substring(1) || ' ';
                    if (!comment)
                        comment = cb;
                    else
                        comment += sep + cb;
                    sep = '';
                    break;
                }
                case 'newline':
                    if (comment)
                        sep += source;
                    hasSpace = true;
                    break;
                default:
                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);
            }
            offset += source.length;
        }
    }
    return { comment, offset };
}

const blockMsg = 'Block collections are not allowed within flow collections';
const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
    const isMap = fc.start.source === '{';
    const fcName = isMap ? 'flow map' : 'flow sequence';
    const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap : YAMLSeq));
    const coll = new NodeClass(ctx.schema);
    coll.flow = true;
    const atRoot = ctx.atRoot;
    if (atRoot)
        ctx.atRoot = false;
    let offset = fc.offset + fc.start.source.length;
    for (let i = 0; i < fc.items.length; ++i) {
        const collItem = fc.items[i];
        const { start, key, sep, value } = collItem;
        const props = resolveProps(start, {
            flow: fcName,
            indicator: 'explicit-key-ind',
            next: key ?? sep?.[0],
            offset,
            onError,
            parentIndent: fc.indent,
            startOnNewline: false
        });
        if (!props.found) {
            if (!props.anchor && !props.tag && !sep && !value) {
                if (i === 0 && props.comma)
                    onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
                else if (i < fc.items.length - 1)
                    onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);
                if (props.comment) {
                    if (coll.comment)
                        coll.comment += '\n' + props.comment;
                    else
                        coll.comment = props.comment;
                }
                offset = props.end;
                continue;
            }
            if (!isMap && ctx.options.strict && containsNewline(key))
                onError(key, // checked by containsNewline()
                'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
        }
        if (i === 0) {
            if (props.comma)
                onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
        }
        else {
            if (!props.comma)
                onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);
            if (props.comment) {
                let prevItemComment = '';
                loop: for (const st of start) {
                    switch (st.type) {
                        case 'comma':
                        case 'space':
                            break;
                        case 'comment':
                            prevItemComment = st.source.substring(1);
                            break loop;
                        default:
                            break loop;
                    }
                }
                if (prevItemComment) {
                    let prev = coll.items[coll.items.length - 1];
                    if (isPair(prev))
                        prev = prev.value ?? prev.key;
                    if (prev.comment)
                        prev.comment += '\n' + prevItemComment;
                    else
                        prev.comment = prevItemComment;
                    props.comment = props.comment.substring(prevItemComment.length + 1);
                }
            }
        }
        if (!isMap && !sep && !props.found) {
            // item is a value in a seq
            // → key & sep are empty, start does not include ? or :
            const valueNode = value
                ? composeNode(ctx, value, props, onError)
                : composeEmptyNode(ctx, props.end, sep, null, props, onError);
            coll.items.push(valueNode);
            offset = valueNode.range[2];
            if (isBlock(value))
                onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
        }
        else {
            // item is a key+value pair
            // key value
            const keyStart = props.end;
            const keyNode = key
                ? composeNode(ctx, key, props, onError)
                : composeEmptyNode(ctx, keyStart, start, null, props, onError);
            if (isBlock(key))
                onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);
            // value properties
            const valueProps = resolveProps(sep ?? [], {
                flow: fcName,
                indicator: 'map-value-ind',
                next: value,
                offset: keyNode.range[2],
                onError,
                parentIndent: fc.indent,
                startOnNewline: false
            });
            if (valueProps.found) {
                if (!isMap && !props.found && ctx.options.strict) {
                    if (sep)
                        for (const st of sep) {
                            if (st === valueProps.found)
                                break;
                            if (st.type === 'newline') {
                                onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
                                break;
                            }
                        }
                    if (props.start < valueProps.found.offset - 1024)
                        onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');
                }
            }
            else if (value) {
                if ('source' in value && value.source && value.source[0] === ':')
                    onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);
                else
                    onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);
            }
            // value value
            const valueNode = value
                ? composeNode(ctx, value, valueProps, onError)
                : valueProps.found
                    ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)
                    : null;
            if (valueNode) {
                if (isBlock(value))
                    onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
            }
            else if (valueProps.comment) {
                if (keyNode.comment)
                    keyNode.comment += '\n' + valueProps.comment;
                else
                    keyNode.comment = valueProps.comment;
            }
            const pair = new Pair(keyNode, valueNode);
            if (ctx.options.keepSourceTokens)
                pair.srcToken = collItem;
            if (isMap) {
                const map = coll;
                if (mapIncludes(ctx, map.items, keyNode))
                    onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
                map.items.push(pair);
            }
            else {
                const map = new YAMLMap(ctx.schema);
                map.flow = true;
                map.items.push(pair);
                coll.items.push(map);
            }
            offset = valueNode ? valueNode.range[2] : valueProps.end;
        }
    }
    const expectedEnd = isMap ? '}' : ']';
    const [ce, ...ee] = fc.end;
    let cePos = offset;
    if (ce && ce.source === expectedEnd)
        cePos = ce.offset + ce.source.length;
    else {
        const name = fcName[0].toUpperCase() + fcName.substring(1);
        const msg = atRoot
            ? `${name} must end with a ${expectedEnd}`
            : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
        onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);
        if (ce && ce.source.length !== 1)
            ee.unshift(ce);
    }
    if (ee.length > 0) {
        const end = resolveEnd(ee, cePos, ctx.options.strict, onError);
        if (end.comment) {
            if (coll.comment)
                coll.comment += '\n' + end.comment;
            else
                coll.comment = end.comment;
        }
        coll.range = [fc.offset, cePos, end.offset];
    }
    else {
        coll.range = [fc.offset, cePos, cePos];
    }
    return coll;
}

function resolveCollection(CN, ctx, token, onError, tagName, tag) {
    const coll = token.type === 'block-map'
        ? resolveBlockMap(CN, ctx, token, onError, tag)
        : token.type === 'block-seq'
            ? resolveBlockSeq(CN, ctx, token, onError, tag)
            : resolveFlowCollection(CN, ctx, token, onError, tag);
    const Coll = coll.constructor;
    // If we got a tagName matching the class, or the tag name is '!',
    // then use the tagName from the node class used to create it.
    if (tagName === '!' || tagName === Coll.tagName) {
        coll.tag = Coll.tagName;
        return coll;
    }
    if (tagName)
        coll.tag = tagName;
    return coll;
}
function composeCollection(CN, ctx, token, tagToken, onError) {
    const tagName = !tagToken
        ? null
        : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
    const expType = token.type === 'block-map'
        ? 'map'
        : token.type === 'block-seq'
            ? 'seq'
            : token.start.source === '{'
                ? 'map'
                : 'seq';
    // shortcut: check if it's a generic YAMLMap or YAMLSeq
    // before jumping into the custom tag logic.
    if (!tagToken ||
        !tagName ||
        tagName === '!' ||
        (tagName === YAMLMap.tagName && expType === 'map') ||
        (tagName === YAMLSeq.tagName && expType === 'seq') ||
        !expType) {
        return resolveCollection(CN, ctx, token, onError, tagName);
    }
    let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);
    if (!tag) {
        const kt = ctx.schema.knownTags[tagName];
        if (kt && kt.collection === expType) {
            ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
            tag = kt;
        }
        else {
            if (kt?.collection) {
                onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true);
            }
            else {
                onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
            }
            return resolveCollection(CN, ctx, token, onError, tagName);
        }
    }
    const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
    const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;
    const node = isNode(res)
        ? res
        : new Scalar(res);
    node.range = coll.range;
    node.tag = tagName;
    if (tag?.format)
        node.format = tag.format;
    return node;
}

function resolveBlockScalar(ctx, scalar, onError) {
    const start = scalar.offset;
    const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
    if (!header)
        return { value: '', type: null, comment: '', range: [start, start, start] };
    const type = header.mode === '>' ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;
    const lines = scalar.source ? splitLines(scalar.source) : [];
    // determine the end of content & start of chomping
    let chompStart = lines.length;
    for (let i = lines.length - 1; i >= 0; --i) {
        const content = lines[i][1];
        if (content === '' || content === '\r')
            chompStart = i;
        else
            break;
    }
    // shortcut for empty contents
    if (chompStart === 0) {
        const value = header.chomp === '+' && lines.length > 0
            ? '\n'.repeat(Math.max(1, lines.length - 1))
            : '';
        let end = start + header.length;
        if (scalar.source)
            end += scalar.source.length;
        return { value, type, comment: header.comment, range: [start, end, end] };
    }
    // find the indentation level to trim from start
    let trimIndent = scalar.indent + header.indent;
    let offset = scalar.offset + header.length;
    let contentStart = 0;
    for (let i = 0; i < chompStart; ++i) {
        const [indent, content] = lines[i];
        if (content === '' || content === '\r') {
            if (header.indent === 0 && indent.length > trimIndent)
                trimIndent = indent.length;
        }
        else {
            if (indent.length < trimIndent) {
                const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
                onError(offset + indent.length, 'MISSING_CHAR', message);
            }
            if (header.indent === 0)
                trimIndent = indent.length;
            contentStart = i;
            if (trimIndent === 0 && !ctx.atRoot) {
                const message = 'Block scalar values in collections must be indented';
                onError(offset, 'BAD_INDENT', message);
            }
            break;
        }
        offset += indent.length + content.length + 1;
    }
    // include trailing more-indented empty lines in content
    for (let i = lines.length - 1; i >= chompStart; --i) {
        if (lines[i][0].length > trimIndent)
            chompStart = i + 1;
    }
    let value = '';
    let sep = '';
    let prevMoreIndented = false;
    // leading whitespace is kept intact
    for (let i = 0; i < contentStart; ++i)
        value += lines[i][0].slice(trimIndent) + '\n';
    for (let i = contentStart; i < chompStart; ++i) {
        let [indent, content] = lines[i];
        offset += indent.length + content.length + 1;
        const crlf = content[content.length - 1] === '\r';
        if (crlf)
            content = content.slice(0, -1);
        /* istanbul ignore if already caught in lexer */
        if (content && indent.length < trimIndent) {
            const src = header.indent
                ? 'explicit indentation indicator'
                : 'first line';
            const message = `Block scalar lines must not be less indented than their ${src}`;
            onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);
            indent = '';
        }
        if (type === Scalar.BLOCK_LITERAL) {
            value += sep + indent.slice(trimIndent) + content;
            sep = '\n';
        }
        else if (indent.length > trimIndent || content[0] === '\t') {
            // more-indented content within a folded block
            if (sep === ' ')
                sep = '\n';
            else if (!prevMoreIndented && sep === '\n')
                sep = '\n\n';
            value += sep + indent.slice(trimIndent) + content;
            sep = '\n';
            prevMoreIndented = true;
        }
        else if (content === '') {
            // empty line
            if (sep === '\n')
                value += '\n';
            else
                sep = '\n';
        }
        else {
            value += sep + content;
            sep = ' ';
            prevMoreIndented = false;
        }
    }
    switch (header.chomp) {
        case '-':
            break;
        case '+':
            for (let i = chompStart; i < lines.length; ++i)
                value += '\n' + lines[i][0].slice(trimIndent);
            if (value[value.length - 1] !== '\n')
                value += '\n';
            break;
        default:
            value += '\n';
    }
    const end = start + header.length + scalar.source.length;
    return { value, type, comment: header.comment, range: [start, end, end] };
}
function parseBlockScalarHeader({ offset, props }, strict, onError) {
    /* istanbul ignore if should not happen */
    if (props[0].type !== 'block-scalar-header') {
        onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');
        return null;
    }
    const { source } = props[0];
    const mode = source[0];
    let indent = 0;
    let chomp = '';
    let error = -1;
    for (let i = 1; i < source.length; ++i) {
        const ch = source[i];
        if (!chomp && (ch === '-' || ch === '+'))
            chomp = ch;
        else {
            const n = Number(ch);
            if (!indent && n)
                indent = n;
            else if (error === -1)
                error = offset + i;
        }
    }
    if (error !== -1)
        onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);
    let hasSpace = false;
    let comment = '';
    let length = source.length;
    for (let i = 1; i < props.length; ++i) {
        const token = props[i];
        switch (token.type) {
            case 'space':
                hasSpace = true;
            // fallthrough
            case 'newline':
                length += token.source.length;
                break;
            case 'comment':
                if (strict && !hasSpace) {
                    const message = 'Comments must be separated from other tokens by white space characters';
                    onError(token, 'MISSING_CHAR', message);
                }
                length += token.source.length;
                comment = token.source.substring(1);
                break;
            case 'error':
                onError(token, 'UNEXPECTED_TOKEN', token.message);
                length += token.source.length;
                break;
            /* istanbul ignore next should not happen */
            default: {
                const message = `Unexpected token in block scalar header: ${token.type}`;
                onError(token, 'UNEXPECTED_TOKEN', message);
                const ts = token.source;
                if (ts && typeof ts === 'string')
                    length += ts.length;
            }
        }
    }
    return { mode, indent, chomp, comment, length };
}
/** @returns Array of lines split up as `[indent, content]` */
function splitLines(source) {
    const split = source.split(/\n( *)/);
    const first = split[0];
    const m = first.match(/^( *)/);
    const line0 = m?.[1]
        ? [m[1], first.slice(m[1].length)]
        : ['', first];
    const lines = [line0];
    for (let i = 1; i < split.length; i += 2)
        lines.push([split[i], split[i + 1]]);
    return lines;
}

function resolveFlowScalar(scalar, strict, onError) {
    const { offset, type, source, end } = scalar;
    let _type;
    let value;
    const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
    switch (type) {
        case 'scalar':
            _type = Scalar.PLAIN;
            value = plainValue(source, _onError);
            break;
        case 'single-quoted-scalar':
            _type = Scalar.QUOTE_SINGLE;
            value = singleQuotedValue(source, _onError);
            break;
        case 'double-quoted-scalar':
            _type = Scalar.QUOTE_DOUBLE;
            value = doubleQuotedValue(source, _onError);
            break;
        /* istanbul ignore next should not happen */
        default:
            onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);
            return {
                value: '',
                type: null,
                comment: '',
                range: [offset, offset + source.length, offset + source.length]
            };
    }
    const valueEnd = offset + source.length;
    const re = resolveEnd(end, valueEnd, strict, onError);
    return {
        value,
        type: _type,
        comment: re.comment,
        range: [offset, valueEnd, re.offset]
    };
}
function plainValue(source, onError) {
    let badChar = '';
    switch (source[0]) {
        /* istanbul ignore next should not happen */
        case '\t':
            badChar = 'a tab character';
            break;
        case ',':
            badChar = 'flow indicator character ,';
            break;
        case '%':
            badChar = 'directive indicator character %';
            break;
        case '|':
        case '>': {
            badChar = `block scalar indicator ${source[0]}`;
            break;
        }
        case '@':
        case '`': {
            badChar = `reserved character ${source[0]}`;
            break;
        }
    }
    if (badChar)
        onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);
    return foldLines(source);
}
function singleQuotedValue(source, onError) {
    if (source[source.length - 1] !== "'" || source.length === 1)
        onError(source.length, 'MISSING_CHAR', "Missing closing 'quote");
    return foldLines(source.slice(1, -1)).replace(/''/g, "'");
}
function foldLines(source) {
    /**
     * The negative lookbehind here and in the `re` RegExp is to
     * prevent causing a polynomial search time in certain cases.
     *
     * The try-catch is for Safari, which doesn't support this yet:
     * https://caniuse.com/js-regexp-lookbehind
     */
    let first, line;
    try {
        first = new RegExp('(.*?)(?<![ \t])[ \t]*\r?\n', 'sy');
        line = new RegExp('[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n', 'sy');
    }
    catch (_) {
        first = /(.*?)[ \t]*\r?\n/sy;
        line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
    }
    let match = first.exec(source);
    if (!match)
        return source;
    let res = match[1];
    let sep = ' ';
    let pos = first.lastIndex;
    line.lastIndex = pos;
    while ((match = line.exec(source))) {
        if (match[1] === '') {
            if (sep === '\n')
                res += sep;
            else
                sep = '\n';
        }
        else {
            res += sep + match[1];
            sep = ' ';
        }
        pos = line.lastIndex;
    }
    const last = /[ \t]*(.*)/sy;
    last.lastIndex = pos;
    match = last.exec(source);
    return res + sep + (match?.[1] ?? '');
}
function doubleQuotedValue(source, onError) {
    let res = '';
    for (let i = 1; i < source.length - 1; ++i) {
        const ch = source[i];
        if (ch === '\r' && source[i + 1] === '\n')
            continue;
        if (ch === '\n') {
            const { fold, offset } = foldNewline(source, i);
            res += fold;
            i = offset;
        }
        else if (ch === '\\') {
            let next = source[++i];
            const cc = escapeCodes[next];
            if (cc)
                res += cc;
            else if (next === '\n') {
                // skip escaped newlines, but still trim the following line
                next = source[i + 1];
                while (next === ' ' || next === '\t')
                    next = source[++i + 1];
            }
            else if (next === '\r' && source[i + 1] === '\n') {
                // skip escaped CRLF newlines, but still trim the following line
                next = source[++i + 1];
                while (next === ' ' || next === '\t')
                    next = source[++i + 1];
            }
            else if (next === 'x' || next === 'u' || next === 'U') {
                const length = { x: 2, u: 4, U: 8 }[next];
                res += parseCharCode(source, i + 1, length, onError);
                i += length;
            }
            else {
                const raw = source.substr(i - 1, 2);
                onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
                res += raw;
            }
        }
        else if (ch === ' ' || ch === '\t') {
            // trim trailing whitespace
            const wsStart = i;
            let next = source[i + 1];
            while (next === ' ' || next === '\t')
                next = source[++i + 1];
            if (next !== '\n' && !(next === '\r' && source[i + 2] === '\n'))
                res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
        }
        else {
            res += ch;
        }
    }
    if (source[source.length - 1] !== '"' || source.length === 1)
        onError(source.length, 'MISSING_CHAR', 'Missing closing "quote');
    return res;
}
/**
 * Fold a single newline into a space, multiple newlines to N - 1 newlines.
 * Presumes `source[offset] === '\n'`
 */
function foldNewline(source, offset) {
    let fold = '';
    let ch = source[offset + 1];
    while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
        if (ch === '\r' && source[offset + 2] !== '\n')
            break;
        if (ch === '\n')
            fold += '\n';
        offset += 1;
        ch = source[offset + 1];
    }
    if (!fold)
        fold = ' ';
    return { fold, offset };
}
const escapeCodes = {
    '0': '\0', // null character
    a: '\x07', // bell character
    b: '\b', // backspace
    e: '\x1b', // escape character
    f: '\f', // form feed
    n: '\n', // line feed
    r: '\r', // carriage return
    t: '\t', // horizontal tab
    v: '\v', // vertical tab
    N: '\u0085', // Unicode next line
    _: '\u00a0', // Unicode non-breaking space
    L: '\u2028', // Unicode line separator
    P: '\u2029', // Unicode paragraph separator
    ' ': ' ',
    '"': '"',
    '/': '/',
    '\\': '\\',
    '\t': '\t'
};
function parseCharCode(source, offset, length, onError) {
    const cc = source.substr(offset, length);
    const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
    const code = ok ? parseInt(cc, 16) : NaN;
    if (isNaN(code)) {
        const raw = source.substr(offset - 2, length + 2);
        onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
        return raw;
    }
    return String.fromCodePoint(code);
}

function composeScalar(ctx, token, tagToken, onError) {
    const { value, type, comment, range } = token.type === 'block-scalar'
        ? resolveBlockScalar(ctx, token, onError)
        : resolveFlowScalar(token, ctx.options.strict, onError);
    const tagName = tagToken
        ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))
        : null;
    const tag = tagToken && tagName
        ? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError)
        : token.type === 'scalar'
            ? findScalarTagByTest(ctx, value, token, onError)
            : ctx.schema[SCALAR];
    let scalar;
    try {
        const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);
        scalar = isScalar(res) ? res : new Scalar(res);
    }
    catch (error) {
        const msg = error instanceof Error ? error.message : String(error);
        onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);
        scalar = new Scalar(value);
    }
    scalar.range = range;
    scalar.source = value;
    if (type)
        scalar.type = type;
    if (tagName)
        scalar.tag = tagName;
    if (tag.format)
        scalar.format = tag.format;
    if (comment)
        scalar.comment = comment;
    return scalar;
}
function findScalarTagByName(schema, value, tagName, tagToken, onError) {
    if (tagName === '!')
        return schema[SCALAR]; // non-specific tag
    const matchWithTest = [];
    for (const tag of schema.tags) {
        if (!tag.collection && tag.tag === tagName) {
            if (tag.default && tag.test)
                matchWithTest.push(tag);
            else
                return tag;
        }
    }
    for (const tag of matchWithTest)
        if (tag.test?.test(value))
            return tag;
    const kt = schema.knownTags[tagName];
    if (kt && !kt.collection) {
        // Ensure that the known tag is available for stringifying,
        // but does not get used by default.
        schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
        return kt;
    }
    onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');
    return schema[SCALAR];
}
function findScalarTagByTest({ directives, schema }, value, token, onError) {
    const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[SCALAR];
    if (schema.compat) {
        const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??
            schema[SCALAR];
        if (tag.tag !== compat.tag) {
            const ts = directives.tagString(tag.tag);
            const cs = directives.tagString(compat.tag);
            const msg = `Value may be parsed as either ${ts} or ${cs}`;
            onError(token, 'TAG_RESOLVE_FAILED', msg, true);
        }
    }
    return tag;
}

function emptyScalarPosition(offset, before, pos) {
    if (before) {
        if (pos === null)
            pos = before.length;
        for (let i = pos - 1; i >= 0; --i) {
            let st = before[i];
            switch (st.type) {
                case 'space':
                case 'comment':
                case 'newline':
                    offset -= st.source.length;
                    continue;
            }
            // Technically, an empty scalar is immediately after the last non-empty
            // node, but it's more useful to place it after any whitespace.
            st = before[++i];
            while (st?.type === 'space') {
                offset += st.source.length;
                st = before[++i];
            }
            break;
        }
    }
    return offset;
}

const CN = { composeNode, composeEmptyNode };
function composeNode(ctx, token, props, onError) {
    const { spaceBefore, comment, anchor, tag } = props;
    let node;
    let isSrcToken = true;
    switch (token.type) {
        case 'alias':
            node = composeAlias(ctx, token, onError);
            if (anchor || tag)
                onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');
            break;
        case 'scalar':
        case 'single-quoted-scalar':
        case 'double-quoted-scalar':
        case 'block-scalar':
            node = composeScalar(ctx, token, tag, onError);
            if (anchor)
                node.anchor = anchor.source.substring(1);
            break;
        case 'block-map':
        case 'block-seq':
        case 'flow-collection':
            node = composeCollection(CN, ctx, token, tag, onError);
            if (anchor)
                node.anchor = anchor.source.substring(1);
            break;
        default: {
            const message = token.type === 'error'
                ? token.message
                : `Unsupported token (type: ${token.type})`;
            onError(token, 'UNEXPECTED_TOKEN', message);
            node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError);
            isSrcToken = false;
        }
    }
    if (anchor && node.anchor === '')
        onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
    if (spaceBefore)
        node.spaceBefore = true;
    if (comment) {
        if (token.type === 'scalar' && token.source === '')
            node.comment = comment;
        else
            node.commentBefore = comment;
    }
    // @ts-expect-error Type checking misses meaning of isSrcToken
    if (ctx.options.keepSourceTokens && isSrcToken)
        node.srcToken = token;
    return node;
}
function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
    const token = {
        type: 'scalar',
        offset: emptyScalarPosition(offset, before, pos),
        indent: -1,
        source: ''
    };
    const node = composeScalar(ctx, token, tag, onError);
    if (anchor) {
        node.anchor = anchor.source.substring(1);
        if (node.anchor === '')
            onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
    }
    if (spaceBefore)
        node.spaceBefore = true;
    if (comment) {
        node.comment = comment;
        node.range[2] = end;
    }
    return node;
}
function composeAlias({ options }, { offset, source, end }, onError) {
    const alias = new Alias(source.substring(1));
    if (alias.source === '')
        onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');
    if (alias.source.endsWith(':'))
        onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);
    const valueEnd = offset + source.length;
    const re = resolveEnd(end, valueEnd, options.strict, onError);
    alias.range = [offset, valueEnd, re.offset];
    if (re.comment)
        alias.comment = re.comment;
    return alias;
}

function composeDoc(options, directives, { offset, start, value, end }, onError) {
    const opts = Object.assign({ _directives: directives }, options);
    const doc = new Document(undefined, opts);
    const ctx = {
        atRoot: true,
        directives: doc.directives,
        options: doc.options,
        schema: doc.schema
    };
    const props = resolveProps(start, {
        indicator: 'doc-start',
        next: value ?? end?.[0],
        offset,
        onError,
        parentIndent: 0,
        startOnNewline: true
    });
    if (props.found) {
        doc.directives.docStart = true;
        if (value &&
            (value.type === 'block-map' || value.type === 'block-seq') &&
            !props.hasNewline)
            onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
    }
    // @ts-expect-error If Contents is set, let's trust the user
    doc.contents = value
        ? composeNode(ctx, value, props, onError)
        : composeEmptyNode(ctx, props.end, start, null, props, onError);
    const contentEnd = doc.contents.range[2];
    const re = resolveEnd(end, contentEnd, false, onError);
    if (re.comment)
        doc.comment = re.comment;
    doc.range = [offset, contentEnd, re.offset];
    return doc;
}

function getErrorPos(src) {
    if (typeof src === 'number')
        return [src, src + 1];
    if (Array.isArray(src))
        return src.length === 2 ? src : [src[0], src[1]];
    const { offset, source } = src;
    return [offset, offset + (typeof source === 'string' ? source.length : 1)];
}
function parsePrelude(prelude) {
    let comment = '';
    let atComment = false;
    let afterEmptyLine = false;
    for (let i = 0; i < prelude.length; ++i) {
        const source = prelude[i];
        switch (source[0]) {
            case '#':
                comment +=
                    (comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') +
                        (source.substring(1) || ' ');
                atComment = true;
                afterEmptyLine = false;
                break;
            case '%':
                if (prelude[i + 1]?.[0] !== '#')
                    i += 1;
                atComment = false;
                break;
            default:
                // This may be wrong after doc-end, but in that case it doesn't matter
                if (!atComment)
                    afterEmptyLine = true;
                atComment = false;
        }
    }
    return { comment, afterEmptyLine };
}
/**
 * Compose a stream of CST nodes into a stream of YAML Documents.
 *
 * ```ts
 * import { Composer, Parser } from 'yaml'
 *
 * const src: string = ...
 * const tokens = new Parser().parse(src)
 * const docs = new Composer().compose(tokens)
 * ```
 */
class Composer {
    constructor(options = {}) {
        this.doc = null;
        this.atDirectives = false;
        this.prelude = [];
        this.errors = [];
        this.warnings = [];
        this.onError = (source, code, message, warning) => {
            const pos = getErrorPos(source);
            if (warning)
                this.warnings.push(new YAMLWarning(pos, code, message));
            else
                this.errors.push(new YAMLParseError(pos, code, message));
        };
        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
        this.directives = new Directives({ version: options.version || '1.2' });
        this.options = options;
    }
    decorate(doc, afterDoc) {
        const { comment, afterEmptyLine } = parsePrelude(this.prelude);
        //console.log({ dc: doc.comment, prelude, comment })
        if (comment) {
            const dc = doc.contents;
            if (afterDoc) {
                doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment;
            }
            else if (afterEmptyLine || doc.directives.docStart || !dc) {
                doc.commentBefore = comment;
            }
            else if (isCollection(dc) && !dc.flow && dc.items.length > 0) {
                let it = dc.items[0];
                if (isPair(it))
                    it = it.key;
                const cb = it.commentBefore;
                it.commentBefore = cb ? `${comment}\n${cb}` : comment;
            }
            else {
                const cb = dc.commentBefore;
                dc.commentBefore = cb ? `${comment}\n${cb}` : comment;
            }
        }
        if (afterDoc) {
            Array.prototype.push.apply(doc.errors, this.errors);
            Array.prototype.push.apply(doc.warnings, this.warnings);
        }
        else {
            doc.errors = this.errors;
            doc.warnings = this.warnings;
        }
        this.prelude = [];
        this.errors = [];
        this.warnings = [];
    }
    /**
     * Current stream status information.
     *
     * Mostly useful at the end of input for an empty stream.
     */
    streamInfo() {
        return {
            comment: parsePrelude(this.prelude).comment,
            directives: this.directives,
            errors: this.errors,
            warnings: this.warnings
        };
    }
    /**
     * Compose tokens into documents.
     *
     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
     */
    *compose(tokens, forceDoc = false, endOffset = -1) {
        for (const token of tokens)
            yield* this.next(token);
        yield* this.end(forceDoc, endOffset);
    }
    /** Advance the composer by one CST token. */
    *next(token) {
        switch (token.type) {
            case 'directive':
                this.directives.add(token.source, (offset, message, warning) => {
                    const pos = getErrorPos(token);
                    pos[0] += offset;
                    this.onError(pos, 'BAD_DIRECTIVE', message, warning);
                });
                this.prelude.push(token.source);
                this.atDirectives = true;
                break;
            case 'document': {
                const doc = composeDoc(this.options, this.directives, token, this.onError);
                if (this.atDirectives && !doc.directives.docStart)
                    this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');
                this.decorate(doc, false);
                if (this.doc)
                    yield this.doc;
                this.doc = doc;
                this.atDirectives = false;
                break;
            }
            case 'byte-order-mark':
            case 'space':
                break;
            case 'comment':
            case 'newline':
                this.prelude.push(token.source);
                break;
            case 'error': {
                const msg = token.source
                    ? `${token.message}: ${JSON.stringify(token.source)}`
                    : token.message;
                const error = new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);
                if (this.atDirectives || !this.doc)
                    this.errors.push(error);
                else
                    this.doc.errors.push(error);
                break;
            }
            case 'doc-end': {
                if (!this.doc) {
                    const msg = 'Unexpected doc-end without preceding document';
                    this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));
                    break;
                }
                this.doc.directives.docEnd = true;
                const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
                this.decorate(this.doc, true);
                if (end.comment) {
                    const dc = this.doc.comment;
                    this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment;
                }
                this.doc.range[2] = end.offset;
                break;
            }
            default:
                this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));
        }
    }
    /**
     * Call at end of input to yield any remaining document.
     *
     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
     */
    *end(forceDoc = false, endOffset = -1) {
        if (this.doc) {
            this.decorate(this.doc, true);
            yield this.doc;
            this.doc = null;
        }
        else if (forceDoc) {
            const opts = Object.assign({ _directives: this.directives }, this.options);
            const doc = new Document(undefined, opts);
            if (this.atDirectives)
                this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');
            doc.range = [0, endOffset, endOffset];
            this.decorate(doc, false);
            yield doc;
        }
    }
}

/**
 * Tracks newlines during parsing in order to provide an efficient API for
 * determining the one-indexed `{ line, col }` position for any offset
 * within the input.
 */
class LineCounter {
    constructor() {
        this.lineStarts = [];
        /**
         * Should be called in ascending order. Otherwise, call
         * `lineCounter.lineStarts.sort()` before calling `linePos()`.
         */
        this.addNewLine = (offset) => this.lineStarts.push(offset);
        /**
         * Performs a binary search and returns the 1-indexed { line, col }
         * position of `offset`. If `line === 0`, `addNewLine` has never been
         * called or `offset` is before the first known newline.
         */
        this.linePos = (offset) => {
            let low = 0;
            let high = this.lineStarts.length;
            while (low < high) {
                const mid = (low + high) >> 1; // Math.floor((low + high) / 2)
                if (this.lineStarts[mid] < offset)
                    low = mid + 1;
                else
                    high = mid;
            }
            if (this.lineStarts[low] === offset)
                return { line: low + 1, col: 1 };
            if (low === 0)
                return { line: 0, col: offset };
            const start = this.lineStarts[low - 1];
            return { line: low, col: offset - start + 1 };
        };
    }
}

function includesToken(list, type) {
    for (let i = 0; i < list.length; ++i)
        if (list[i].type === type)
            return true;
    return false;
}
function findNonEmptyIndex(list) {
    for (let i = 0; i < list.length; ++i) {
        switch (list[i].type) {
            case 'space':
            case 'comment':
            case 'newline':
                break;
            default:
                return i;
        }
    }
    return -1;
}
function isFlowToken(token) {
    switch (token?.type) {
        case 'alias':
        case 'scalar':
        case 'single-quoted-scalar':
        case 'double-quoted-scalar':
        case 'flow-collection':
            return true;
        default:
            return false;
    }
}
function getPrevProps(parent) {
    switch (parent.type) {
        case 'document':
            return parent.start;
        case 'block-map': {
            const it = parent.items[parent.items.length - 1];
            return it.sep ?? it.start;
        }
        case 'block-seq':
            return parent.items[parent.items.length - 1].start;
        /* istanbul ignore next should not happen */
        default:
            return [];
    }
}
/** Note: May modify input array */
function getFirstKeyStartProps(prev) {
    if (prev.length === 0)
        return [];
    let i = prev.length;
    loop: while (--i >= 0) {
        switch (prev[i].type) {
            case 'doc-start':
            case 'explicit-key-ind':
            case 'map-value-ind':
            case 'seq-item-ind':
            case 'newline':
                break loop;
        }
    }
    while (prev[++i]?.type === 'space') {
        /* loop */
    }
    return prev.splice(i, prev.length);
}
function fixFlowSeqItems(fc) {
    if (fc.start.type === 'flow-seq-start') {
        for (const it of fc.items) {
            if (it.sep &&
                !it.value &&
                !includesToken(it.start, 'explicit-key-ind') &&
                !includesToken(it.sep, 'map-value-ind')) {
                if (it.key)
                    it.value = it.key;
                delete it.key;
                if (isFlowToken(it.value)) {
                    if (it.value.end)
                        Array.prototype.push.apply(it.value.end, it.sep);
                    else
                        it.value.end = it.sep;
                }
                else
                    Array.prototype.push.apply(it.start, it.sep);
                delete it.sep;
            }
        }
    }
}
/**
 * A YAML concrete syntax tree (CST) parser
 *
 * ```ts
 * const src: string = ...
 * for (const token of new Parser().parse(src)) {
 *   // token: Token
 * }
 * ```
 *
 * To use the parser with a user-provided lexer:
 *
 * ```ts
 * function* parse(source: string, lexer: Lexer) {
 *   const parser = new Parser()
 *   for (const lexeme of lexer.lex(source))
 *     yield* parser.next(lexeme)
 *   yield* parser.end()
 * }
 *
 * const src: string = ...
 * const lexer = new Lexer()
 * for (const token of parse(src, lexer)) {
 *   // token: Token
 * }
 * ```
 */
class Parser {
    /**
     * @param onNewLine - If defined, called separately with the start position of
     *   each new line (in `parse()`, including the start of input).
     */
    constructor(onNewLine) {
        /** If true, space and sequence indicators count as indentation */
        this.atNewLine = true;
        /** If true, next token is a scalar value */
        this.atScalar = false;
        /** Current indentation level */
        this.indent = 0;
        /** Current offset since the start of parsing */
        this.offset = 0;
        /** On the same line with a block map key */
        this.onKeyLine = false;
        /** Top indicates the node that's currently being built */
        this.stack = [];
        /** The source of the current token, set in parse() */
        this.source = '';
        /** The type of the current token, set in parse() */
        this.type = '';
        // Must be defined after `next()`
        this.lexer = new Lexer();
        this.onNewLine = onNewLine;
    }
    /**
     * Parse `source` as a YAML stream.
     * If `incomplete`, a part of the last line may be left as a buffer for the next call.
     *
     * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
     *
     * @returns A generator of tokens representing each directive, document, and other structure.
     */
    *parse(source, incomplete = false) {
        if (this.onNewLine && this.offset === 0)
            this.onNewLine(0);
        for (const lexeme of this.lexer.lex(source, incomplete))
            yield* this.next(lexeme);
        if (!incomplete)
            yield* this.end();
    }
    /**
     * Advance the parser by the `source` of one lexical token.
     */
    *next(source) {
        this.source = source;
        if (this.atScalar) {
            this.atScalar = false;
            yield* this.step();
            this.offset += source.length;
            return;
        }
        const type = tokenType(source);
        if (!type) {
            const message = `Not a YAML token: ${source}`;
            yield* this.pop({ type: 'error', offset: this.offset, message, source });
            this.offset += source.length;
        }
        else if (type === 'scalar') {
            this.atNewLine = false;
            this.atScalar = true;
            this.type = 'scalar';
        }
        else {
            this.type = type;
            yield* this.step();
            switch (type) {
                case 'newline':
                    this.atNewLine = true;
                    this.indent = 0;
                    if (this.onNewLine)
                        this.onNewLine(this.offset + source.length);
                    break;
                case 'space':
                    if (this.atNewLine && source[0] === ' ')
                        this.indent += source.length;
                    break;
                case 'explicit-key-ind':
                case 'map-value-ind':
                case 'seq-item-ind':
                    if (this.atNewLine)
                        this.indent += source.length;
                    break;
                case 'doc-mode':
                case 'flow-error-end':
                    return;
                default:
                    this.atNewLine = false;
            }
            this.offset += source.length;
        }
    }
    /** Call at end of input to push out any remaining constructions */
    *end() {
        while (this.stack.length > 0)
            yield* this.pop();
    }
    get sourceToken() {
        const st = {
            type: this.type,
            offset: this.offset,
            indent: this.indent,
            source: this.source
        };
        return st;
    }
    *step() {
        const top = this.peek(1);
        if (this.type === 'doc-end' && (!top || top.type !== 'doc-end')) {
            while (this.stack.length > 0)
                yield* this.pop();
            this.stack.push({
                type: 'doc-end',
                offset: this.offset,
                source: this.source
            });
            return;
        }
        if (!top)
            return yield* this.stream();
        switch (top.type) {
            case 'document':
                return yield* this.document(top);
            case 'alias':
            case 'scalar':
            case 'single-quoted-scalar':
            case 'double-quoted-scalar':
                return yield* this.scalar(top);
            case 'block-scalar':
                return yield* this.blockScalar(top);
            case 'block-map':
                return yield* this.blockMap(top);
            case 'block-seq':
                return yield* this.blockSequence(top);
            case 'flow-collection':
                return yield* this.flowCollection(top);
            case 'doc-end':
                return yield* this.documentEnd(top);
        }
        /* istanbul ignore next should not happen */
        yield* this.pop();
    }
    peek(n) {
        return this.stack[this.stack.length - n];
    }
    *pop(error) {
        const token = error ?? this.stack.pop();
        /* istanbul ignore if should not happen */
        if (!token) {
            const message = 'Tried to pop an empty stack';
            yield { type: 'error', offset: this.offset, source: '', message };
        }
        else if (this.stack.length === 0) {
            yield token;
        }
        else {
            const top = this.peek(1);
            if (token.type === 'block-scalar') {
                // Block scalars use their parent rather than header indent
                token.indent = 'indent' in top ? top.indent : 0;
            }
            else if (token.type === 'flow-collection' && top.type === 'document') {
                // Ignore all indent for top-level flow collections
                token.indent = 0;
            }
            if (token.type === 'flow-collection')
                fixFlowSeqItems(token);
            switch (top.type) {
                case 'document':
                    top.value = token;
                    break;
                case 'block-scalar':
                    top.props.push(token); // error
                    break;
                case 'block-map': {
                    const it = top.items[top.items.length - 1];
                    if (it.value) {
                        top.items.push({ start: [], key: token, sep: [] });
                        this.onKeyLine = true;
                        return;
                    }
                    else if (it.sep) {
                        it.value = token;
                    }
                    else {
                        Object.assign(it, { key: token, sep: [] });
                        this.onKeyLine = !it.explicitKey;
                        return;
                    }
                    break;
                }
                case 'block-seq': {
                    const it = top.items[top.items.length - 1];
                    if (it.value)
                        top.items.push({ start: [], value: token });
                    else
                        it.value = token;
                    break;
                }
                case 'flow-collection': {
                    const it = top.items[top.items.length - 1];
                    if (!it || it.value)
                        top.items.push({ start: [], key: token, sep: [] });
                    else if (it.sep)
                        it.value = token;
                    else
                        Object.assign(it, { key: token, sep: [] });
                    return;
                }
                /* istanbul ignore next should not happen */
                default:
                    yield* this.pop();
                    yield* this.pop(token);
            }
            if ((top.type === 'document' ||
                top.type === 'block-map' ||
                top.type === 'block-seq') &&
                (token.type === 'block-map' || token.type === 'block-seq')) {
                const last = token.items[token.items.length - 1];
                if (last &&
                    !last.sep &&
                    !last.value &&
                    last.start.length > 0 &&
                    findNonEmptyIndex(last.start) === -1 &&
                    (token.indent === 0 ||
                        last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {
                    if (top.type === 'document')
                        top.end = last.start;
                    else
                        top.items.push({ start: last.start });
                    token.items.splice(-1, 1);
                }
            }
        }
    }
    *stream() {
        switch (this.type) {
            case 'directive-line':
                yield { type: 'directive', offset: this.offset, source: this.source };
                return;
            case 'byte-order-mark':
            case 'space':
            case 'comment':
            case 'newline':
                yield this.sourceToken;
                return;
            case 'doc-mode':
            case 'doc-start': {
                const doc = {
                    type: 'document',
                    offset: this.offset,
                    start: []
                };
                if (this.type === 'doc-start')
                    doc.start.push(this.sourceToken);
                this.stack.push(doc);
                return;
            }
        }
        yield {
            type: 'error',
            offset: this.offset,
            message: `Unexpected ${this.type} token in YAML stream`,
            source: this.source
        };
    }
    *document(doc) {
        if (doc.value)
            return yield* this.lineEnd(doc);
        switch (this.type) {
            case 'doc-start': {
                if (findNonEmptyIndex(doc.start) !== -1) {
                    yield* this.pop();
                    yield* this.step();
                }
                else
                    doc.start.push(this.sourceToken);
                return;
            }
            case 'anchor':
            case 'tag':
            case 'space':
            case 'comment':
            case 'newline':
                doc.start.push(this.sourceToken);
                return;
        }
        const bv = this.startBlockValue(doc);
        if (bv)
            this.stack.push(bv);
        else {
            yield {
                type: 'error',
                offset: this.offset,
                message: `Unexpected ${this.type} token in YAML document`,
                source: this.source
            };
        }
    }
    *scalar(scalar) {
        if (this.type === 'map-value-ind') {
            const prev = getPrevProps(this.peek(2));
            const start = getFirstKeyStartProps(prev);
            let sep;
            if (scalar.end) {
                sep = scalar.end;
                sep.push(this.sourceToken);
                delete scalar.end;
            }
            else
                sep = [this.sourceToken];
            const map = {
                type: 'block-map',
                offset: scalar.offset,
                indent: scalar.indent,
                items: [{ start, key: scalar, sep }]
            };
            this.onKeyLine = true;
            this.stack[this.stack.length - 1] = map;
        }
        else
            yield* this.lineEnd(scalar);
    }
    *blockScalar(scalar) {
        switch (this.type) {
            case 'space':
            case 'comment':
            case 'newline':
                scalar.props.push(this.sourceToken);
                return;
            case 'scalar':
                scalar.source = this.source;
                // block-scalar source includes trailing newline
                this.atNewLine = true;
                this.indent = 0;
                if (this.onNewLine) {
                    let nl = this.source.indexOf('\n') + 1;
                    while (nl !== 0) {
                        this.onNewLine(this.offset + nl);
                        nl = this.source.indexOf('\n', nl) + 1;
                    }
                }
                yield* this.pop();
                break;
            /* istanbul ignore next should not happen */
            default:
                yield* this.pop();
                yield* this.step();
        }
    }
    *blockMap(map) {
        const it = map.items[map.items.length - 1];
        // it.sep is true-ish if pair already has key or : separator
        switch (this.type) {
            case 'newline':
                this.onKeyLine = false;
                if (it.value) {
                    const end = 'end' in it.value ? it.value.end : undefined;
                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;
                    if (last?.type === 'comment')
                        end?.push(this.sourceToken);
                    else
                        map.items.push({ start: [this.sourceToken] });
                }
                else if (it.sep) {
                    it.sep.push(this.sourceToken);
                }
                else {
                    it.start.push(this.sourceToken);
                }
                return;
            case 'space':
            case 'comment':
                if (it.value) {
                    map.items.push({ start: [this.sourceToken] });
                }
                else if (it.sep) {
                    it.sep.push(this.sourceToken);
                }
                else {
                    if (this.atIndentedComment(it.start, map.indent)) {
                        const prev = map.items[map.items.length - 2];
                        const end = prev?.value?.end;
                        if (Array.isArray(end)) {
                            Array.prototype.push.apply(end, it.start);
                            end.push(this.sourceToken);
                            map.items.pop();
                            return;
                        }
                    }
                    it.start.push(this.sourceToken);
                }
                return;
        }
        if (this.indent >= map.indent) {
            const atMapIndent = !this.onKeyLine && this.indent === map.indent;
            const atNextItem = atMapIndent &&
                (it.sep || it.explicitKey) &&
                this.type !== 'seq-item-ind';
            // For empty nodes, assign newline-separated not indented empty tokens to following node
            let start = [];
            if (atNextItem && it.sep && !it.value) {
                const nl = [];
                for (let i = 0; i < it.sep.length; ++i) {
                    const st = it.sep[i];
                    switch (st.type) {
                        case 'newline':
                            nl.push(i);
                            break;
                        case 'space':
                            break;
                        case 'comment':
                            if (st.indent > map.indent)
                                nl.length = 0;
                            break;
                        default:
                            nl.length = 0;
                    }
                }
                if (nl.length >= 2)
                    start = it.sep.splice(nl[1]);
            }
            switch (this.type) {
                case 'anchor':
                case 'tag':
                    if (atNextItem || it.value) {
                        start.push(this.sourceToken);
                        map.items.push({ start });
                        this.onKeyLine = true;
                    }
                    else if (it.sep) {
                        it.sep.push(this.sourceToken);
                    }
                    else {
                        it.start.push(this.sourceToken);
                    }
                    return;
                case 'explicit-key-ind':
                    if (!it.sep && !it.explicitKey) {
                        it.start.push(this.sourceToken);
                        it.explicitKey = true;
                    }
                    else if (atNextItem || it.value) {
                        start.push(this.sourceToken);
                        map.items.push({ start, explicitKey: true });
                    }
                    else {
                        this.stack.push({
                            type: 'block-map',
                            offset: this.offset,
                            indent: this.indent,
                            items: [{ start: [this.sourceToken], explicitKey: true }]
                        });
                    }
                    this.onKeyLine = true;
                    return;
                case 'map-value-ind':
                    if (it.explicitKey) {
                        if (!it.sep) {
                            if (includesToken(it.start, 'newline')) {
                                Object.assign(it, { key: null, sep: [this.sourceToken] });
                            }
                            else {
                                const start = getFirstKeyStartProps(it.start);
                                this.stack.push({
                                    type: 'block-map',
                                    offset: this.offset,
                                    indent: this.indent,
                                    items: [{ start, key: null, sep: [this.sourceToken] }]
                                });
                            }
                        }
                        else if (it.value) {
                            map.items.push({ start: [], key: null, sep: [this.sourceToken] });
                        }
                        else if (includesToken(it.sep, 'map-value-ind')) {
                            this.stack.push({
                                type: 'block-map',
                                offset: this.offset,
                                indent: this.indent,
                                items: [{ start, key: null, sep: [this.sourceToken] }]
                            });
                        }
                        else if (isFlowToken(it.key) &&
                            !includesToken(it.sep, 'newline')) {
                            const start = getFirstKeyStartProps(it.start);
                            const key = it.key;
                            const sep = it.sep;
                            sep.push(this.sourceToken);
                            // @ts-expect-error type guard is wrong here
                            delete it.key, delete it.sep;
                            this.stack.push({
                                type: 'block-map',
                                offset: this.offset,
                                indent: this.indent,
                                items: [{ start, key, sep }]
                            });
                        }
                        else if (start.length > 0) {
                            // Not actually at next item
                            it.sep = it.sep.concat(start, this.sourceToken);
                        }
                        else {
                            it.sep.push(this.sourceToken);
                        }
                    }
                    else {
                        if (!it.sep) {
                            Object.assign(it, { key: null, sep: [this.sourceToken] });
                        }
                        else if (it.value || atNextItem) {
                            map.items.push({ start, key: null, sep: [this.sourceToken] });
                        }
                        else if (includesToken(it.sep, 'map-value-ind')) {
                            this.stack.push({
                                type: 'block-map',
                                offset: this.offset,
                                indent: this.indent,
                                items: [{ start: [], key: null, sep: [this.sourceToken] }]
                            });
                        }
                        else {
                            it.sep.push(this.sourceToken);
                        }
                    }
                    this.onKeyLine = true;
                    return;
                case 'alias':
                case 'scalar':
                case 'single-quoted-scalar':
                case 'double-quoted-scalar': {
                    const fs = this.flowScalar(this.type);
                    if (atNextItem || it.value) {
                        map.items.push({ start, key: fs, sep: [] });
                        this.onKeyLine = true;
                    }
                    else if (it.sep) {
                        this.stack.push(fs);
                    }
                    else {
                        Object.assign(it, { key: fs, sep: [] });
                        this.onKeyLine = true;
                    }
                    return;
                }
                default: {
                    const bv = this.startBlockValue(map);
                    if (bv) {
                        if (atMapIndent && bv.type !== 'block-seq') {
                            map.items.push({ start });
                        }
                        this.stack.push(bv);
                        return;
                    }
                }
            }
        }
        yield* this.pop();
        yield* this.step();
    }
    *blockSequence(seq) {
        const it = seq.items[seq.items.length - 1];
        switch (this.type) {
            case 'newline':
                if (it.value) {
                    const end = 'end' in it.value ? it.value.end : undefined;
                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;
                    if (last?.type === 'comment')
                        end?.push(this.sourceToken);
                    else
                        seq.items.push({ start: [this.sourceToken] });
                }
                else
                    it.start.push(this.sourceToken);
                return;
            case 'space':
            case 'comment':
                if (it.value)
                    seq.items.push({ start: [this.sourceToken] });
                else {
                    if (this.atIndentedComment(it.start, seq.indent)) {
                        const prev = seq.items[seq.items.length - 2];
                        const end = prev?.value?.end;
                        if (Array.isArray(end)) {
                            Array.prototype.push.apply(end, it.start);
                            end.push(this.sourceToken);
                            seq.items.pop();
                            return;
                        }
                    }
                    it.start.push(this.sourceToken);
                }
                return;
            case 'anchor':
            case 'tag':
                if (it.value || this.indent <= seq.indent)
                    break;
                it.start.push(this.sourceToken);
                return;
            case 'seq-item-ind':
                if (this.indent !== seq.indent)
                    break;
                if (it.value || includesToken(it.start, 'seq-item-ind'))
                    seq.items.push({ start: [this.sourceToken] });
                else
                    it.start.push(this.sourceToken);
                return;
        }
        if (this.indent > seq.indent) {
            const bv = this.startBlockValue(seq);
            if (bv) {
                this.stack.push(bv);
                return;
            }
        }
        yield* this.pop();
        yield* this.step();
    }
    *flowCollection(fc) {
        const it = fc.items[fc.items.length - 1];
        if (this.type === 'flow-error-end') {
            let top;
            do {
                yield* this.pop();
                top = this.peek(1);
            } while (top && top.type === 'flow-collection');
        }
        else if (fc.end.length === 0) {
            switch (this.type) {
                case 'comma':
                case 'explicit-key-ind':
                    if (!it || it.sep)
                        fc.items.push({ start: [this.sourceToken] });
                    else
                        it.start.push(this.sourceToken);
                    return;
                case 'map-value-ind':
                    if (!it || it.value)
                        fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
                    else if (it.sep)
                        it.sep.push(this.sourceToken);
                    else
                        Object.assign(it, { key: null, sep: [this.sourceToken] });
                    return;
                case 'space':
                case 'comment':
                case 'newline':
                case 'anchor':
                case 'tag':
                    if (!it || it.value)
                        fc.items.push({ start: [this.sourceToken] });
                    else if (it.sep)
                        it.sep.push(this.sourceToken);
                    else
                        it.start.push(this.sourceToken);
                    return;
                case 'alias':
                case 'scalar':
                case 'single-quoted-scalar':
                case 'double-quoted-scalar': {
                    const fs = this.flowScalar(this.type);
                    if (!it || it.value)
                        fc.items.push({ start: [], key: fs, sep: [] });
                    else if (it.sep)
                        this.stack.push(fs);
                    else
                        Object.assign(it, { key: fs, sep: [] });
                    return;
                }
                case 'flow-map-end':
                case 'flow-seq-end':
                    fc.end.push(this.sourceToken);
                    return;
            }
            const bv = this.startBlockValue(fc);
            /* istanbul ignore else should not happen */
            if (bv)
                this.stack.push(bv);
            else {
                yield* this.pop();
                yield* this.step();
            }
        }
        else {
            const parent = this.peek(2);
            if (parent.type === 'block-map' &&
                ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||
                    (this.type === 'newline' &&
                        !parent.items[parent.items.length - 1].sep))) {
                yield* this.pop();
                yield* this.step();
            }
            else if (this.type === 'map-value-ind' &&
                parent.type !== 'flow-collection') {
                const prev = getPrevProps(parent);
                const start = getFirstKeyStartProps(prev);
                fixFlowSeqItems(fc);
                const sep = fc.end.splice(1, fc.end.length);
                sep.push(this.sourceToken);
                const map = {
                    type: 'block-map',
                    offset: fc.offset,
                    indent: fc.indent,
                    items: [{ start, key: fc, sep }]
                };
                this.onKeyLine = true;
                this.stack[this.stack.length - 1] = map;
            }
            else {
                yield* this.lineEnd(fc);
            }
        }
    }
    flowScalar(type) {
        if (this.onNewLine) {
            let nl = this.source.indexOf('\n') + 1;
            while (nl !== 0) {
                this.onNewLine(this.offset + nl);
                nl = this.source.indexOf('\n', nl) + 1;
            }
        }
        return {
            type,
            offset: this.offset,
            indent: this.indent,
            source: this.source
        };
    }
    startBlockValue(parent) {
        switch (this.type) {
            case 'alias':
            case 'scalar':
            case 'single-quoted-scalar':
            case 'double-quoted-scalar':
                return this.flowScalar(this.type);
            case 'block-scalar-header':
                return {
                    type: 'block-scalar',
                    offset: this.offset,
                    indent: this.indent,
                    props: [this.sourceToken],
                    source: ''
                };
            case 'flow-map-start':
            case 'flow-seq-start':
                return {
                    type: 'flow-collection',
                    offset: this.offset,
                    indent: this.indent,
                    start: this.sourceToken,
                    items: [],
                    end: []
                };
            case 'seq-item-ind':
                return {
                    type: 'block-seq',
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start: [this.sourceToken] }]
                };
            case 'explicit-key-ind': {
                this.onKeyLine = true;
                const prev = getPrevProps(parent);
                const start = getFirstKeyStartProps(prev);
                start.push(this.sourceToken);
                return {
                    type: 'block-map',
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start, explicitKey: true }]
                };
            }
            case 'map-value-ind': {
                this.onKeyLine = true;
                const prev = getPrevProps(parent);
                const start = getFirstKeyStartProps(prev);
                return {
                    type: 'block-map',
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start, key: null, sep: [this.sourceToken] }]
                };
            }
        }
        return null;
    }
    atIndentedComment(start, indent) {
        if (this.type !== 'comment')
            return false;
        if (this.indent <= indent)
            return false;
        return start.every(st => st.type === 'newline' || st.type === 'space');
    }
    *documentEnd(docEnd) {
        if (this.type !== 'doc-mode') {
            if (docEnd.end)
                docEnd.end.push(this.sourceToken);
            else
                docEnd.end = [this.sourceToken];
            if (this.type === 'newline')
                yield* this.pop();
        }
    }
    *lineEnd(token) {
        switch (this.type) {
            case 'comma':
            case 'doc-start':
            case 'doc-end':
            case 'flow-seq-end':
            case 'flow-map-end':
            case 'map-value-ind':
                yield* this.pop();
                yield* this.step();
                break;
            case 'newline':
                this.onKeyLine = false;
            // fallthrough
            case 'space':
            case 'comment':
            default:
                // all other values are errors
                if (token.end)
                    token.end.push(this.sourceToken);
                else
                    token.end = [this.sourceToken];
                if (this.type === 'newline')
                    yield* this.pop();
        }
    }
}

function parseOptions(options) {
    const prettyErrors = options.prettyErrors !== false;
    const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null;
    return { lineCounter, prettyErrors };
}
/** Parse an input string into a single YAML.Document */
function parseDocument(source, options = {}) {
    const { lineCounter, prettyErrors } = parseOptions(options);
    const parser = new Parser(lineCounter?.addNewLine);
    const composer = new Composer(options);
    // `doc` is always set by compose.end(true) at the very latest
    let doc = null;
    for (const _doc of composer.compose(parser.parse(source), true, source.length)) {
        if (!doc)
            doc = _doc;
        else if (doc.options.logLevel !== 'silent') {
            doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));
            break;
        }
    }
    if (prettyErrors && lineCounter) {
        doc.errors.forEach(prettifyError(source, lineCounter));
        doc.warnings.forEach(prettifyError(source, lineCounter));
    }
    return doc;
}

function parseYaml(source) {
    const diagnostics = createDiagnosticCollector();
    const file = typeof source === "string" ? createSourceFile(source, "<anonymous file>") : source;
    const doc = parseDocument(file.text, {
        prettyErrors: false, // We are handling the error display ourself to be consistent in the style.
    });
    for (const error of doc.errors) {
        diagnostics.add(convertYamlErrorToDiagnostic("error", error, file));
    }
    for (const warning of doc.warnings) {
        diagnostics.add(convertYamlErrorToDiagnostic("warning", warning, file));
    }
    return diagnostics.wrap({
        kind: "yaml-script",
        file,
        value: doc.toJSON(),
        doc,
    });
}
function convertYamlErrorToDiagnostic(severity, error, file) {
    return {
        code: `yaml-${error.code.toLowerCase().replace(/_/g, "-")}`,
        message: error.message,
        severity,
        target: { file, pos: error.pos[0], end: error.pos[1] },
    };
}

const emitterOptionsSchema = {
    type: "object",
    additionalProperties: true,
    required: [],
    properties: {
        "emitter-output-dir": { type: "string", nullable: true },
    },
};
const TypeSpecConfigJsonSchema = {
    type: "object",
    additionalProperties: false,
    properties: {
        extends: {
            type: "string",
            nullable: true,
        },
        "environment-variables": {
            type: "object",
            nullable: true,
            required: [],
            additionalProperties: {
                type: "object",
                properties: {
                    default: { type: "string" },
                },
                required: ["default"],
            },
        },
        parameters: {
            type: "object",
            nullable: true,
            required: [],
            additionalProperties: {
                type: "object",
                properties: {
                    default: { type: "string" },
                },
                required: ["default"],
            },
        },
        "output-dir": {
            type: "string",
            nullable: true,
        },
        "warn-as-error": {
            type: "boolean",
            nullable: true,
        },
        trace: {
            oneOf: [
                { type: "string" },
                {
                    type: "array",
                    items: { type: "string" },
                },
            ],
        }, // Issue with AJV optional property typing https://github.com/ajv-validator/ajv/issues/1664
        imports: {
            type: "array",
            nullable: true,
            items: { type: "string" },
        },
        emit: {
            type: "array",
            nullable: true,
            items: { type: "string" },
        },
        options: {
            type: "object",
            nullable: true,
            required: [],
            additionalProperties: emitterOptionsSchema,
        },
        emitters: {
            type: "object",
            nullable: true,
            required: [],
            additionalProperties: {
                oneOf: [{ type: "boolean" }, emitterOptionsSchema],
            },
        },
        linter: {
            type: "object",
            nullable: true,
            required: [],
            additionalProperties: false,
            properties: {
                extends: {
                    type: "array",
                    nullable: true,
                    items: { type: "string" },
                },
                enable: {
                    type: "object",
                    required: [],
                    nullable: true,
                    additionalProperties: { type: "boolean" },
                },
                disable: {
                    type: "object",
                    required: [],
                    nullable: true,
                    additionalProperties: { type: "string" },
                },
            },
        }, // ajv type system doesn't like the string templates
    },
};

const OldTypeSpecConfigFilename = "cadl-project.yaml";
const TypeSpecConfigFilename = "tspconfig.yaml";
const defaultConfig = deepFreeze({
    outputDir: "{cwd}/tsp-output",
    diagnostics: [],
});
/**
 * Look for the project root by looking up until a `tspconfig.yaml` is found.
 * @param path Path to the file or the folder to start looking
 */
async function findTypeSpecConfigPath(host, path, lookup = true) {
    // if the path is a file, return immediately
    const stats = await doIO(() => host.stat(path), path, () => { }, { allowFileNotFound: true });
    if (!stats) {
        return undefined;
    }
    else if (stats.isFile()) {
        return path;
    }
    let current = path;
    // only recurse if the path is a directory and the flag was set to true (only for default case)
    // otherwise, look in the specific directory for tspconfig.yaml ONLY (not cadl-project.yaml)
    if (!lookup) {
        current = `${path}/tspconfig.yaml`;
        const stats = await doIO(() => host.stat(current), current, () => { }, { allowFileNotFound: true });
        if (stats?.isFile()) {
            return current;
        }
        return undefined;
    }
    else {
        while (true) {
            let pkgPath = await searchConfigFile(host, current, TypeSpecConfigFilename);
            if (pkgPath === undefined) {
                pkgPath = await searchConfigFile(host, current, OldTypeSpecConfigFilename);
            }
            // if found either file in current folder, return it
            if (pkgPath !== undefined) {
                return pkgPath;
            }
            const parent = getDirectoryPath(current);
            if (parent === current) {
                return undefined;
            }
            current = parent;
        }
    }
}
/**
 * Load the TypeSpec configuration for the provided path or directory
 * @param host
 * @param path
 */
async function loadTypeSpecConfigForPath(host, path, errorIfNotFound = false, lookup = true) {
    const typespecConfigPath = await findTypeSpecConfigPath(host, path, lookup);
    if (typespecConfigPath === undefined) {
        const projectRoot = getDirectoryPath(path);
        const tsConfig = { ...deepClone(defaultConfig), projectRoot: projectRoot };
        if (errorIfNotFound) {
            tsConfig.diagnostics.push(createDiagnostic({
                code: "config-path-not-found",
                format: {
                    path: path,
                },
                target: NoTarget,
            }));
        }
        return tsConfig;
    }
    const tsConfig = await loadTypeSpecConfigFile(host, typespecConfigPath);
    // Add diagnostics if still using cadl-project.yaml
    if (typespecConfigPath.endsWith(OldTypeSpecConfigFilename)) {
        tsConfig.diagnostics.push(createDiagnostic({
            code: "deprecated",
            format: {
                message: "`cadl-project.yaml` is deprecated. Please rename to `tspconfig.yaml`.",
            },
            target: NoTarget,
        }));
    }
    return tsConfig;
}
/**
 * Load given file as a TypeSpec configuration
 */
async function loadTypeSpecConfigFile(host, filePath) {
    const config = await loadConfigFile(host, filePath, parseYaml);
    if (config.diagnostics.length === 0 && config.extends) {
        const extendPath = resolvePath(getDirectoryPath(filePath), config.extends);
        const parent = await loadTypeSpecConfigFile(host, extendPath);
        // Add diagnostics if still using cadl-project.yaml
        if (filePath.endsWith(OldTypeSpecConfigFilename)) {
            parent.diagnostics.push(createDiagnostic({
                code: "deprecated",
                format: {
                    message: "`cadl-project.yaml` is deprecated. Please rename to `tspconfig.yaml`.",
                },
                target: NoTarget,
            }));
        }
        if (parent.diagnostics.length > 0) {
            return {
                ...config,
                diagnostics: parent.diagnostics,
            };
        }
        return {
            ...parent,
            ...config,
        };
    }
    return {
        ...deepClone(defaultConfig),
        ...config,
    };
}
const configValidator = createJSONSchemaValidator(TypeSpecConfigJsonSchema);
async function searchConfigFile(host, path, filename) {
    const pkgPath = joinPaths(path, filename);
    const stat = await doIO(() => host.stat(pkgPath), pkgPath, () => { });
    return stat?.isFile() === true ? pkgPath : undefined;
}
async function loadConfigFile(host, filename, loadData) {
    let diagnostics = [];
    const reportDiagnostic = (d) => diagnostics.push(d);
    const file = (await doIO(host.readFile, filename, reportDiagnostic)) ?? createSourceFile("", filename);
    const [yamlScript, yamlDiagnostics] = loadData(file);
    yamlDiagnostics.forEach((d) => reportDiagnostic(d));
    let data = yamlScript.value;
    if (data) {
        diagnostics = diagnostics.concat(configValidator.validate(data, yamlScript));
    }
    if (!data || diagnostics.length > 0) {
        // NOTE: Don't trust the data if there are errors and use default
        // config. Otherwise, we may return an object that does not conform to
        // TypeSpecConfig's typing.
        data = deepClone(defaultConfig);
    }
    const emit = data.emit;
    const options = data.options;
    return omitUndefined({
        projectRoot: getDirectoryPath(filename),
        file: yamlScript,
        filename,
        diagnostics,
        extends: data.extends,
        environmentVariables: data["environment-variables"],
        parameters: data.parameters,
        outputDir: data["output-dir"] ?? "{cwd}/tsp-output",
        warnAsError: data["warn-as-error"],
        imports: data.imports,
        trace: typeof data.trace === "string" ? [data.trace] : data.trace,
        emit,
        options,
        linter: data.linter,
    });
}
function validateConfigPathsAbsolute(config) {
    const diagnostics = [];
    function checkPath(value, path) {
        if (value === undefined) {
            return;
        }
        const diagnostic = validatePathAbsolute(value, config.file ? { file: config.file, path } : NoTarget);
        if (diagnostic) {
            diagnostics.push(diagnostic);
        }
    }
    checkPath(config.outputDir, ["output-dir"]);
    for (const [emitterName, emitterOptions] of Object.entries(config.options ?? {})) {
        checkPath(emitterOptions["emitter-output-dir"], ["options", emitterName, "emitter-output-dir"]);
    }
    return diagnostics;
}
function validatePathAbsolute(path, target) {
    if (path.startsWith(".") || !isPathAbsolute(path)) {
        return createDiagnostic({
            code: "config-path-absolute",
            format: { path },
            target: target === NoTarget ? target : getLocationInYamlScript(target.file, target.path),
        });
    }
    return undefined;
}

/**
 * Validate the decorator target is matching the expected value.
 * @param context
 * @param target
 * @param decoratorName
 * @param expectedType
 * @returns
 */
function validateDecoratorTarget(context, target, decoratorName, expectedType) {
    const isCorrectType = isTypeSpecValueTypeOf(target, expectedType);
    if (!isCorrectType) {
        reportDiagnostic(context.program, {
            code: "decorator-wrong-target",
            format: {
                decorator: decoratorName,
                to: target.kind,
            },
            target: context.decoratorTarget,
        });
        return false;
    }
    return true;
}
function isIntrinsicType(program, type, kind) {
    return ignoreDiagnostics(program.checker.isTypeAssignableTo(type.projectionBase ?? type, program.checker.getStdType(kind), type));
}
/**
 * @deprecated this function is deprecated use decorator definition in TypeSpec instead or check assignability directly.
 */
function validateDecoratorTargetIntrinsic(context, target, decoratorName, expectedType) {
    const expectedTypeStrs = typeof expectedType === "string" ? [expectedType] : expectedType;
    const expectedTypes = expectedTypeStrs.map((x) => context.program.checker.getStdType(x));
    const type = getPropertyType(target);
    const isCorrect = expectedTypes.some((x) => context.program.checker.isTypeAssignableTo(type, x, type)[0]);
    if (!isCorrect) {
        context.program.reportDiagnostic(createDiagnostic({
            code: "decorator-wrong-target",
            format: {
                decorator: decoratorName,
                to: `type it is not one of: ${expectedTypeStrs.join(", ")}`,
            },
            target: context.decoratorTarget,
        }));
        return false;
    }
    return true;
}
/** @deprecated use isTypeSpecValueTypeOf */
const isCadlValueTypeOf = isTypeSpecValueTypeOf;
/**
 * Check if the given target is of any of the TypeSpec types.
 * @param target Target to validate.
 * @param expectedType One or multiple allowed TypeSpec types.
 * @returns boolean if the target is of one of the allowed types.
 */
function isTypeSpecValueTypeOf(target, expectedType) {
    const kind = getTypeKind(target);
    if (kind === undefined) {
        return false;
    }
    return typeof expectedType === "string"
        ? expectedType === "Any" || kind === expectedType
        : expectedType.includes("Any") || expectedType.includes(kind);
}
function getTypeKind(target) {
    switch (typeof target) {
        case "object":
            return target.kind;
        case "string":
            return "String";
        case "number":
            return "Number";
        case "boolean":
            return "Boolean";
        default:
            return undefined;
    }
}
/**
 * Validate a decorator parameter has the correct type.
 * @param program Program
 * @param target Decorator target
 * @param value Value of the parameter.
 * @param expectedType Expected type or list of expected type
 * @returns true if the value is of one of the type in the list of expected types. If not emit a diagnostic.
 * @deprecated use @see createDecoratorDefinition#validate instead.
 */
function validateDecoratorParamType(program, target, value, expectedType) {
    if (!isTypeSpecValueTypeOf(value, expectedType)) {
        reportDiagnostic(program, {
            code: "invalid-argument",
            format: {
                value: prettyValue(program, value),
                expected: typeof expectedType === "string" ? expectedType : expectedType.join(", "),
            },
            target,
        });
        return false;
    }
    return true;
}
/**
 * @deprecated use extern dec definition in TypeSpec instead.
 */
function createDecoratorDefinition(definition) {
    const minParams = definition.args.filter((x) => !x.optional).length;
    const maxParams = definition.spreadArgs ? undefined : definition.args.length;
    function validate(context, target, args) {
        if (!validateDecoratorTarget(context, target, definition.name, definition.target) ||
            !validateDecoratorParamCount(context, minParams, maxParams, args)) {
            return false;
        }
        for (const [index, arg] of args.entries()) {
            const paramDefinition = definition.args[index] ?? definition.spreadArgs;
            if (arg === undefined) {
                if (!paramDefinition.optional) {
                    reportDiagnostic(context.program, {
                        code: "invalid-argument",
                        format: {
                            value: "undefined",
                            expected: expectedTypeList(paramDefinition.kind),
                        },
                        target: context.getArgumentTarget(index),
                    });
                    return false;
                }
            }
            else if (!isTypeSpecValueTypeOf(arg, paramDefinition.kind)) {
                reportDiagnostic(context.program, {
                    code: "invalid-argument",
                    format: {
                        value: prettyValue(context.program, arg),
                        expected: expectedTypeList(paramDefinition.kind),
                    },
                    target: context.getArgumentTarget(index),
                });
                return false;
            }
        }
        return true;
    }
    return {
        validate(context, target, parameters) {
            return validate(context, target, parameters);
        },
    };
}
function expectedTypeList(expectedType) {
    return typeof expectedType === "string" ? expectedType : expectedType.join(", ");
}
function validateDecoratorParamCount(context, min, max, parameters) {
    let missing = 0;
    for (let i = parameters.length - 1; i >= 0; i--) {
        if (parameters[i] === undefined) {
            missing++;
        }
        else {
            break;
        }
    }
    const parameterCount = parameters.length - missing;
    if (parameterCount < min || (max !== undefined && parameterCount > max)) {
        if (min === max) {
            reportDiagnostic(context.program, {
                code: "invalid-argument-count",
                format: {
                    actual: parameterCount.toString(),
                    expected: min.toString(),
                },
                target: context.decoratorTarget,
            });
        }
        else {
            reportDiagnostic(context.program, {
                code: "invalid-argument-count",
                format: {
                    actual: parameterCount.toString(),
                    expected: `${min}-${max === undefined ? "infinity" : max.toString()}`,
                },
                target: context.decoratorTarget,
            });
        }
        return false;
    }
    return true;
}
function prettyValue(program, value) {
    if (typeof value === "object" && value !== null && "kind" in value) {
        return getTypeName(value);
    }
    return value;
}
/** @deprecated use typespecTypeToJson */
const cadlTypeToJson = typespecTypeToJson;
/**
 * Convert a TypeSpec type to a serializable Json object.
 * Emits diagnostics if the given type is invalid
 * @param typespecType The type to convert to Json data
 * @param target The diagnostic target in case of errors.
 */
function typespecTypeToJson(typespecType, target) {
    if (typeof typespecType !== "object") {
        return [typespecType, []];
    }
    return typespecTypeToJsonInternal(typespecType, target, []);
}
function typespecTypeToJsonInternal(typespecType, target, path) {
    switch (typespecType.kind) {
        case "String":
        case "Boolean":
        case "Number":
            return [typespecType.value, []];
        case "EnumMember":
            return [typespecType.value ?? typespecType.name, []];
        case "Tuple": {
            const result = [];
            for (const [index, type] of typespecType.values.entries()) {
                const [item, diagnostics] = typespecTypeToJsonInternal(type, target, [
                    ...path,
                    index.toString(),
                ]);
                if (diagnostics.length > 0) {
                    return [undefined, diagnostics];
                }
                result.push(item);
            }
            return [result, []];
        }
        case "Model": {
            const result = {};
            for (const [name, type] of typespecType.properties.entries()) {
                const [item, diagnostics] = typespecTypeToJsonInternal(type.type, target, [
                    ...path,
                    name.toString(),
                ]);
                if (diagnostics.length > 0) {
                    return [undefined, diagnostics];
                }
                result[name] = item;
            }
            return [result, []];
        }
        default:
            const diagnostic = path.length === 0
                ? createDiagnostic({
                    code: "invalid-value",
                    format: {
                        kind: typespecType.kind,
                    },
                    target,
                })
                : createDiagnostic({
                    code: "invalid-value",
                    messageId: "atPath",
                    format: {
                        kind: typespecType.kind,
                        path: path.join("."),
                    },
                    target,
                });
            return [undefined, [diagnostic]];
    }
}
function validateDecoratorUniqueOnNode(context, type, decorator) {
    compilerAssert("decorators" in type, "Type should have decorators");
    const sameDecorators = type.decorators.filter((x) => x.decorator === decorator &&
        x.node?.kind === SyntaxKind.DecoratorExpression &&
        x.node?.parent === type.node);
    if (sameDecorators.length > 1) {
        reportDiagnostic(context.program, {
            code: "duplicate-decorator",
            format: { decoratorName: "@" + decorator.name.slice(1) },
            target: context.decoratorTarget,
        });
        return false;
    }
    return true;
}
/**
 * Validate that a given decorator is not on a type or any of its base types.
 * Useful to check for decorator usage that conflicts with another decorator.
 * @param context Decorator context
 * @param type The type to check
 * @param badDecorator The decorator we don't want present
 * @param givenDecorator The decorator that is the reason why we don't want the bad decorator present
 * @param includeHeritage Whether to check base types for the bad decorator too
 * @returns Whether the decorator application is valid
 */
function validateDecoratorNotOnType(context, type, badDecorator, givenDecorator) {
    compilerAssert("decorators" in type, "Type should have decorators");
    const decAppsToCheck = [];
    let base = type;
    while (base) {
        decAppsToCheck.push(...base.decorators);
        base = getHeritage(base);
    }
    for (const decapp of decAppsToCheck) {
        if (decapp.decorator === badDecorator) {
            reportDiagnostic(context.program, {
                code: "decorator-conflict",
                format: {
                    decoratorName: "@" + badDecorator.name.slice(1),
                    otherDecoratorName: "@" + givenDecorator.name.slice(1),
                },
                target: context.decoratorTarget,
            });
            return false;
        }
    }
    return true;
    function getHeritage(type) {
        if (type.kind === "Model") {
            return type.baseModel;
        }
        else if (type.kind === "Scalar") {
            return type.baseScalar;
        }
        else {
            return undefined;
        }
    }
}
/**
 * Return the type of the property or the model itself.
 */
function getPropertyType(target) {
    if (target.kind === "ModelProperty") {
        return target.type;
    }
    else {
        return target;
    }
}

function parse$1(text, options) {
    const result = parse$2(text, { comments: true, docs: true });
    flattenNamespaces(result);
    const errors = result.parseDiagnostics.filter((x) => x.severity === "error");
    if (errors.length > 0 && !result.printable) {
        throw new PrettierParserError(errors[0]);
    }
    // Remove doc comments as those are handled directly.
    mutate(result).comments = result.comments.filter((x) => !(x.kind === SyntaxKind.BlockComment && x.parsedAsDocs));
    return result;
}
/**
 * We are patching the syntax tree to flatten the namespace nodes that are created from namespace Foo.Bar; which have the same pos, end
 * This causes prettier to not know where comments belong.
 * https://github.com/microsoft/typespec/pull/2061
 */
function flattenNamespaces(base) {
    visitChildren(base, (node) => {
        if (node.kind === SyntaxKind.NamespaceStatement) {
            let current = node;
            const ids = [node.id];
            while (current.statements && "kind" in current.statements) {
                current = current.statements;
                ids.push(current.id);
            }
            Object.assign(node, current, {
                ids,
            });
            flattenNamespaces(current);
        }
    });
}
class PrettierParserError extends Error {
    error;
    loc;
    constructor(error) {
        super(error.message);
        this.error = error;
        const location = getSourceLocation(error.target);
        this.loc = {
            start: location?.pos ?? 0,
            end: location?.end ?? 0,
        };
    }
}

const defaultOptions$2 = {};
const languages = [
    {
        name: "TypeSpec",
        parsers: ["typespec"],
        extensions: [".tsp", ".cadl"],
        vscodeLanguageIds: ["typespec"],
    },
];
const TypeSpecParser = {
    parse: parse$1,
    astFormat: "typespec-format",
    locStart(node) {
        return node.pos;
    },
    locEnd(node) {
        return node.end;
    },
};
const parsers = {
    typespec: TypeSpecParser,
};
const printers = {
    "typespec-format": typespecPrinter,
};

var formatter = /*#__PURE__*/Object.freeze({
    __proto__: null,
    defaultOptions: defaultOptions$2,
    languages: languages,
    parsers: parsers,
    printers: printers
});

async function formatTypeSpec(code, prettierConfig) {
    const output = await gu(code, {
        ...prettierConfig,
        parser: "typespec",
        plugins: [formatter],
    });
    return output;
}
/** @deprecated use checkFormatTypeSpec */
const checkFormatCadl = checkFormatTypeSpec;
/**
 * Check the given is correctly formatted.
 * @returns true if code is formatted correctly.
 */
async function checkFormatTypeSpec(code, prettierConfig) {
    return fi$1(code, {
        ...prettierConfig,
        parser: "typespec",
        plugins: [formatter],
    });
}

/**
 * List operations in the given container. Will list operation recursively by default(Check subnamespaces.)
 * @param container Container.
 * @param options Options.
 */
function listOperationsIn(container, options = {}) {
    const operations = [];
    function addOperations(current) {
        if (current.kind === "Interface" && isTemplateDeclaration(current)) {
            // Skip template interface operations
            return;
        }
        for (const op of current.operations.values()) {
            // Skip templated operations
            if (!isTemplateDeclarationOrInstance(op)) {
                operations.push(op);
            }
        }
        if (current.kind === "Namespace") {
            const recursive = options.recursive ?? true;
            const children = [
                ...(recursive ? current.namespaces.values() : []),
                ...current.interfaces.values(),
            ];
            for (const child of children) {
                addOperations(child);
            }
        }
    }
    addOperations(container);
    return operations;
}

const VariableInterpolationRegex$1 = /{([a-zA-Z-_.]+)}(\/|\.?)/g;
/**
 * Interpolate a path template
 * @param pathTemplate Path template
 * @param predefinedVariables Variables that can be used in the path template.
 * @returns
 */
function interpolatePath(pathTemplate, predefinedVariables) {
    return pathTemplate.replace(VariableInterpolationRegex$1, (match, expression, suffix) => {
        const isPathSegment = suffix === "/" || suffix === ".";
        const resolved = resolveExpression(predefinedVariables, expression);
        if (resolved) {
            return isPathSegment ? `${resolved}${suffix}` : resolved;
        }
        return "";
    });
}
function resolveExpression(predefinedVariables, expression) {
    const segments = expression.split(".");
    let resolved = predefinedVariables;
    for (const segment of segments) {
        resolved = resolved[segment];
        if (resolved === undefined) {
            return undefined;
        }
    }
    if (typeof resolved === "string") {
        return resolved;
    }
    else {
        return undefined;
    }
}

const regex = /^(application|audio|font|example|image|message|model|multipart|text|video|x-(?:[0-9A-Za-z!#$%&'*+.^_`|~-]+))\/([0-9A-Za-z!#$%&'*+.^_`|~-]+)$/;
function parseMimeType(mimeType) {
    const match = mimeType.match(regex);
    if (match == null) {
        return undefined;
    }
    const type = {
        type: match[1],
        ...parseSubType(match[2]),
    };
    return type;
}
function parseSubType(value) {
    if (!value.includes("+"))
        return { subtype: value };
    const [subtype, suffix] = value.split("+", 2);
    return { subtype, suffix };
}

function createStateSymbol$1(name) {
    return Symbol.for(`TypeSpec.${name}`);
}
const encodedNameKey = createStateSymbol$1("encodedName");
function $encodedName(context, target, mimeType, name) {
    let existing = context.program.stateMap(encodedNameKey).get(target);
    if (existing === undefined) {
        existing = new Map();
        context.program.stateMap(encodedNameKey).set(target, existing);
    }
    const mimeTypeObj = parseMimeType(mimeType);
    if (mimeTypeObj === undefined) {
        reportDiagnostic(context.program, {
            code: "invalid-mime-type",
            format: { mimeType },
            target: context.getArgumentTarget(0),
        });
    }
    else if (mimeTypeObj.suffix) {
        reportDiagnostic(context.program, {
            code: "no-mime-type-suffix",
            format: { mimeType, suffix: mimeTypeObj.suffix },
            target: context.getArgumentTarget(0),
        });
    }
    existing.set(mimeType, name);
}
function getEncodedName(program, target, mimeType) {
    const mimeTypeObj = parseMimeType(mimeType);
    if (mimeTypeObj === undefined) {
        return undefined;
    }
    const resolvedMimeType = mimeTypeObj?.suffix
        ? `${mimeTypeObj.type}/${mimeTypeObj.suffix}`
        : mimeType;
    return program.stateMap(encodedNameKey).get(target)?.get(resolvedMimeType);
}
/**
 * Resolve the encoded name for the given type when serialized to the given mime type.
 * If a specific value was provided by `@encodedName` decorator for that mime type it will return that otherwise it will return the name of the type.
 *
 * @example
 *
 * For the given
 * ```tsp
 * model Certificate {
 *   @encodedName("application/json", "exp")
 *   @encodedName("application/xml", "expiry")
 *   expireAt: utcDateTime;
 *
 * }
 * ```
 *
 * ```ts
 * resolveEncodedName(program, type, "application/json") // exp
 * resolveEncodedName(program, type, "application/merge-patch+json") // exp
 * resolveEncodedName(program, type, "application/xml") // expireAt
 * resolveEncodedName(program, type, "application/yaml") // expiry
 * ```
 */
function resolveEncodedName(program, target, mimeType) {
    return getEncodedName(program, target, mimeType) ?? target.name;
}
/**
 * Validate encoded names for conflicts. Validate the encoded names doesn't encode to an existing property name and that 2 encoded names don't map to the same name for the same mime type.
 * @internal
 */
function validateEncodedNamesConflicts(program) {
    const duplicateTrackers = new Map();
    function getOrCreateDuplicateTracker(type, mimeType) {
        let perMimeTypes = duplicateTrackers.get(type);
        if (perMimeTypes === undefined) {
            perMimeTypes = new Map();
            duplicateTrackers.set(type, perMimeTypes);
        }
        let tracker = perMimeTypes.get(mimeType);
        if (tracker === undefined) {
            tracker = new DuplicateTracker();
            perMimeTypes.set(mimeType, tracker);
        }
        return tracker;
    }
    for (const [target, map] of program.stateMap(encodedNameKey).entries()) {
        const scope = getScope(target);
        if (scope === undefined) {
            return;
        }
        for (const [mimeType, name] of map.entries()) {
            const duplicateTracker = getOrCreateDuplicateTracker(scope.parent, mimeType);
            duplicateTracker.track(name, target);
            if (scope.members.has(name)) {
                reportDiagnostic(program, {
                    code: "encoded-name-conflict",
                    format: { name, mimeType },
                    target: target,
                });
            }
        }
    }
    for (const perMimeTypes of duplicateTrackers.values()) {
        for (const [mimeType, tracker] of perMimeTypes.entries()) {
            for (const [duplicateName, items] of tracker.entries()) {
                for (const item of items) {
                    reportDiagnostic(program, {
                        code: "encoded-name-conflict",
                        messageId: "duplicate",
                        format: { name: duplicateName, mimeType },
                        target: item,
                    });
                }
            }
        }
    }
}
function getScope(type) {
    switch (type.kind) {
        case "ModelProperty":
            return type.model && { parent: type.model, members: type.model.properties };
        case "EnumMember":
            return { parent: type.enum, members: type.enum.members };
        case "UnionVariant":
            return { parent: type.union, members: type.union.variants };
        default:
            return undefined;
    }
}

function createSuppressCodeFix(diagnosticTarget, warningCode) {
    return defineCodeFix({
        id: "suppress",
        label: `Suppress warning: "${warningCode}"`,
        fix: (context) => {
            const location = getSourceLocation(diagnosticTarget);
            const { lineStart, indent } = findLineStartAndIndent(location);
            const updatedLocation = { ...location, pos: lineStart };
            return context.prependText(updatedLocation, `${indent}#suppress "${warningCode}" ""\n`);
        },
    });
}
function findLineStartAndIndent(location) {
    const text = location.file.text;
    let pos = location.pos;
    let indent = 0;
    while (pos > 0 && text[pos - 1] !== "\n") {
        if (isWhiteSpace(text.charCodeAt(pos - 1))) {
            indent++;
        }
        else {
            indent = 0;
        }
        pos--;
    }
    return { lineStart: pos, indent: location.file.text.slice(pos, pos + indent) };
}

/**
 * Resolve the path to the main file
 * @param path path to the entrypoint of the program. Can be the main.tsp, folder containing main.tsp or a project/library root.
 * @returns Absolute path to the entrypoint.
 */
async function resolveTypeSpecEntrypoint(host, path, reportDiagnostic) {
    const resolvedPath = resolvePath(path);
    const mainStat = await doIO(host.stat, resolvedPath, reportDiagnostic);
    if (!mainStat) {
        return undefined;
    }
    if (mainStat.isDirectory()) {
        return resolveTypeSpecEntrypointForDir(host, resolvedPath, reportDiagnostic);
    }
    else {
        return resolvedPath;
    }
}
async function resolveTypeSpecEntrypointForDir(host, dir, reportDiagnostic) {
    const pkgJsonPath = resolvePath(dir, "package.json");
    const [pkg] = await loadFile(host, pkgJsonPath, JSON.parse, reportDiagnostic, {
        allowFileNotFound: true,
    });
    const tspMain = resolveTspMain(pkg);
    if (tspMain !== undefined) {
        return resolvePath(dir, tspMain);
    }
    // Back Compat: if main.cadl exist, return main.cadl
    let mainFile = resolvePath(dir, "main.cadl");
    const stat = await doIO(() => host.stat(mainFile), mainFile, () => { });
    // if not found, use the normal resolution.
    if (stat?.isFile() !== true) {
        mainFile = resolvePath(dir, "main.tsp");
    }
    return mainFile;
}

class ExternalError extends Error {
    info;
    constructor(info) {
        super(renderExternalErrorInfo(info));
        this.info = info;
        this.name = "ExternalError";
    }
    render(color) {
        return renderExternalErrorInfo(this.info, color);
    }
}
function renderExternalErrorInfo(info, color = (x) => x) {
    const { metadata, kind } = info;
    const msg = [
        color(kind === "emitter"
            ? `Emitter "${metadata.name}" crashed! This is a bug.`
            : `Library "${metadata.name}" $onValidate crashed! This is a bug.`, "red"),
    ];
    if (metadata.bugs?.url) {
        msg.push(`Please file an issue at ${color(metadata.bugs?.url, "cyan")}`);
    }
    else {
        msg.push(`Please contact library author to report this issue.`);
    }
    msg.push("");
    msg.push(color(getInnerError(info), "gray"));
    msg.push("");
    msg.push(getReportInfo(metadata, color));
    return msg.join("\n");
}
function getInnerError({ error }) {
    if (typeof error === "object" &&
        error !== null &&
        "stack" in error &&
        typeof error.stack === "string") {
        return error.stack;
    }
    else {
        return String(error);
    }
}
function getReportInfo(metadata, color) {
    const details = {
        "Library Version": metadata.version ?? "?",
        "TypeSpec Compiler Version": MANIFEST.version,
    };
    return [
        "-".repeat(50),
        ...Object.entries(details).map(([k, v]) => `${k.padEnd(30)} ${color(v, "yellow")}`),
        "-".repeat(50),
    ].join("\n");
}

const defaultOptions$1 = {
    includeTemplateDeclaration: false,
};
/**
 * Navigate all types in the program.
 * @param program Program to navigate.
 * @param listeners Listener called when visiting types.
 * @param options Navigation options.
 */
function navigateProgram(program, listeners, options = {}) {
    const context = createNavigationContext(listeners, options);
    context.emit("root", program);
    navigateNamespaceType(program.getGlobalNamespaceType(), context);
}
/**
 * Navigate the given type and all the types that are used in it.
 * @param type Type to navigate.
 * @param listeners Listener for the types found.
 * @param options Navigation options
 */
function navigateType(type, listeners, options) {
    const context = createNavigationContext(listeners, options);
    navigateTypeInternal(type, context);
}
/**
 * Scope the current navigation to the given namespace.
 * @param namespace Namespace the traversal shouldn't leave.
 * @param listeners Type listeners.
 * @param options Scope options
 * @returns wrapped listeners that that can be used with `navigateType`
 */
function scopeNavigationToNamespace(namespace, listeners, options = {}) {
    const wrappedListeners = {};
    for (const [name, callback] of Object.entries(listeners)) {
        wrappedListeners[name] = (x) => {
            if (x !== namespace && "namespace" in x) {
                if (options.skipSubNamespaces && x.namespace !== namespace) {
                    return ListenerFlow.NoRecursion;
                }
                if (x.namespace && !isSubNamespace(x.namespace, namespace)) {
                    return ListenerFlow.NoRecursion;
                }
            }
            return callback(x);
        };
    }
    return wrappedListeners;
}
function navigateTypesInNamespace(namespace, listeners, options = {}) {
    navigateType(namespace, scopeNavigationToNamespace(namespace, listeners, options), options);
}
/**
 * Create a Semantic node listener from an event emitter.
 * @param eventEmitter Event emitter.
 * @returns Semantic node listener.
 */
function mapEventEmitterToNodeListener(eventEmitter) {
    const listener = {};
    for (const eventName of eventNames) {
        listener[eventName] = (...args) => {
            eventEmitter.emit(eventName, ...args);
        };
    }
    return listener;
}
function isSubNamespace(subNamespace, namespace) {
    let current = subNamespace;
    while (current !== undefined) {
        if (current === namespace) {
            return true;
        }
        current = current.namespace;
    }
    return false;
}
function createNavigationContext(listeners, options = {}) {
    return {
        visited: new Set(),
        emit: (key, ...args) => listeners[key]?.(...args),
        options: computeOptions(options),
    };
}
function computeOptions(options) {
    return { ...defaultOptions$1, ...options };
}
function navigateNamespaceType(namespace, context) {
    if (context.emit("namespace", namespace) === ListenerFlow.NoRecursion)
        return;
    for (const model of namespace.models.values()) {
        navigateModelType(model, context);
    }
    for (const scalar of namespace.scalars.values()) {
        navigateScalarType(scalar, context);
    }
    for (const operation of namespace.operations.values()) {
        navigateOperationType(operation, context);
    }
    for (const subNamespace of namespace.namespaces.values()) {
        navigateNamespaceType(subNamespace, context);
    }
    for (const union of namespace.unions.values()) {
        navigateUnionType(union, context);
    }
    for (const iface of namespace.interfaces.values()) {
        navigateInterfaceType(iface, context);
    }
    for (const enumType of namespace.enums.values()) {
        navigateEnumType(enumType, context);
    }
    for (const decorator of namespace.decoratorDeclarations.values()) {
        navigateDecoratorDeclaration(decorator, context);
    }
}
function checkVisited(visited, item) {
    if (visited.has(item)) {
        return true;
    }
    visited.add(item);
    return false;
}
function shouldNavigateTemplatableType(context, type) {
    if (context.options.includeTemplateDeclaration) {
        return type.isFinished || isTemplateDeclaration(type);
    }
    else {
        return type.isFinished;
    }
}
function navigateOperationType(operation, context) {
    if (checkVisited(context.visited, operation)) {
        return;
    }
    if (!shouldNavigateTemplatableType(context, operation)) {
        return;
    }
    if (context.emit("operation", operation) === ListenerFlow.NoRecursion)
        return;
    for (const parameter of operation.parameters.properties.values()) {
        navigateTypeInternal(parameter, context);
    }
    navigateTypeInternal(operation.returnType, context);
    if (operation.sourceOperation) {
        navigateTypeInternal(operation.sourceOperation, context);
    }
}
function navigateModelType(model, context) {
    if (checkVisited(context.visited, model)) {
        return;
    }
    if (!shouldNavigateTemplatableType(context, model)) {
        return;
    }
    if (context.emit("model", model) === ListenerFlow.NoRecursion)
        return;
    for (const property of model.properties.values()) {
        navigateModelTypeProperty(property, context);
    }
    if (model.baseModel) {
        navigateModelType(model.baseModel, context);
    }
    if (model.indexer && model.indexer.value) {
        navigateTypeInternal(model.indexer.value, context);
    }
    context.emit("exitModel", model);
}
function navigateModelTypeProperty(property, context) {
    if (checkVisited(context.visited, property)) {
        return;
    }
    if (context.emit("modelProperty", property) === ListenerFlow.NoRecursion)
        return;
    navigateTypeInternal(property.type, context);
}
function navigateScalarType(scalar, context) {
    if (checkVisited(context.visited, scalar)) {
        return;
    }
    if (context.emit("scalar", scalar) === ListenerFlow.NoRecursion)
        return;
    if (scalar.baseScalar) {
        navigateScalarType(scalar.baseScalar, context);
    }
    for (const constructor of scalar.constructors.values()) {
        navigateScalarConstructor(constructor, context);
    }
    context.emit("exitScalar", scalar);
}
function navigateInterfaceType(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (!shouldNavigateTemplatableType(context, type)) {
        return;
    }
    context.emit("interface", type);
    for (const op of type.operations.values()) {
        navigateOperationType(op, context);
    }
}
function navigateEnumType(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    context.emit("enum", type);
}
function navigateUnionType(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (!shouldNavigateTemplatableType(context, type)) {
        return;
    }
    if (context.emit("union", type) === ListenerFlow.NoRecursion)
        return;
    for (const variant of type.variants.values()) {
        navigateUnionTypeVariant(variant, context);
    }
}
function navigateUnionTypeVariant(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (context.emit("unionVariant", type) === ListenerFlow.NoRecursion)
        return;
    navigateTypeInternal(type.type, context);
}
function navigateTupleType(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (context.emit("tuple", type) === ListenerFlow.NoRecursion)
        return;
    for (const value of type.values) {
        navigateTypeInternal(value, context);
    }
}
function navigateStringTemplate(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (context.emit("stringTemplate", type) === ListenerFlow.NoRecursion)
        return;
    for (const value of type.spans) {
        navigateTypeInternal(value, context);
    }
}
function navigateStringTemplateSpan(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (context.emit("stringTemplateSpan", type) === ListenerFlow.NoRecursion)
        return;
    navigateTypeInternal(type.type, context);
}
function navigateTemplateParameter(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (context.emit("templateParameter", type) === ListenerFlow.NoRecursion)
        return;
}
function navigateDecoratorDeclaration(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (context.emit("decorator", type) === ListenerFlow.NoRecursion)
        return;
}
function navigateScalarConstructor(type, context) {
    if (checkVisited(context.visited, type)) {
        return;
    }
    if (context.emit("scalarConstructor", type) === ListenerFlow.NoRecursion)
        return;
}
function navigateTypeInternal(type, context) {
    switch (type.kind) {
        case "Model":
            return navigateModelType(type, context);
        case "Scalar":
            return navigateScalarType(type, context);
        case "ModelProperty":
            return navigateModelTypeProperty(type, context);
        case "Namespace":
            return navigateNamespaceType(type, context);
        case "Interface":
            return navigateInterfaceType(type, context);
        case "Enum":
            return navigateEnumType(type, context);
        case "Operation":
            return navigateOperationType(type, context);
        case "Union":
            return navigateUnionType(type, context);
        case "UnionVariant":
            return navigateUnionTypeVariant(type, context);
        case "Tuple":
            return navigateTupleType(type, context);
        case "StringTemplate":
            return navigateStringTemplate(type, context);
        case "StringTemplateSpan":
            return navigateStringTemplateSpan(type, context);
        case "TemplateParameter":
            return navigateTemplateParameter(type, context);
        case "Decorator":
            return navigateDecoratorDeclaration(type, context);
        case "ScalarConstructor":
            return navigateScalarConstructor(type, context);
        case "Object":
        case "Projection":
        case "Function":
        case "FunctionParameter":
        case "Boolean":
        case "EnumMember":
        case "Intrinsic":
        case "Number":
        case "String":
            return;
        default:
            return;
    }
}
// Return property from type, nesting into baseTypes as needed.
function getProperty(type, propertyName) {
    while (type.baseModel) {
        if (type.properties.has(propertyName)) {
            return type.properties.get(propertyName);
        }
        type = type.baseModel;
    }
    return type.properties.get(propertyName);
}
class EventEmitter {
    listeners = new Map();
    on(name, listener) {
        const array = this.listeners.get(name);
        if (array) {
            array.push(listener);
        }
        else {
            this.listeners.set(name, [listener]);
        }
    }
    emit(name, ...args) {
        const listeners = this.listeners.get(name);
        if (listeners) {
            for (const listener of listeners) {
                listener(...args);
            }
        }
    }
}
const eventNames = [
    "root",
    "templateParameter",
    "exitTemplateParameter",
    "scalar",
    "exitScalar",
    "model",
    "exitModel",
    "modelProperty",
    "exitModelProperty",
    "interface",
    "exitInterface",
    "enum",
    "exitEnum",
    "enumMember",
    "exitEnumMember",
    "namespace",
    "exitNamespace",
    "operation",
    "exitOperation",
    "string",
    "exitString",
    "number",
    "exitNumber",
    "boolean",
    "exitBoolean",
    "tuple",
    "exitTuple",
    "union",
    "exitUnion",
    "unionVariant",
    "exitUnionVariant",
    "intrinsic",
    "exitIntrinsic",
    "function",
    "exitFunction",
    "object",
    "exitObject",
    "projection",
    "exitProjection",
];

/**
 * Resolve the linter definition
 */
function resolveLinterDefinition(libName, linter) {
    const rules = linter.rules.map((rule) => {
        return { ...rule, id: `${libName}/${rule.name}` };
    });
    if (linter.rules.length === 0 || (linter.ruleSets && "all" in linter.ruleSets)) {
        return {
            rules,
            ruleSets: linter.ruleSets ?? {},
        };
    }
    else {
        return {
            rules,
            ruleSets: {
                all: {
                    enable: Object.fromEntries(rules.map((x) => [x.id, true])),
                },
                ...linter.ruleSets,
            },
        };
    }
}
function createLinter(program, loadLibrary) {
    const tracer = program.tracer.sub("linter");
    const ruleMap = new Map();
    const enabledRules = new Map();
    const linterLibraries = new Map();
    return {
        extendRuleSet,
        lint,
    };
    async function extendRuleSet(ruleSet) {
        tracer.trace("extend-rule-set.start", JSON.stringify(ruleSet, null, 2));
        const diagnostics = createDiagnosticCollector();
        if (ruleSet.extends) {
            for (const extendingRuleSetName of ruleSet.extends) {
                const ref = diagnostics.pipe(parseRuleReference(extendingRuleSetName));
                if (ref) {
                    const library = await resolveLibrary(ref.libraryName);
                    const libLinterDefinition = library?.linter;
                    const extendingRuleSet = libLinterDefinition?.ruleSets?.[ref.name];
                    if (extendingRuleSet) {
                        await extendRuleSet(extendingRuleSet);
                    }
                    else {
                        diagnostics.add(createDiagnostic({
                            code: "unknown-rule-set",
                            format: { libraryName: ref.libraryName, ruleSetName: ref.name },
                            target: NoTarget,
                        }));
                    }
                }
            }
        }
        const enabledInThisRuleSet = new Set();
        if (ruleSet.enable) {
            for (const [ruleName, enable] of Object.entries(ruleSet.enable)) {
                if (enable === false) {
                    continue;
                }
                const ref = diagnostics.pipe(parseRuleReference(ruleName));
                if (ref) {
                    await resolveLibrary(ref.libraryName);
                    const rule = ruleMap.get(ruleName);
                    if (rule) {
                        enabledInThisRuleSet.add(ruleName);
                        enabledRules.set(ruleName, rule);
                    }
                    else {
                        diagnostics.add(createDiagnostic({
                            code: "unknown-rule",
                            format: { libraryName: ref.libraryName, ruleName: ref.name },
                            target: NoTarget,
                        }));
                    }
                }
            }
        }
        if (ruleSet.disable) {
            for (const ruleName of Object.keys(ruleSet.disable)) {
                if (enabledInThisRuleSet.has(ruleName)) {
                    diagnostics.add(createDiagnostic({
                        code: "rule-enabled-disabled",
                        format: { ruleName },
                        target: NoTarget,
                    }));
                }
                enabledRules.delete(ruleName);
            }
        }
        tracer.trace("extend-rule-set.end", "Rules enabled: \n" + [...enabledRules.keys()].map((x) => ` - ${x}`).join("\n"));
        return diagnostics.diagnostics;
    }
    function lint() {
        const diagnostics = createDiagnosticCollector();
        const eventEmitter = new EventEmitter();
        tracer.trace("lint", `Running linter with following rules:\n` +
            [...enabledRules.keys()].map((x) => ` - ${x}`).join("\n"));
        for (const rule of enabledRules.values()) {
            const listener = rule.create(createLinterRuleContext(program, rule, diagnostics));
            for (const [name, cb] of Object.entries(listener)) {
                eventEmitter.on(name, cb);
            }
        }
        navigateProgram(program, mapEventEmitterToNodeListener(eventEmitter));
        return diagnostics.diagnostics;
    }
    async function resolveLibrary(name) {
        const loadedLibrary = linterLibraries.get(name);
        if (loadedLibrary === undefined) {
            return registerLinterLibrary(name);
        }
        return loadedLibrary;
    }
    async function registerLinterLibrary(name) {
        tracer.trace("register-library", name);
        const library = await loadLibrary(name);
        const linter = library?.linter;
        if (linter?.rules) {
            for (const rule of linter.rules) {
                tracer.trace("register-library.rule", `Registering rule "${rule.id}" for library "${name}".`);
                if (ruleMap.has(rule.id)) {
                    compilerAssert(false, `Unexpected duplicate linter rule: "${rule.id}"`);
                }
                else {
                    ruleMap.set(rule.id, rule);
                }
            }
        }
        linterLibraries.set(name, library);
        return library;
    }
    function parseRuleReference(ref) {
        const segments = ref.split("/");
        const name = segments.pop();
        const libraryName = segments.join("/");
        if (!libraryName || !name) {
            return [
                undefined,
                [createDiagnostic({ code: "invalid-rule-ref", format: { ref }, target: NoTarget })],
            ];
        }
        return [{ libraryName, name }, []];
    }
}
function createLinterRuleContext(program, rule, diagnosticCollector) {
    return {
        program,
        reportDiagnostic,
    };
    function createDiagnostic(diag) {
        const message = rule.messages[diag.messageId ?? "default"];
        if (!message) {
            const messageString = Object.keys(rule.messages)
                .map((x) => ` - ${x}`)
                .join("\n");
            const messageId = String(diag.messageId);
            throw new Error(`Unexpected message id '${messageId}' for rule '${rule.name}'. Defined messages:\n${messageString}`);
        }
        const messageStr = typeof message === "string" ? message : message(diag.format);
        return {
            code: rule.id,
            severity: rule.severity,
            message: messageStr,
            target: diag.target,
            codefixes: diag.codefixes,
        };
    }
    function reportDiagnostic(diag) {
        const diagnostic = createDiagnostic(diag);
        if (diagnostic.target !== NoTarget) {
            const context = getLocationContext(program, diagnostic.target);
            // Only report diagnostic in the user project.
            // See for showing diagnostic in library at point of usage https://github.com/microsoft/typespec/issues/1997
            if (context.type === "project") {
                diagnosticCollector.add(diagnostic);
            }
        }
    }
}

const LogLevels = {
    trace: 10,
    warning: 40,
    error: 50,
};
const defaultOptions = {
    level: "trace",
};
function createLogger(options) {
    const config = { ...defaultOptions, ...options };
    function log(log) {
        if (LogLevels[config.level] <= LogLevels[log.level]) {
            config.sink.log(processLog(log));
        }
    }
    return {
        log,
        trace: (message) => log({ level: "trace", message }),
        warn: (message) => log({ level: "warning", message }),
        error: (message) => log({ level: "error", message }),
    };
}
function processLog(log) {
    return {
        level: log.level,
        code: log.code,
        message: log.message,
        sourceLocation: getSourceLocation(log.target, { locateId: true }),
    };
}

function createTracer(logger, tracerOptions = {}) {
    const filters = tracerOptions.filter ? createFilterTree(tracerOptions.filter) : undefined;
    function shouldTrace(area) {
        if (!filters) {
            return false;
        }
        return filters.match(area);
    }
    function log(area, message) {
        if (shouldTrace(area)) {
            logger.log({
                level: "trace",
                code: area,
                message,
            });
        }
    }
    return createTracerInternal(log);
}
function createFilterTree(filters) {
    const tree = {
        all: false,
        children: {},
    };
    for (const filter of filters) {
        if (tree.all) {
            break;
        }
        let current = tree;
        const segments = filter.split(".");
        for (const segment of segments) {
            if (current.all) {
                break;
            }
            if (segment === "*") {
                current.all = true;
                break;
            }
            current.children[segment] = {
                all: false,
                children: {},
            };
            current = current.children[segment];
        }
        current.all = true;
    }
    return { match };
    function match(area) {
        if (tree.all) {
            return true;
        }
        const segments = area.split(".");
        let current = tree;
        for (const segment of segments) {
            if (current.all) {
                return true;
            }
            if (!current.children[segment]) {
                return false;
            }
            current = current.children[segment];
        }
        return true;
    }
}
function createTracerInternal(log) {
    return {
        trace,
        sub,
    };
    function trace(area, message) {
        log(area, message);
    }
    function sub(subArea) {
        return createTracerInternal((area, message) => {
            log(joinAreas(subArea, area), message);
        });
    }
}
function joinAreas(a, b) {
    if (a) {
        if (b) {
            return `${a}.${b}`;
        }
        return a;
    }
    else {
        return b ?? "";
    }
}

function isProjectedProgram(program) {
    return "projector" in program;
}

class StateMap extends Map {
}
class StateSet extends Map {
}
class StateMapView {
    state;
    projector;
    constructor(state, projector) {
        this.state = state;
        this.projector = projector;
    }
    has(t) {
        return this.dispatch(t)?.has(t) ?? false;
    }
    set(t, v) {
        this.dispatch(t).set(t, v);
        return this;
    }
    get(t) {
        return this.dispatch(t).get(t);
    }
    delete(t) {
        return this.dispatch(t).delete(t);
    }
    forEach(cb, thisArg) {
        this.dispatch().forEach(cb, thisArg);
        return this;
    }
    get size() {
        return this.dispatch().size;
    }
    clear() {
        return this.dispatch().clear();
    }
    entries() {
        return this.dispatch().entries();
    }
    values() {
        return this.dispatch().values();
    }
    keys() {
        return this.dispatch().keys();
    }
    [Symbol.iterator]() {
        return this.entries();
    }
    [Symbol.toStringTag] = "StateMap";
    dispatch(keyType) {
        const key = keyType ? keyType.projector : this.projector;
        if (!this.state.has(key)) {
            this.state.set(key, new Map());
        }
        return this.state.get(key);
    }
}
class StateSetView {
    state;
    projector;
    constructor(state, projector) {
        this.state = state;
        this.projector = projector;
    }
    has(t) {
        return this.dispatch(t)?.has(t) ?? false;
    }
    add(t) {
        this.dispatch(t).add(t);
        return this;
    }
    delete(t) {
        return this.dispatch(t).delete(t);
    }
    forEach(cb, thisArg) {
        this.dispatch().forEach(cb, thisArg);
        return this;
    }
    get size() {
        return this.dispatch().size;
    }
    clear() {
        return this.dispatch().clear();
    }
    values() {
        return this.dispatch().values();
    }
    keys() {
        return this.dispatch().keys();
    }
    entries() {
        return this.dispatch().entries();
    }
    [Symbol.iterator]() {
        return this.values();
    }
    [Symbol.toStringTag] = "StateSet";
    dispatch(keyType) {
        const key = keyType ? keyType.projector : this.projector;
        if (!this.state.has(key)) {
            this.state.set(key, new Set());
        }
        return this.state.get(key);
    }
}
function createStateAccessors(stateMaps, stateSets, projector) {
    function stateMap(key) {
        let m = stateMaps.get(key);
        if (!m) {
            m = new StateMap();
            stateMaps.set(key, m);
        }
        return new StateMapView(m, projector);
    }
    function stateSet(key) {
        let s = stateSets.get(key);
        if (!s) {
            s = new StateSet();
            stateSets.set(key, s);
        }
        return new StateSetView(s, projector);
    }
    return { stateMap, stateSet };
}

/**
 * Creates a projector which returns a projected view of either the global namespace or the
 * start node provided. Projecting a type effectively clones every type referenced underneath
 * it. This is accomplished by doing a semantic walk of each type, cloning each type we find,
 * and running projection code on the clone.
 *
 * Projectors can run multiple projections at once. In such cases, each projection is run
 * on the same clone of the unprojected type. It is up to projections and the user to ensure
 * that projections which depend on a particular shape are run when that shape is present (or
 * else to ensure that their projections are tolerant to shape changes).
 *
 * The projector maintains its own state maps and sets. If a projection is active (i.e.
 * program.currentProjector is set), then the projector's state will be returned instead
 * of the program's state. This ensures that there is no overlap between projected and
 * unprojected state. It also means that you cannot get state for nodes that are not
 * part of the active projection.
 *
 * Note that decorators are run on namespaces prior to cloning any child types to align
 * with the checker semantics, while projections are run after everything under the namespace
 * is cloned. All other run decorators and projections after all child types are cloned and
 * have their decorators run.
 */
function createProjector(program, projections, startNode) {
    const projectedTypes = new Map();
    const checker = program.checker;
    const neverType = checker.neverType;
    const scope = [];
    const projector = {
        projectedTypes,
        projections,
        projectType,
        parentProjector: isProjectedProgram(program) ? program.projector : undefined,
    };
    const projectedNamespaces = [];
    let projectingNamespaces = false;
    const projectedProgram = {
        ...program,
        getGlobalNamespaceType: () => projector.projectedGlobalNamespace,
        projector,
        ...createStateAccessors(program.stateMaps, program.stateSets, projector),
    };
    const targetGlobalNs = startNode
        ? startNode.projector
            ? startNode.projector.projectedGlobalNamespace
            : program.checker.getGlobalNamespaceType()
        : program.checker.getGlobalNamespaceType();
    projectingNamespaces = true;
    // Project the global namespace to get a reference.
    projector.projectedGlobalNamespace = projectNamespace(targetGlobalNs, false);
    // Then project the content
    projectSubNamespaces(targetGlobalNs, projector.projectedGlobalNamespace);
    projectingNamespaces = false;
    // then project all the types
    for (const ns of projectedNamespaces) {
        projectNamespaceContents(ns);
    }
    projectType(targetGlobalNs);
    projector.projectedStartNode = startNode
        ? projectedTypes.get(startNode)
        : projector.projectedGlobalNamespace;
    return projectedProgram;
    function projectType(type) {
        if (isValue(type)) {
            return type;
        }
        if (type.entityKind === "Indeterminate") {
            return { entityKind: "Indeterminate", type: projectType(type.type) };
        }
        if (projectedTypes.has(type)) {
            return projectedTypes.get(type);
        }
        scope.push(type);
        const preProjected = applyPreProjection(type);
        if (preProjected !== type) {
            projectedTypes.set(type, preProjected);
            scope.pop();
            return preProjected;
        }
        let projected;
        switch (type.kind) {
            case "Namespace":
                compilerAssert(projectingNamespaces, `Namespace ${type.name} should have already been projected.`);
                projected = projectNamespace(type, false);
                break;
            case "Scalar":
                projected = projectScalar(type);
                break;
            case "Model":
                projected = projectModel(type);
                break;
            case "ModelProperty":
                projected = projectModelProperty(type);
                break;
            case "Operation":
                projected = projectOperation(type);
                break;
            case "Interface":
                projected = projectInterface(type);
                break;
            case "Union":
                projected = projectUnion(type);
                break;
            case "UnionVariant":
                projected = projectUnionVariant(type);
                break;
            case "Tuple":
                projected = projectTuple(type);
                break;
            case "Enum":
                projected = projectEnum(type);
                break;
            case "EnumMember":
                projected = projectEnumMember(type);
                break;
            default:
                projected = type;
        }
        scope.pop();
        return projected;
    }
    function projectSubNamespaces(ns, projectedNs) {
        if (ns.namespaces.size === projectedNs.namespaces.size) {
            // Sub namespace should already have been projected.
            return;
        }
        for (const [key, childNs] of ns.namespaces) {
            const projected = projectNamespace(childNs);
            if (projected.kind === "Namespace") {
                // todo: check for never?
                projectedNs.namespaces.set(key, projected);
            }
        }
    }
    function projectNamespace(ns, projectSubNamespace = true) {
        const alreadyProjected = projectedTypes.get(ns);
        if (alreadyProjected) {
            if (projectSubNamespace) {
                projectSubNamespaces(ns, alreadyProjected);
            }
            return alreadyProjected;
        }
        const projectedNs = shallowClone(ns, {
            namespaces: new Map(),
            scalars: new Map(),
            models: new Map(),
            operations: new Map(),
            interfaces: new Map(),
            unions: new Map(),
            enums: new Map(),
            decorators: [],
        });
        projectedNs.decorators = projectDecorators(ns.decorators);
        if (ns.namespace) {
            projectedNs.namespace = projectNamespace(ns.namespace, false);
        }
        // ns run decorators before projecting anything inside them
        finishTypeForProgram(projectedProgram, projectedNs);
        if (projectSubNamespace) {
            projectSubNamespaces(ns, projectedNs);
        }
        projectedNamespaces.push(ns);
        return applyProjection(ns, projectedNs);
    }
    /**
     * Projects the contents of a namespace, but not the namespace itself. The namespace itself
     * is projected in an earlier phase.
     */
    function projectNamespaceContents(ns) {
        const projectedNs = projectedTypes.get(ns);
        compilerAssert(projectedNs, "Should have projected namespace by now");
        if (projectedNs.kind !== "Namespace") {
            // we projected the namespace to something else so don't do any more work.
            // this might happen if a namespace itself was added/removed/etc. and is
            // projected to never.
            return neverType;
        }
        for (const childModel of ns.models.values()) {
            const projected = projectType(childModel);
            if (projected.kind === "Model") {
                projectedNs.models.set(projected.name, projected);
            }
        }
        for (const scalar of ns.scalars.values()) {
            const projected = projectType(scalar);
            if (projected.kind === "Scalar") {
                projectedNs.scalars.set(projected.name, projected);
            }
        }
        for (const childOperation of ns.operations.values()) {
            const projected = projectType(childOperation);
            if (projected.kind === "Operation") {
                projectedNs.operations.set(projected.name, projected);
            }
        }
        for (const childInterface of ns.interfaces.values()) {
            const projected = projectType(childInterface);
            if (projected.kind === "Interface") {
                projectedNs.interfaces.set(projected.name, projected);
            }
        }
        for (const childUnion of ns.unions.values()) {
            const projected = projectType(childUnion);
            if (projected.kind === "Union") {
                projectedNs.unions.set(projected.name, projected);
            }
        }
        for (const childEnum of ns.enums.values()) {
            const projected = projectType(childEnum);
            if (projected.kind === "Enum") {
                projectedNs.enums.set(projected.name, projected);
            }
        }
        return projectedNs;
    }
    function projectModel(model) {
        const properties = createRekeyableMap();
        const projectedModel = shallowClone(model, {
            properties,
            derivedModels: [],
        });
        if (model.templateMapper) {
            projectedModel.templateMapper = projectTemplateMapper(model.templateMapper);
            // eslint-disable-next-line deprecation/deprecation
            projectedModel.templateArguments = mutate(projectedModel.templateMapper.args);
        }
        if (model.baseModel) {
            projectedModel.baseModel = projectType(model.baseModel);
        }
        if (model.sourceModel) {
            projectedModel.sourceModel = projectType(model.sourceModel);
        }
        if (model.indexer) {
            const projectedValue = projectType(model.indexer.value);
            projectedModel.indexer = {
                key: projectType(model.indexer.key),
                value: projectedValue,
            };
        }
        projectedTypes.set(model, projectedModel);
        for (const prop of model.properties.values()) {
            const projectedProp = projectType(prop);
            if (projectedProp.kind === "ModelProperty") {
                properties.set(projectedProp.name, projectedProp);
            }
        }
        projectedModel.decorators = projectDecorators(model.decorators);
        if (shouldFinishType(model)) {
            finishTypeForProgram(projectedProgram, projectedModel);
        }
        const projectedResult = applyProjection(model, projectedModel);
        if (!isNeverType(projectedResult) &&
            projectedResult.kind === "Model" &&
            projectedResult.baseModel) {
            projectedResult.baseModel.derivedModels ??= [];
            projectedResult.baseModel.derivedModels.push(projectedModel);
        }
        return projectedResult;
    }
    function projectTemplateMapper(mapper) {
        const projectedMapper = {
            ...mapper,
            args: [],
            map: new Map(),
        };
        for (const arg of mapper.args) {
            mutate(projectedMapper.args).push(projectType(arg));
        }
        for (const [param, type] of mapper.map) {
            projectedMapper.map.set(param, projectType(type));
        }
        return projectedMapper;
    }
    function projectScalar(scalar) {
        const projectedScalar = shallowClone(scalar, {
            derivedScalars: [],
        });
        if (scalar.templateMapper) {
            projectedScalar.templateMapper = projectTemplateMapper(scalar.templateMapper);
            // eslint-disable-next-line deprecation/deprecation
            projectedScalar.templateArguments = mutate(projectedScalar.templateMapper.args);
        }
        if (scalar.baseScalar) {
            projectedScalar.baseScalar = projectType(scalar.baseScalar);
        }
        projectedTypes.set(scalar, projectedScalar);
        projectedScalar.decorators = projectDecorators(scalar.decorators);
        if (shouldFinishType(scalar)) {
            finishTypeForProgram(projectedProgram, projectedScalar);
        }
        const projectedResult = applyProjection(scalar, projectedScalar);
        if (!isNeverType(projectedResult) &&
            projectedResult.kind === "Scalar" &&
            projectedResult.baseScalar) {
            projectedResult.baseScalar.derivedScalars ??= [];
            projectedResult.baseScalar.derivedScalars.push(projectedScalar);
        }
        return projectedResult;
    }
    /**
     * Returns true if we should finish a type. The only time we don't finish is when it's
     * a template type, because we don't want to run decorators for templates.
     */
    function shouldFinishType(type) {
        const parentTemplate = type.node && getParentTemplateNode(type.node);
        return !parentTemplate || isTemplateInstance(type);
    }
    function projectModelProperty(prop) {
        const projectedType = projectType(prop.type);
        const projectedDecs = projectDecorators(prop.decorators);
        const projectedProp = shallowClone(prop, {
            type: projectedType,
            decorators: projectedDecs,
        });
        if (prop.sourceProperty) {
            const sourceProperty = projectType(prop.sourceProperty);
            projectedProp.sourceProperty = sourceProperty;
        }
        if (shouldFinishType(prop)) {
            finishTypeForProgram(projectedProgram, projectedProp);
        }
        if (prop.model) {
            projectedProp.model = projectType(prop.model);
        }
        return applyProjection(prop, projectedProp);
    }
    function projectOperation(op) {
        const projectedOp = shallowClone(op, {});
        projectedOp.parameters = projectType(op.parameters);
        projectedOp.returnType = projectType(op.returnType);
        projectedOp.decorators = projectDecorators(op.decorators);
        if (op.templateMapper) {
            projectedOp.templateMapper = projectTemplateMapper(op.templateMapper);
            // eslint-disable-next-line deprecation/deprecation
            projectedOp.templateArguments = mutate(projectedOp.templateMapper.args);
        }
        if (op.sourceOperation) {
            projectedOp.sourceOperation = projectType(op.sourceOperation);
        }
        if (op.namespace) {
            projectedOp.namespace = projectedNamespaceScope();
        }
        if (op.isFinished) {
            finishTypeForProgram(projectedProgram, projectedOp);
        }
        if (op.interface) {
            projectedOp.interface = projectType(op.interface);
        }
        return applyProjection(op, projectedOp);
    }
    function projectInterface(iface) {
        const operations = createRekeyableMap();
        const sourceInterfaces = [];
        const projectedIface = shallowClone(iface, {
            operations,
            sourceInterfaces,
        });
        projectedIface.decorators = projectDecorators(iface.decorators);
        if (iface.templateMapper) {
            projectedIface.templateMapper = projectTemplateMapper(iface.templateMapper);
            // eslint-disable-next-line deprecation/deprecation
            projectedIface.templateArguments = mutate(projectedIface.templateMapper.args);
        }
        for (const op of iface.operations.values()) {
            const projectedOp = projectType(op);
            if (projectedOp.kind === "Operation") {
                operations.set(projectedOp.name, projectedOp);
            }
        }
        for (const source of iface.sourceInterfaces) {
            sourceInterfaces.push(projectType(source));
        }
        if (shouldFinishType(iface)) {
            finishTypeForProgram(projectedProgram, projectedIface);
        }
        return applyProjection(iface, projectedIface);
    }
    function projectUnion(union) {
        const variants = createRekeyableMap();
        const projectedUnion = shallowClone(union, {
            variants,
        });
        projectedUnion.decorators = projectDecorators(union.decorators);
        if (union.templateMapper) {
            projectedUnion.templateMapper = projectTemplateMapper(union.templateMapper);
            // eslint-disable-next-line deprecation/deprecation
            projectedUnion.templateArguments = mutate(projectedUnion.templateMapper.args);
        }
        for (const variant of union.variants.values()) {
            const projectedVariant = projectType(variant);
            if (projectedVariant.kind === "UnionVariant" && projectedVariant.type !== neverType) {
                variants.set(projectedVariant.name, projectedVariant);
            }
        }
        if (shouldFinishType(union)) {
            finishTypeForProgram(projectedProgram, projectedUnion);
        }
        return applyProjection(union, projectedUnion);
    }
    function projectUnionVariant(variant) {
        const projectedType = projectType(variant.type);
        const projectedDecs = projectDecorators(variant.decorators);
        const projectedVariant = shallowClone(variant, {
            type: projectedType,
            decorators: projectedDecs,
        });
        finishTypeForProgram(projectedProgram, projectedVariant);
        projectedVariant.union = projectType(variant.union);
        return applyProjection(variant, projectedVariant);
    }
    function projectTuple(tuple) {
        const values = [];
        const projectedTuple = shallowClone(tuple, {
            values,
        });
        for (const item of tuple.values) {
            values.push(projectType(item));
        }
        return projectedTuple;
    }
    function projectEnum(e) {
        const members = createRekeyableMap();
        const projectedEnum = shallowClone(e, {
            members,
        });
        projectedEnum.decorators = projectDecorators(e.decorators);
        projectedTypes.set(e, projectedEnum);
        for (const member of e.members.values()) {
            const projectedMember = projectType(member);
            if (projectedMember.kind === "EnumMember") {
                members.set(projectedMember.name, projectedMember);
            }
        }
        finishTypeForProgram(projectedProgram, projectedEnum);
        return applyProjection(e, projectedEnum);
    }
    function projectEnumMember(e) {
        const decorators = projectDecorators(e.decorators);
        const projectedMember = shallowClone(e, {
            decorators,
        });
        finishTypeForProgram(projectedProgram, projectedMember);
        projectedMember.enum = projectType(e.enum);
        return applyProjection(e, projectedMember);
    }
    function projectDecorators(decs) {
        const decorators = [];
        for (const dec of decs) {
            const args = [];
            for (const arg of dec.args) {
                const jsValue = typeof arg.jsValue === "object" && arg.jsValue !== null && "kind" in arg.jsValue
                    ? projectType(arg.jsValue)
                    : arg.jsValue;
                args.push({ ...arg, value: projectType(arg.value), jsValue });
            }
            decorators.push({ ...dec, args });
        }
        return decorators;
    }
    function getInScopeProjections() {
        const candidates = new Set(projections);
        const inScope = [];
        let currentScope = namespaceScope();
        outer: while (currentScope) {
            for (const candidate of candidates) {
                if (!candidate.scope || candidate.scope === currentScope) {
                    candidates.delete(candidate);
                    inScope.push(candidate);
                    if (candidates.size === 0) {
                        break outer;
                    }
                }
            }
            currentScope = currentScope.namespace;
        }
        return inScope;
    }
    function namespaceScope() {
        for (let i = scope.length - 1; i >= 0; i--) {
            if (scope[i].namespace !== undefined) {
                return scope[i].namespace;
            }
        }
        return undefined;
    }
    function projectedNamespaceScope() {
        const ns = namespaceScope();
        if (!ns)
            return ns;
        return projectType(ns);
    }
    function applyProjection(baseType, projectedType) {
        const inScopeProjections = getInScopeProjections();
        for (const projectionApplication of inScopeProjections) {
            const projectionsByName = baseType.projectionsByName(projectionApplication.projectionName);
            if (projectionsByName.length === 0)
                continue;
            const targetNode = projectionApplication.direction === "from"
                ? projectionsByName[0].from
                : projectionsByName[0].to;
            if (targetNode) {
                const projected = checker.project(projectedType, targetNode, projectionApplication.arguments);
                if (projected !== projectedType) {
                    // override the projected type cache with the returned type
                    projectedTypes.set(baseType, projected);
                    return projected;
                }
            }
        }
        return projectedType;
    }
    function applyPreProjection(type) {
        const inScopeProjections = getInScopeProjections();
        for (const projectionApplication of inScopeProjections) {
            const projectionsByName = type.projectionsByName(projectionApplication.projectionName);
            if (projectionsByName.length === 0)
                continue;
            const targetNode = projectionApplication.direction === "from"
                ? projectionsByName[0].preFrom
                : projectionsByName[0].preTo;
            if (targetNode) {
                return checker.project(type, targetNode, projectionApplication.arguments);
            }
        }
        return type;
    }
    function shallowClone(type, additionalProps) {
        const scopeProps = {};
        if ("namespace" in type && type.namespace !== undefined) {
            scopeProps.namespace = projectedNamespaceScope();
        }
        const clone = checker.createType({
            ...type,
            ...additionalProps,
            ...scopeProps,
            projectionSource: type,
            projectionBase: type.projectionBase ?? type,
            projector,
        });
        if (type.kind === "Union") {
            // create the options getter
            Object.defineProperty(clone, "options", {
                get() {
                    return Array.from(this.variants.values()).map((v) => v.type);
                },
            });
        }
        projectedTypes.set(type, clone);
        return clone;
    }
}

function projectProgram(program, projections, startNode) {
    return createProjector(program, projections, startNode);
}
async function compile(host, mainFile, options = {}, oldProgram // NOTE: deliberately separate from options to avoid memory leak by chaining all old programs together.
) {
    const validateCbs = [];
    const stateMaps = new Map();
    const stateSets = new Map();
    const diagnostics = [];
    const seenSourceFiles = new Set();
    const duplicateSymbols = new Set();
    const emitters = [];
    const requireImports = new Map();
    const loadedLibraries = new Map();
    const sourceFileLocationContexts = new WeakMap();
    let error = false;
    let continueToNextStage = true;
    const logger = createLogger({ sink: host.logSink });
    const tracer = createTracer(logger, { filter: options.trace });
    const resolvedMain = await resolveTypeSpecEntrypoint(host, mainFile, reportDiagnostic);
    const program = {
        checker: undefined,
        compilerOptions: resolveOptions(options),
        sourceFiles: new Map(),
        jsSourceFiles: new Map(),
        literalTypes: new Map(),
        host,
        diagnostics,
        emitters,
        loadTypeSpecScript,
        getOption,
        stateMaps,
        stateSets,
        tracer,
        trace,
        ...createStateAccessors(stateMaps, stateSets),
        reportDiagnostic,
        reportDiagnostics,
        reportDuplicateSymbols,
        hasError() {
            return error;
        },
        onValidate(cb, metadata) {
            validateCbs.push({ callback: cb, metadata });
        },
        getGlobalNamespaceType,
        resolveTypeReference,
        getSourceFileLocationContext,
        projectRoot: getDirectoryPath(options.config ?? resolvedMain ?? ""),
    };
    trace("compiler.options", JSON.stringify(options, null, 2));
    function trace(area, message) {
        tracer.trace(area, message);
    }
    const binder = createBinder(program);
    await loadIntrinsicTypes();
    if (!options?.nostdlib) {
        await loadStandardLibrary();
    }
    // Load additional imports prior to compilation
    if (resolvedMain && options.additionalImports) {
        const importScript = options.additionalImports.map((i) => `import "${i}";`).join("\n");
        const sourceFile = createSourceFile(importScript, joinPaths(getDirectoryPath(resolvedMain), `__additional_imports`));
        sourceFileLocationContexts.set(sourceFile, { type: "project" });
        await loadTypeSpecScript(sourceFile);
    }
    if (resolvedMain) {
        await loadMain(resolvedMain);
    }
    else {
        return program;
    }
    const basedir = getDirectoryPath(resolvedMain);
    let emit = options.emit;
    let emitterOptions = options.options;
    /* eslint-disable deprecation/deprecation */
    if (options.emitters) {
        emit ??= Object.keys(options.emitters);
        emitterOptions ??= options.emitters;
    }
    /* eslint-enable deprecation/deprecation */
    await loadEmitters(basedir, emit ?? [], emitterOptions ?? {});
    if (oldProgram &&
        mapEquals(oldProgram.sourceFiles, program.sourceFiles) &&
        deepEquals(oldProgram.compilerOptions, program.compilerOptions)) {
        return oldProgram;
    }
    // let GC reclaim old program, we do not reuse it beyond this point.
    oldProgram = undefined;
    const linter = createLinter(program, (name) => loadLibrary(basedir, name));
    if (options.linterRuleSet) {
        program.reportDiagnostics(await linter.extendRuleSet(options.linterRuleSet));
    }
    program.checker = createChecker(program);
    program.checker.checkProgram();
    if (!continueToNextStage) {
        return program;
    }
    // onValidate stage
    await runValidators();
    validateRequiredImports();
    await validateLoadedLibraries();
    if (!continueToNextStage) {
        return program;
    }
    // Linter stage
    program.reportDiagnostics(linter.lint());
    // Emitter stage
    for (const instance of emitters) {
        await runEmitter(instance);
    }
    return program;
    /**
     * Validate the libraries loaded during the compilation process are compatible.
     */
    async function validateLoadedLibraries() {
        const loadedRoots = new Set();
        // Check all the files that were loaded
        for (const fileUrl of getLibraryUrlsLoaded()) {
            if (fileUrl.startsWith("file:")) {
                const root = await findProjectRoot(host.stat, host.fileURLToPath(fileUrl));
                if (root) {
                    loadedRoots.add(root);
                }
            }
        }
        const libraries = new Map([...loadedLibraries.entries()]);
        const incompatibleLibraries = new Map();
        for (const root of loadedRoots) {
            const packageJsonPath = joinPaths(root, "package.json");
            try {
                const packageJson = JSON.parse((await host.readFile(packageJsonPath)).text);
                const found = libraries.get(packageJson.name);
                if (found && found.path !== root && found.manifest.version !== packageJson.version) {
                    let incompatibleIndex = incompatibleLibraries.get(packageJson.name);
                    if (incompatibleIndex === undefined) {
                        incompatibleIndex = [found];
                        incompatibleLibraries.set(packageJson.name, incompatibleIndex);
                    }
                    incompatibleIndex.push({ path: root, manifest: packageJson });
                }
            }
            catch { }
        }
        for (const [name, incompatibleLibs] of incompatibleLibraries) {
            reportDiagnostic(createDiagnostic({
                code: "incompatible-library",
                format: {
                    name: name,
                    versionMap: incompatibleLibs
                        .map((x) => `  - Version: "${x.manifest.version}" installed at "${x.path}"`)
                        .join("\n"),
                },
                target: NoTarget,
            }));
        }
    }
    async function loadIntrinsicTypes() {
        const locationContext = { type: "compiler" };
        await loadTypeSpecFile(resolvePath(host.getExecutionRoot(), "lib/intrinsics.tsp"), locationContext, NoTarget);
    }
    async function loadStandardLibrary() {
        const locationContext = { type: "compiler" };
        for (const dir of host.getLibDirs()) {
            await loadDirectory(dir, locationContext, NoTarget);
        }
    }
    async function loadDirectory(dir, locationContext, diagnosticTarget) {
        const mainFile = await resolveTypeSpecEntrypointForDir(host, dir, reportDiagnostic);
        await loadTypeSpecFile(mainFile, locationContext, diagnosticTarget);
        return mainFile;
    }
    async function loadTypeSpecFile(path, locationContext, diagnosticTarget) {
        if (seenSourceFiles.has(path)) {
            return;
        }
        seenSourceFiles.add(path);
        const file = await doIO(host.readFile, path, program.reportDiagnostic, {
            diagnosticTarget,
        });
        if (file) {
            sourceFileLocationContexts.set(file, locationContext);
            await loadTypeSpecScript(file);
        }
    }
    async function loadJsFile(path, locationContext, diagnosticTarget) {
        const sourceFile = program.jsSourceFiles.get(path);
        if (sourceFile !== undefined) {
            return sourceFile;
        }
        const file = createSourceFile("", path);
        sourceFileLocationContexts.set(file, locationContext);
        const exports = await doIO(host.getJsImport, path, program.reportDiagnostic, {
            diagnosticTarget,
            jsDiagnosticTarget: { file, pos: 0, end: 0 },
        });
        if (!exports) {
            return undefined;
        }
        return {
            kind: SyntaxKind.JsSourceFile,
            id: {
                kind: SyntaxKind.Identifier,
                sv: "",
                pos: 0,
                end: 0,
                symbol: undefined,
                flags: 8 /* NodeFlags.Synthetic */,
            },
            esmExports: exports,
            file,
            namespaceSymbols: [],
            symbol: undefined,
            pos: 0,
            end: 0,
            flags: 0 /* NodeFlags.None */,
        };
    }
    /**
     * Import the Javascript files decorator and lifecycle hooks.
     */
    async function importJsFile(path, locationContext, diagnosticTarget) {
        const file = await loadJsFile(path, locationContext, diagnosticTarget);
        if (file !== undefined) {
            program.jsSourceFiles.set(path, file);
            binder.bindJsSourceFile(file);
        }
    }
    async function loadTypeSpecScript(file) {
        // This is not a diagnostic because the compiler should never reuse the same path.
        // It's the caller's responsibility to use unique paths.
        if (program.sourceFiles.has(file.path)) {
            throw new RangeError("Duplicate script path: " + file.path);
        }
        const script = parseOrReuse(file);
        program.reportDiagnostics(script.parseDiagnostics);
        program.sourceFiles.set(file.path, script);
        binder.bindSourceFile(script);
        await loadScriptImports(script);
        return script;
    }
    function parseOrReuse(file) {
        const old = oldProgram?.sourceFiles.get(file.path) ?? host?.parseCache?.get(file);
        if (old?.file === file && deepEquals(old.parseOptions, options.parseOptions)) {
            return old;
        }
        const script = parse$2(file, options.parseOptions);
        host.parseCache?.set(file, script);
        return script;
    }
    async function loadScriptImports(file) {
        // collect imports
        const basedir = getDirectoryPath(file.file.path);
        await loadImports(file.statements.filter(isImportStatement).map((x) => ({ path: x.path.value, target: x })), basedir, getSourceFileLocationContext(file.file));
    }
    function getSourceFileLocationContext(sourcefile) {
        const locationContext = sourceFileLocationContexts.get(sourcefile);
        compilerAssert(locationContext, "SourceFile should have a declaration locationContext.");
        return locationContext;
    }
    async function loadImports(imports, relativeTo, locationContext) {
        // collect imports
        for (const { path, target } of imports) {
            await loadImport(path, target, relativeTo, locationContext);
        }
    }
    async function loadImport(path, target, relativeTo, locationContext) {
        const library = await resolveTypeSpecLibrary(path, relativeTo, target);
        if (library === undefined) {
            return;
        }
        if (library.type === "module") {
            loadedLibraries.set(library.manifest.name, {
                path: library.path,
                manifest: library.manifest,
            });
            trace("import-resolution.library", `Loading library "${path}" from "${library.mainFile}"`);
            const metadata = computeModuleMetadata(library);
            locationContext = {
                type: "library",
                metadata,
            };
        }
        const importFilePath = library.type === "module" ? library.mainFile : library.path;
        const isDirectory = (await host.stat(importFilePath)).isDirectory();
        if (isDirectory) {
            return await loadDirectory(importFilePath, locationContext, target);
        }
        const sourceFileKind = host.getSourceFileKind(importFilePath);
        switch (sourceFileKind) {
            case "js":
                return await importJsFile(importFilePath, locationContext, target);
            case "typespec":
                return await loadTypeSpecFile(importFilePath, locationContext, target);
            default:
                program.reportDiagnostic(createDiagnostic({ code: "invalid-import", target }));
        }
    }
    async function loadEmitters(basedir, emitterNameOrPaths, emitterOptions) {
        for (const emitterNameOrPath of emitterNameOrPaths) {
            const emitter = await loadEmitter(basedir, emitterNameOrPath, emitterOptions);
            if (emitter) {
                emitters.push(emitter);
            }
        }
    }
    async function resolveEmitterModuleAndEntrypoint(basedir, emitterNameOrPath) {
        const locationContext = { type: "project" };
        // attempt to resolve a node module with this name
        const [module, diagnostics] = await resolveJSLibrary(emitterNameOrPath, basedir);
        if (!module) {
            return [undefined, diagnostics];
        }
        const entrypoint = module.type === "file" ? module.path : module.mainFile;
        const file = await loadJsFile(entrypoint, locationContext, NoTarget);
        return [{ module, entrypoint: file }, []];
    }
    async function loadLibrary(basedir, libraryNameOrPath) {
        const [resolution, diagnostics] = await resolveEmitterModuleAndEntrypoint(basedir, libraryNameOrPath);
        if (resolution === undefined) {
            program.reportDiagnostics(diagnostics);
            return undefined;
        }
        const { module, entrypoint } = resolution;
        const libDefinition = entrypoint?.esmExports.$lib;
        const metadata = computeLibraryMetadata(module, libDefinition);
        // eslint-disable-next-line deprecation/deprecation
        const linterDef = entrypoint?.esmExports.$linter ?? libDefinition?.linter;
        return {
            ...resolution,
            metadata,
            definition: libDefinition,
            linter: linterDef && resolveLinterDefinition(libraryNameOrPath, linterDef),
        };
    }
    async function loadEmitter(basedir, emitterNameOrPath, emittersOptions) {
        const library = await loadLibrary(basedir, emitterNameOrPath);
        if (library === undefined) {
            return undefined;
        }
        const { entrypoint, metadata } = library;
        if (entrypoint === undefined) {
            program.reportDiagnostic(createDiagnostic({
                code: "invalid-emitter",
                format: { emitterPackage: emitterNameOrPath },
                target: NoTarget,
            }));
            return undefined;
        }
        const emitFunction = entrypoint.esmExports.$onEmit;
        const libDefinition = library.definition;
        let { "emitter-output-dir": emitterOutputDir, ...emitterOptions } = emittersOptions[metadata.name ?? emitterNameOrPath] ?? {};
        if (emitterOutputDir === undefined) {
            emitterOutputDir = [options.outputDir, metadata.name].filter(isDefined).join("/");
        }
        if (libDefinition?.requireImports) {
            for (const lib of libDefinition.requireImports) {
                requireImports.set(lib, libDefinition.name);
            }
        }
        if (emitFunction !== undefined) {
            if (libDefinition?.emitter?.options) {
                const diagnostics = libDefinition?.emitterOptionValidator?.validate(emitterOptions, options.configFile?.file
                    ? {
                        kind: "path-target",
                        path: ["options", emitterNameOrPath],
                        script: options.configFile.file,
                    }
                    : NoTarget);
                if (diagnostics && diagnostics.length > 0) {
                    program.reportDiagnostics(diagnostics);
                    return;
                }
            }
            return {
                main: entrypoint.file.path,
                emitFunction,
                metadata,
                emitterOutputDir,
                options: emitterOptions,
            };
        }
        else {
            program.reportDiagnostic(createDiagnostic({
                code: "invalid-emitter",
                format: { emitterPackage: emitterNameOrPath },
                target: NoTarget,
            }));
            return undefined;
        }
    }
    function computeLibraryMetadata(module, libDefinition) {
        if (module.type === "file") {
            return {
                type: "file",
                name: libDefinition?.name,
            };
        }
        return computeModuleMetadata(module);
    }
    function computeModuleMetadata(module) {
        const metadata = {
            type: "module",
            name: module.manifest.name,
        };
        if (module.manifest.homepage) {
            metadata.homepage = module.manifest.homepage;
        }
        if (module.manifest.bugs?.url) {
            metadata.bugs = { url: module.manifest.bugs?.url };
        }
        if (module.manifest.version) {
            metadata.version = module.manifest.version;
        }
        return metadata;
    }
    /**
     * @param emitter Emitter ref to run
     */
    async function runEmitter(emitter) {
        const context = {
            program,
            emitterOutputDir: emitter.emitterOutputDir,
            options: emitter.options,
            getAssetEmitter(TypeEmitterClass) {
                return createAssetEmitter(program, TypeEmitterClass, this);
            },
        };
        try {
            await emitter.emitFunction(context);
        }
        catch (error) {
            throw new ExternalError({ kind: "emitter", metadata: emitter.metadata, error });
        }
    }
    async function runValidators() {
        runCompilerValidators();
        for (const validator of validateCbs) {
            await runValidator(validator);
        }
    }
    async function runValidator(validator) {
        try {
            await validator.callback(program);
        }
        catch (error) {
            if (options.designTimeBuild) {
                program.reportDiagnostic(createDiagnostic({
                    code: "on-validate-fail",
                    format: { error: error.stack },
                    target: NoTarget,
                }));
            }
            else {
                throw new ExternalError({ kind: "validator", metadata: validator.metadata, error });
            }
        }
    }
    /** Run the compiler built-in validators */
    function runCompilerValidators() {
        validateEncodedNamesConflicts(program);
    }
    function validateRequiredImports() {
        for (const [requiredImport, emitterName] of requireImports) {
            if (!loadedLibraries.has(requiredImport)) {
                program.reportDiagnostic(createDiagnostic({
                    code: "missing-import",
                    format: { requiredImport, emitterName },
                    target: NoTarget,
                }));
            }
        }
    }
    /**
     * resolves a module specifier like "myLib" to an absolute path where we can find the main of
     * that module, e.g. "/typespec/node_modules/myLib/main.tsp".
     */
    async function resolveTypeSpecLibrary(specifier, baseDir, target) {
        try {
            return await resolveModule(getResolveModuleHost(), specifier, {
                baseDir,
                directoryIndexFiles: ["main.tsp", "index.mjs", "index.js"],
                resolveMain(pkg) {
                    // this lets us follow node resolve semantics more-or-less exactly
                    // but using tspMain instead of main.
                    return resolveTspMain(pkg) ?? pkg.main;
                },
            });
        }
        catch (e) {
            if (e.code === "MODULE_NOT_FOUND") {
                program.reportDiagnostic(createDiagnostic({ code: "import-not-found", format: { path: specifier }, target }));
                return undefined;
            }
            else if (e.code === "INVALID_MAIN") {
                program.reportDiagnostic(createDiagnostic({
                    code: "library-invalid",
                    format: { path: specifier },
                    messageId: "tspMain",
                    target,
                }));
                return undefined;
            }
            else {
                throw e;
            }
        }
    }
    /**
     * resolves a module specifier like "myLib" to an absolute path where we can find the main of
     * that module, e.g. "/typespec/node_modules/myLib/dist/lib.js".
     */
    async function resolveJSLibrary(specifier, baseDir, locationContext) {
        try {
            return [await resolveModule(getResolveModuleHost(), specifier, { baseDir }), []];
        }
        catch (e) {
            if (e.code === "MODULE_NOT_FOUND") {
                return [
                    undefined,
                    [
                        createDiagnostic({
                            code: "import-not-found",
                            format: { path: specifier },
                            target: NoTarget,
                        }),
                    ],
                ];
            }
            else if (e.code === "INVALID_MAIN") {
                return [
                    undefined,
                    [
                        createDiagnostic({
                            code: "library-invalid",
                            format: { path: specifier },
                            target: NoTarget,
                        }),
                    ],
                ];
            }
            else {
                throw e;
            }
        }
    }
    function getResolveModuleHost() {
        return {
            realpath: host.realpath,
            stat: host.stat,
            readFile: async (path) => {
                const file = await host.readFile(path);
                return file.text;
            },
        };
    }
    /**
     * Load the main file from the given path
     * @param mainPath Absolute path to the main file.
     */
    async function loadMain(mainPath) {
        await checkForCompilerVersionMismatch(mainPath);
        const sourceFileKind = host.getSourceFileKind(mainPath);
        const locationContext = { type: "project" };
        switch (sourceFileKind) {
            case "js":
                return await importJsFile(mainPath, locationContext, NoTarget);
            case "typespec":
                return await loadTypeSpecFile(mainPath, locationContext, NoTarget);
            default:
                program.reportDiagnostic(createDiagnostic({ code: "invalid-main", target: NoTarget }));
        }
    }
    // It's important that we use the compiler version that resolves locally
    // from the input TypeSpec source location. Otherwise, there will be undefined
    // runtime behavior when decorators and handlers expect a
    // different version of TypeSpec than the current one. Abort the compilation
    // with an error if the TypeSpec entry point resolves to a different local
    // compiler.
    async function checkForCompilerVersionMismatch(mainPath) {
        const baseDir = getDirectoryPath(mainPath);
        let actual;
        try {
            const resolved = await resolveModule({
                realpath: host.realpath,
                stat: host.stat,
                readFile: async (path) => {
                    const file = await host.readFile(path);
                    return file.text;
                },
            }, "@typespec/compiler", { baseDir });
            compilerAssert(resolved.type === "module", `Expected to have resolved "@typespec/compiler" to a node module.`);
            actual = resolved;
        }
        catch (err) {
            if (err.code === "MODULE_NOT_FOUND" || err.code === "INVALID_MAIN") {
                return true; // no local typespec, ok to use any compiler
            }
            throw err;
        }
        const expected = host.getExecutionRoot();
        if (actual.path !== expected && MANIFEST.version !== actual.manifest.version) {
            const betterTypeSpecServerPath = actual.path;
            program.reportDiagnostic(createDiagnostic({
                code: "compiler-version-mismatch",
                format: { basedir: baseDir, betterTypeSpecServerPath, actual: actual.path, expected },
                target: NoTarget,
            }));
            return false;
        }
        return true;
    }
    function getOption(key) {
        return (options.miscOptions || {})[key];
    }
    function reportDiagnostic(diagnostic) {
        if (shouldSuppress(diagnostic)) {
            return;
        }
        if (diagnostic.severity === "error") {
            continueToNextStage = false;
        }
        if (diagnostic.severity === "warning" && diagnostic.target !== NoTarget) {
            mutate(diagnostic).codefixes ??= [];
            mutate(diagnostic.codefixes).push(createSuppressCodeFix(diagnostic.target, diagnostic.code));
        }
        if (options.warningAsError && diagnostic.severity === "warning") {
            diagnostic = { ...diagnostic, severity: "error" };
        }
        if (diagnostic.severity === "error") {
            error = true;
        }
        diagnostics.push(diagnostic);
    }
    function reportDiagnostics(newDiagnostics) {
        for (const diagnostic of newDiagnostics) {
            reportDiagnostic(diagnostic);
        }
    }
    function shouldSuppress(diagnostic) {
        const { target } = diagnostic;
        if (diagnostic.code === "error") {
            diagnostics.push(diagnostic);
            return false;
        }
        if (target === NoTarget || target === undefined) {
            return false;
        }
        if ("file" in target) {
            return false; // No global file suppress yet.
        }
        const node = getNode(target);
        if (node === undefined) {
            return false; // Can't find target cannot be suppressed.
        }
        const suppressing = findDirectiveSuppressingOnNode(diagnostic.code, node);
        if (suppressing) {
            if (diagnostic.severity === "error") {
                // Cannot suppress errors.
                diagnostics.push({
                    severity: "error",
                    code: "suppress-error",
                    message: "Errors cannot be suppressed.",
                    target: suppressing.node,
                });
                return false;
            }
            else {
                return true;
            }
        }
        return false;
    }
    function findDirectiveSuppressingOnNode(code, node) {
        let current = node;
        do {
            if (current.directives) {
                const directive = findDirectiveSuppressingCode(code, current.directives);
                if (directive) {
                    return directive;
                }
            }
        } while ((current = current.parent));
        return undefined;
    }
    /**
     * Returns the directive node that is suppressing this code.
     * @param code Code to check for suppression.
     * @param directives List of directives.
     * @returns Directive suppressing this code if found, `undefined` otherwise
     */
    function findDirectiveSuppressingCode(code, directives) {
        for (const directive of directives.map((x) => parseDirective(x))) {
            if (directive.name === "suppress") {
                if (directive.code === code) {
                    return directive;
                }
            }
        }
        return undefined;
    }
    function parseDirective(node) {
        const args = node.arguments.map((x) => {
            return x.kind === SyntaxKind.Identifier ? x.sv : x.value;
        });
        switch (node.target.sv) {
            case "suppress":
                return { name: "suppress", code: args[0], message: args[1], node };
            case "deprecated":
                return { name: "deprecated", message: args[0], node };
            default:
                throw new Error("Unexpected directive name.");
        }
    }
    function getNode(target) {
        if (!("kind" in target) && !("valueKind" in target) && !("entityKind" in target)) {
            // symbol
            if (target.flags & 524288 /* SymbolFlags.Using */) {
                return target.symbolSource.declarations[0];
            }
            return target.declarations[0]; // handle multiple decls
        }
        else if ("kind" in target && typeof target.kind === "number") {
            // node
            return target;
        }
        else {
            // type
            return target.node;
        }
    }
    function reportDuplicateSymbols(symbols) {
        if (!symbols) {
            return;
        }
        for (const set of symbols.duplicates.values()) {
            for (const symbol of set) {
                if (!duplicateSymbols.has(symbol)) {
                    duplicateSymbols.add(symbol);
                    const name = symbol.flags & 524288 /* SymbolFlags.Using */ ? symbol.symbolSource.name : symbol.name;
                    reportDiagnostic(createDiagnostic({
                        code: "duplicate-symbol",
                        format: { name },
                        target: symbol,
                    }));
                }
            }
        }
    }
    function getGlobalNamespaceType() {
        return program.checker.getGlobalNamespaceType();
    }
    function resolveTypeReference(reference) {
        const [node, parseDiagnostics] = parseStandaloneTypeReference(reference);
        if (parseDiagnostics.length > 0) {
            return [undefined, parseDiagnostics];
        }
        const binder = createBinder(program);
        binder.bindNode(node);
        mutate(node).parent = program.checker.getGlobalNamespaceNode();
        return program.checker.resolveTypeReference(node);
    }
}
/**
 * Resolve compiler options from input options.
 */
function resolveOptions(options) {
    // eslint-disable-next-line deprecation/deprecation
    const outputDir = options.outputDir ?? options.outputPath;
    return {
        ...options,
        outputDir,
        outputPath: outputDir,
    };
}

/**
 * Create an helper to manager project names.
 * @param program Program
 * @param target Name of the projected name target(e.g. json, csharp, etc.)
 * @returns ProjectedNameView
 */
function createProjectedNameProgram(program, target) {
    const projectedProgram = projectProgram(program, [
        {
            projectionName: "target",
            arguments: [target],
        },
    ]);
    return {
        program: projectedProgram,
        getProjectedName,
    };
    function getProjectedName(type) {
        const baseType = findTypeInProjector(projectedProgram.projector, type);
        const projectedType = projectedProgram.projector.projectedTypes.get(baseType);
        if (projectedType === undefined ||
            !("name" in projectedType) ||
            projectedType.name === baseType.name) {
            return type.name;
        }
        return projectedType.name;
    }
}
// TODO will REALM help here?
function findTypeInProjector(projector, type) {
    if (type.projectionSource === undefined) {
        return type;
    }
    else if (type.projector === projector) {
        return type;
    }
    else {
        return findTypeInProjector(projector, type.projectionSource);
    }
}

const NodeHost = undefined;

function expandConfigVariables(config, expandOptions) {
    const diagnostics = createDiagnosticCollector();
    const builtInVars = {
        "project-root": config.projectRoot,
        cwd: expandOptions.cwd,
    };
    const commonVars = {
        ...builtInVars,
        ...diagnostics.pipe(resolveArgs(config.parameters, expandOptions.args, builtInVars)),
        env: diagnostics.pipe(resolveArgs(config.environmentVariables, expandOptions.env, builtInVars, true)),
    };
    const outputDir = diagnostics.pipe(resolveValue(expandOptions.outputDir ?? config.outputDir, commonVars));
    const result = { ...config, outputDir };
    if (config.options) {
        const options = {};
        for (const [name, emitterOptions] of Object.entries(config.options)) {
            const emitterVars = { ...commonVars, "output-dir": outputDir, "emitter-name": name };
            options[name] = diagnostics.pipe(resolveValues(emitterOptions, emitterVars));
        }
        result.options = options;
    }
    return diagnostics.wrap(result);
}
function resolveArgs(declarations, args, predefinedVariables, allowUnspecified = false) {
    const unmatchedArgs = new Set(Object.keys(args ?? {}));
    const result = {};
    if (declarations !== undefined) {
        for (const [name, definition] of Object.entries(declarations)) {
            unmatchedArgs.delete(name);
            result[name] = ignoreDiagnostics(resolveValue(args?.[name] ?? definition.default, predefinedVariables));
        }
    }
    if (!allowUnspecified) {
        const diagnostics = [...unmatchedArgs].map((unmatchedArg) => {
            return createDiagnostic({
                code: "config-invalid-argument",
                format: { name: unmatchedArg },
                target: NoTarget,
            });
        });
        return [result, diagnostics];
    }
    return [result, []];
}
const VariableInterpolationRegex = /{([a-zA-Z-_.]+)}/g;
function resolveValue(value, predefinedVariables) {
    const [result, diagnostics] = resolveValues({ value }, predefinedVariables);
    return [result.value, diagnostics];
}
function resolveValues(values, predefinedVariables = {}) {
    const diagnostics = [];
    const resolvedValues = {};
    const resolvingValues = new Set();
    function resolveValue(key) {
        resolvingValues.add(key);
        const value = values[key];
        if (!(typeof value === "string")) {
            return value;
        }
        return value.replace(VariableInterpolationRegex, (match, expression) => {
            return resolveExpression(expression) ?? `{${expression}}`;
        });
    }
    function resolveExpression(expression) {
        if (expression in resolvedValues) {
            return resolvedValues[expression];
        }
        if (resolvingValues.has(expression)) {
            diagnostics.push(createDiagnostic({
                code: "config-circular-variable",
                target: NoTarget,
                format: { name: expression },
            }));
            return undefined;
        }
        if (expression in values) {
            return resolveValue(expression);
        }
        const segments = expression.split(".");
        let resolved = predefinedVariables;
        for (const segment of segments) {
            resolved = resolved[segment];
            if (resolved === undefined) {
                return undefined;
            }
        }
        if (typeof resolved === "string") {
            return resolved;
        }
        else {
            return undefined;
        }
    }
    for (const key of Object.keys(values)) {
        resolvingValues.clear();
        if (key in resolvedValues) {
            continue;
        }
        resolvedValues[key] = resolveValue(key);
    }
    return [resolvedValues, diagnostics];
}

/**
 * Resolve the compiler options for the given entrypoint by resolving the tspconfig.yaml.
 * @param host Compiler host
 * @param options
 */
async function resolveCompilerOptions(host, options) {
    const diagnostics = createDiagnosticCollector();
    const entrypointStat = await doIO(host.stat, options.entrypoint, (diag) => diagnostics.add(diag), { allowFileNotFound: true });
    const configPath = options.configPath ??
        (entrypointStat?.isDirectory() ? options.entrypoint : getDirectoryPath(options.entrypoint));
    const config = await loadTypeSpecConfigForPath(host, configPath, options.configPath !== undefined, options.configPath === undefined);
    config.diagnostics.forEach((x) => diagnostics.add(x));
    const compilerOptions = diagnostics.pipe(resolveOptionsFromConfig(config, options));
    return diagnostics.wrap(compilerOptions);
}
/**
 * Resolve the compiler options from the given raw TypeSpec config
 * @param config TypeSpec config.
 * @param options Options for interpolation in the config.
 * @returns
 */
function resolveOptionsFromConfig(config, options) {
    const cwd = normalizePath(options.cwd);
    const diagnostics = createDiagnosticCollector();
    const configWithOverrides = {
        ...config,
        ...options.overrides,
        options: mergeOptions(config.options, options.overrides?.options),
    };
    const expandedConfig = diagnostics.pipe(expandConfigVariables(configWithOverrides, {
        cwd,
        outputDir: options.overrides?.outputDir,
        env: options.env ?? {},
        args: options.args,
    }));
    validateConfigPathsAbsolute(expandedConfig).forEach((x) => diagnostics.add(x));
    const resolvedOptions = omitUndefined({
        outputDir: expandedConfig.outputDir,
        config: config.filename,
        configFile: config,
        additionalImports: expandedConfig["imports"],
        warningAsError: expandedConfig.warnAsError,
        trace: expandedConfig.trace,
        emit: expandedConfig.emit,
        options: expandedConfig.options,
        linterRuleSet: expandedConfig.linter,
    });
    return diagnostics.wrap(resolvedOptions);
}
function mergeOptions(base, overrides) {
    const configuredEmitters = deepClone(base ?? {});
    for (const [emitterName, cliOptionOverride] of Object.entries(overrides ?? {})) {
        configuredEmitters[emitterName] = {
            ...(configuredEmitters[emitterName] ?? {}),
            ...cliOptionOverride,
        };
    }
    return configuredEmitters;
}

function clampProp(e, n, t, o, r) {
  return clampEntity(n, getDefinedProp(e, n), t, o, r);
}

function clampEntity(e, n, t, o, r, i) {
  const a = clampNumber(n, t, o);
  if (r && n !== a) {
    throw new RangeError(numberOutOfRange(e, n, t, o, i));
  }
  return a;
}

function getDefinedProp(e, n) {
  const t = e[n];
  if (void 0 === t) {
    throw new TypeError(missingField(n));
  }
  return t;
}

function z(e) {
  return null !== e && /object|function/.test(typeof e);
}

function Jn(e, n = Map) {
  const t = new n;
  return (n, ...o) => {
    if (t.has(n)) {
      return t.get(n);
    }
    const r = e(n, ...o);
    return t.set(n, r), r;
  };
}

function D(e) {
  return p({
    name: e
  }, 1);
}

function p(e, n) {
  return T((e => ({
    value: e,
    configurable: 1,
    writable: !n
  })), e);
}

function O(e) {
  return T((e => ({
    get: e,
    configurable: 1
  })), e);
}

function h(e) {
  return {
    [Symbol.toStringTag]: {
      value: e,
      configurable: 1
    }
  };
}

function zipProps(e, n) {
  const t = {};
  let o = e.length;
  for (const r of n) {
    t[e[--o]] = r;
  }
  return t;
}

function T(e, n, t) {
  const o = {};
  for (const r in n) {
    o[r] = e(n[r], r, t);
  }
  return o;
}

function b(e, n, t) {
  const o = {};
  for (let r = 0; r < n.length; r++) {
    const i = n[r];
    o[i] = e(i, r, t);
  }
  return o;
}

function remapProps(e, n, t) {
  const o = {};
  for (let r = 0; r < e.length; r++) {
    o[n[r]] = t[e[r]];
  }
  return o;
}

function Vn(e, n) {
  const t = {};
  for (const o of e) {
    t[o] = n[o];
  }
  return t;
}

function V(e, n) {
  const t = {};
  for (const o in n) {
    e.has(o) || (t[o] = n[o]);
  }
  return t;
}

function nn(e) {
  e = {
    ...e
  };
  const n = Object.keys(e);
  for (const t of n) {
    void 0 === e[t] && delete e[t];
  }
  return e;
}

function C(e, n) {
  for (const t of n) {
    if (!(t in e)) {
      return 0;
    }
  }
  return 1;
}

function allPropsEqual(e, n, t) {
  for (const o of e) {
    if (n[o] !== t[o]) {
      return 0;
    }
  }
  return 1;
}

function zeroOutProps(e, n, t) {
  const o = {
    ...t
  };
  for (let t = 0; t < n; t++) {
    o[e[t]] = 0;
  }
  return o;
}

function E(e, ...n) {
  return (...t) => e(...n, ...t);
}

function capitalize(e) {
  return e[0].toUpperCase() + e.substring(1);
}

function sortStrings(e) {
  return e.slice().sort();
}

function padNumber(e, n) {
  return String(n).padStart(e, "0");
}

function compareNumbers(e, n) {
  return Math.sign(e - n);
}

function clampNumber(e, n, t) {
  return Math.min(Math.max(e, n), t);
}

function divModFloor(e, n) {
  return [ Math.floor(e / n), modFloor(e, n) ];
}

function modFloor(e, n) {
  return (e % n + n) % n;
}

function divModTrunc(e, n) {
  return [ divTrunc(e, n), modTrunc(e, n) ];
}

function divTrunc(e, n) {
  return Math.trunc(e / n) || 0;
}

function modTrunc(e, n) {
  return e % n || 0;
}

function hasHalf(e) {
  return .5 === Math.abs(e % 1);
}

function givenFieldsToBigNano(e, n, t) {
  let o = 0, r = 0;
  for (let i = 0; i <= n; i++) {
    const n = e[t[i]], a = Xr[i], s = Qr / a, [c, u] = divModTrunc(n, s);
    o += u * a, r += c;
  }
  const [i, a] = divModTrunc(o, Qr);
  return [ r + i, a ];
}

function nanoToGivenFields(e, n, t) {
  const o = {};
  for (let r = n; r >= 0; r--) {
    const n = Xr[r];
    o[t[r]] = divTrunc(e, n), e = modTrunc(e, n);
  }
  return o;
}

function un(e) {
  return e === X ? si : [];
}

function cn(e) {
  return e === X ? li : [];
}

function ln(e) {
  return e === X ? [ "year", "day" ] : [];
}

function l(e) {
  if (void 0 !== e) {
    return m(e);
  }
}

function S(e) {
  if (void 0 !== e) {
    return d(e);
  }
}

function c(e) {
  if (void 0 !== e) {
    return u(e);
  }
}

function d(e) {
  return requireNumberIsPositive(u(e));
}

function u(e) {
  return requireNumberIsInteger(Mi(e));
}

function on(e) {
  if (null == e) {
    throw new TypeError("Cannot be null or undefined");
  }
  return e;
}

function requirePropDefined(e, n) {
  if (null == n) {
    throw new RangeError(missingField(e));
  }
  return n;
}

function de(e) {
  if (!z(e)) {
    throw new TypeError(hr);
  }
  return e;
}

function requireType(e, n, t = e) {
  if (typeof n !== e) {
    throw new TypeError(invalidEntity(t, n));
  }
  return n;
}

function requireNumberIsInteger(e, n = "number") {
  if (!Number.isInteger(e)) {
    throw new RangeError(expectedInteger(n, e));
  }
  return e || 0;
}

function requireNumberIsPositive(e, n = "number") {
  if (e <= 0) {
    throw new RangeError(expectedPositive(n, e));
  }
  return e;
}

function toString(e) {
  if ("symbol" == typeof e) {
    throw new TypeError(pr);
  }
  return String(e);
}

function toStringViaPrimitive(e, n) {
  return z(e) ? String(e) : m(e, n);
}

function toBigInt(e) {
  if ("string" == typeof e) {
    return BigInt(e);
  }
  if ("bigint" != typeof e) {
    throw new TypeError(invalidBigInt(e));
  }
  return e;
}

function toNumber(e, n = "number") {
  if ("bigint" == typeof e) {
    throw new TypeError(forbiddenBigIntToNumber(n));
  }
  if (e = Number(e), !Number.isFinite(e)) {
    throw new RangeError(expectedFinite(n, e));
  }
  return e;
}

function toInteger(e, n) {
  return Math.trunc(toNumber(e, n)) || 0;
}

function toStrictInteger(e, n) {
  return requireNumberIsInteger(toNumber(e, n), n);
}

function toPositiveInteger(e, n) {
  return requireNumberIsPositive(toInteger(e, n), n);
}

function createBigNano(e, n) {
  let [t, o] = divModTrunc(n, Qr), r = e + t;
  const i = Math.sign(r);
  return i && i === -Math.sign(o) && (r -= i, o += i * Qr), [ r, o ];
}

function addBigNanos(e, n, t = 1) {
  return createBigNano(e[0] + n[0] * t, e[1] + n[1] * t);
}

function moveBigNano(e, n) {
  return createBigNano(e[0], e[1] + n);
}

function re(e, n) {
  return addBigNanos(n, e, -1);
}

function te(e, n) {
  return compareNumbers(e[0], n[0]) || compareNumbers(e[1], n[1]);
}

function bigNanoOutside(e, n, t) {
  return -1 === te(e, n) || 1 === te(e, t);
}

function bigIntToBigNano(e, n = 1) {
  const t = BigInt(Qr / n);
  return [ Number(e / t), Number(e % t) * n ];
}

function he(e, n = 1) {
  const t = Qr / n, [o, r] = divModTrunc(e, t);
  return [ o, r * n ];
}

function bigNanoToBigInt(e, n = 1) {
  const [t, o] = e, r = Math.floor(o / n), i = Qr / n;
  return BigInt(t) * BigInt(i) + BigInt(r);
}

function oe(e, n = 1, t) {
  const [o, r] = e, [i, a] = divModTrunc(r, n);
  return o * (Qr / n) + (i + (t ? a / n : 0));
}

function divModBigNano(e, n, t = divModFloor) {
  const [o, r] = e, [i, a] = t(r, n);
  return [ o * (Qr / n) + i, a ];
}

function hashIntlFormatParts(e, n) {
  const t = e.formatToParts(n), o = {};
  for (const e of t) {
    o[e.type] = e.value;
  }
  return o;
}

function checkIsoYearMonthInBounds(e) {
  return clampProp(e, "isoYear", Li, Ai, 1), e.isoYear === Li ? clampProp(e, "isoMonth", 4, 12, 1) : e.isoYear === Ai && clampProp(e, "isoMonth", 1, 9, 1), 
  e;
}

function checkIsoDateInBounds(e) {
  return checkIsoDateTimeInBounds({
    ...e,
    ...Dt,
    isoHour: 12
  }), e;
}

function checkIsoDateTimeInBounds(e) {
  const n = clampProp(e, "isoYear", Li, Ai, 1), t = n === Li ? 1 : n === Ai ? -1 : 0;
  return t && checkEpochNanoInBounds(isoToEpochNano({
    ...e,
    isoDay: e.isoDay + t,
    isoNanosecond: e.isoNanosecond - t
  })), e;
}

function checkEpochNanoInBounds(e) {
  if (!e || bigNanoOutside(e, Ui, qi)) {
    throw new RangeError(Cr);
  }
  return e;
}

function isoTimeFieldsToNano(e) {
  return givenFieldsToBigNano(e, 5, j)[1];
}

function nanoToIsoTimeAndDay(e) {
  const [n, t] = divModFloor(e, Qr);
  return [ nanoToGivenFields(t, 5, j), n ];
}

function epochNanoToSec(e) {
  return epochNanoToSecMod(e)[0];
}

function epochNanoToSecMod(e) {
  return divModBigNano(e, _r);
}

function isoToEpochMilli(e) {
  return isoArgsToEpochMilli(e.isoYear, e.isoMonth, e.isoDay, e.isoHour, e.isoMinute, e.isoSecond, e.isoMillisecond);
}

function isoToEpochNano(e) {
  const n = isoToEpochMilli(e);
  if (void 0 !== n) {
    const [t, o] = divModTrunc(n, Gr);
    return [ t, o * be + (e.isoMicrosecond || 0) * Vr + (e.isoNanosecond || 0) ];
  }
}

function isoToEpochNanoWithOffset(e, n) {
  const [t, o] = nanoToIsoTimeAndDay(isoTimeFieldsToNano(e) - n);
  return checkEpochNanoInBounds(isoToEpochNano({
    ...e,
    isoDay: e.isoDay + o,
    ...t
  }));
}

function isoArgsToEpochSec(...e) {
  return isoArgsToEpochMilli(...e) / Hr;
}

function isoArgsToEpochMilli(...e) {
  const [n, t] = isoToLegacyDate(...e), o = n.valueOf();
  if (!isNaN(o)) {
    return o - t * Gr;
  }
}

function isoToLegacyDate(e, n = 1, t = 1, o = 0, r = 0, i = 0, a = 0) {
  const s = e === Li ? 1 : e === Ai ? -1 : 0, c = new Date;
  return c.setUTCHours(o, r, i, a), c.setUTCFullYear(e, n - 1, t + s), [ c, s ];
}

function Ie(e, n) {
  let [t, o] = moveBigNano(e, n);
  o < 0 && (o += Qr, t -= 1);
  const [r, i] = divModFloor(o, be), [a, s] = divModFloor(i, Vr);
  return epochMilliToIso(t * Gr + r, a, s);
}

function epochMilliToIso(e, n = 0, t = 0) {
  const o = Math.ceil(Math.max(0, Math.abs(e) - zi) / Gr) * Math.sign(e), r = new Date(e - o * Gr);
  return zipProps(wi, [ r.getUTCFullYear(), r.getUTCMonth() + 1, r.getUTCDate() + o, r.getUTCHours(), r.getUTCMinutes(), r.getUTCSeconds(), r.getUTCMilliseconds(), n, t ]);
}

function computeIsoDateParts(e) {
  return [ e.isoYear, e.isoMonth, e.isoDay ];
}

function computeIsoMonthsInYear() {
  return xi;
}

function computeIsoDaysInMonth(e, n) {
  switch (n) {
   case 2:
    return computeIsoInLeapYear(e) ? 29 : 28;

   case 4:
   case 6:
   case 9:
   case 11:
    return 30;
  }
  return 31;
}

function computeIsoDaysInYear(e) {
  return computeIsoInLeapYear(e) ? 366 : 365;
}

function computeIsoInLeapYear(e) {
  return e % 4 == 0 && (e % 100 != 0 || e % 400 == 0);
}

function computeIsoDayOfWeek(e) {
  const [n, t] = isoToLegacyDate(e.isoYear, e.isoMonth, e.isoDay);
  return modFloor(n.getUTCDay() - t, 7) || 7;
}

function computeGregoryEraParts({isoYear: e}) {
  return e < 1 ? [ "bce", 1 - e ] : [ "ce", e ];
}

function computeJapaneseEraParts(e) {
  const n = isoToEpochMilli(e);
  if (n < $i) {
    return computeGregoryEraParts(e);
  }
  const t = hashIntlFormatParts(La(Ti), n), {era: o, eraYear: r} = parseIntlYear(t, Ti);
  return [ o, r ];
}

function checkIsoDateTimeFields(e) {
  return checkIsoDateFields(e), constrainIsoTimeFields(e, 1), e;
}

function checkIsoDateFields(e) {
  return constrainIsoDateFields(e, 1), e;
}

function isIsoDateFieldsValid(e) {
  return allPropsEqual(Oi, e, constrainIsoDateFields(e));
}

function constrainIsoDateFields(e, n) {
  const {isoYear: t} = e, o = clampProp(e, "isoMonth", 1, computeIsoMonthsInYear(), n);
  return {
    isoYear: t,
    isoMonth: o,
    isoDay: clampProp(e, "isoDay", 1, computeIsoDaysInMonth(t, o), n)
  };
}

function constrainIsoTimeFields(e, n) {
  return zipProps(j, [ clampProp(e, "isoHour", 0, 23, n), clampProp(e, "isoMinute", 0, 59, n), clampProp(e, "isoSecond", 0, 59, n), clampProp(e, "isoMillisecond", 0, 999, n), clampProp(e, "isoMicrosecond", 0, 999, n), clampProp(e, "isoNanosecond", 0, 999, n) ]);
}

function H(e) {
  return void 0 === e ? 0 : ua(de(e));
}

function wn(e, n = 0) {
  e = normalizeOptions(e);
  const t = la(e), o = fa(e, n);
  return [ ua(e), o, t ];
}

function ve(e) {
  return la(normalizeOptions(e));
}

function _t(e) {
  return e = normalizeOptions(e), sa(e, 9, 6, 1);
}

function refineDiffOptions(e, n, t, o = 9, r = 0, i = 4) {
  n = normalizeOptions(n);
  let a = sa(n, o, r), s = parseRoundingIncInteger(n), c = ha(n, i);
  const u = aa(n, o, r, 1);
  return null == a ? a = Math.max(t, u) : checkLargestSmallestUnit(a, u), s = refineRoundingInc(s, u, 1), 
  e && (c = (e => e < 4 ? (e + 2) % 4 : e)(c)), [ a, u, s, c ];
}

function refineRoundingOptions(e, n = 6, t) {
  let o = parseRoundingIncInteger(e = normalizeOptionsOrString(e, Hi));
  const r = ha(e, 7);
  let i = aa(e, n);
  return i = requirePropDefined(Hi, i), o = refineRoundingInc(o, i, void 0, t), [ i, o, r ];
}

function refineDateDisplayOptions(e) {
  return da(normalizeOptions(e));
}

function refineTimeDisplayOptions(e, n) {
  return refineTimeDisplayTuple(normalizeOptions(e), n);
}

function refineTimeDisplayTuple(e, n = 4) {
  const t = refineSubsecDigits(e);
  return [ ha(e, 4), ...refineSmallestUnitAndSubsecDigits(aa(e, n), t) ];
}

function refineSmallestUnitAndSubsecDigits(e, n) {
  return null != e ? [ Xr[e], e < 4 ? 9 - 3 * e : -1 ] : [ void 0 === n ? 1 : 10 ** (9 - n), n ];
}

function parseRoundingIncInteger(e) {
  const n = e[_i];
  return void 0 === n ? 1 : toInteger(n, _i);
}

function refineRoundingInc(e, n, t, o) {
  const r = o ? Qr : Xr[n + 1];
  if (r) {
    const t = Xr[n];
    if (r % ((e = clampEntity(_i, e, 1, r / t - (o ? 0 : 1), 1)) * t)) {
      throw new RangeError(invalidEntity(_i, e));
    }
  } else {
    e = clampEntity(_i, e, 1, t ? 10 ** 9 : 1, 1);
  }
  return e;
}

function refineSubsecDigits(e) {
  let n = e[Ji];
  if (void 0 !== n) {
    if ("number" != typeof n) {
      if ("auto" === toString(n)) {
        return;
      }
      throw new RangeError(invalidEntity(Ji, n));
    }
    n = clampEntity(Ji, Math.floor(n), 0, 9, 1);
  }
  return n;
}

function normalizeOptions(e) {
  return void 0 === e ? {} : de(e);
}

function normalizeOptionsOrString(e, n) {
  return "string" == typeof e ? {
    [n]: e
  } : de(e);
}

function U(e) {
  if (void 0 !== e) {
    if (z(e)) {
      return Object.assign(Object.create(null), e);
    }
    throw new TypeError(hr);
  }
}

function overrideOverflowOptions(e, n) {
  return e && Object.assign(Object.create(null), e, {
    overflow: Xi[n]
  });
}

function refineUnitOption(e, n, t = 9, o = 0, r) {
  let i = n[e];
  if (void 0 === i) {
    return r ? o : void 0;
  }
  if (i = toString(i), "auto" === i) {
    return r ? o : null;
  }
  let a = $r[i];
  if (void 0 === a && (a = Ei[i]), void 0 === a) {
    throw new RangeError(invalidChoice(e, i, $r));
  }
  return clampEntity(e, a, o, t, 1, Et), a;
}

function refineChoiceOption(e, n, t, o = 0) {
  const r = t[e];
  if (void 0 === r) {
    return o;
  }
  const i = toString(r), a = n[i];
  if (void 0 === a) {
    throw new RangeError(invalidChoice(e, i, n));
  }
  return a;
}

function checkLargestSmallestUnit(e, n) {
  if (n > e) {
    throw new RangeError(Ar);
  }
}

function _(e) {
  return {
    branding: Oe,
    epochNanoseconds: e
  };
}

function Yn(e, n, t) {
  return {
    branding: Te,
    calendar: t,
    timeZone: n,
    epochNanoseconds: e
  };
}

function ee(e, n = e.calendar) {
  return {
    branding: We,
    calendar: n,
    ...Vn(Yi, e)
  };
}

function v(e, n = e.calendar) {
  return {
    branding: J,
    calendar: n,
    ...Vn(Bi, e)
  };
}

function createPlainYearMonthSlots(e, n = e.calendar) {
  return {
    branding: L,
    calendar: n,
    ...Vn(Bi, e)
  };
}

function createPlainMonthDaySlots(e, n = e.calendar) {
  return {
    branding: q,
    calendar: n,
    ...Vn(Bi, e)
  };
}

function Ge(e) {
  return {
    branding: xe,
    ...Vn(ki, e)
  };
}

function Vt(e) {
  return {
    branding: qt,
    sign: computeDurationSign(e),
    ...Vn(Ni, e)
  };
}

function M(e) {
  return epochNanoToSec(e.epochNanoseconds);
}

function y(e) {
  return divModBigNano(e.epochNanoseconds, be)[0];
}

function N(e) {
  return bigNanoToBigInt(e.epochNanoseconds, Vr);
}

function B(e) {
  return bigNanoToBigInt(e.epochNanoseconds);
}

function extractEpochNano(e) {
  return e.epochNanoseconds;
}

function I(e) {
  return "string" == typeof e ? e : m(e.id);
}

function isIdLikeEqual(e, n) {
  return e === n || I(e) === I(n);
}

function Ut(e, n, t, o, r) {
  const i = getMaxDurationUnit(o), [a, s] = ((e, n) => {
    const t = n((e = normalizeOptionsOrString(e, Vi))[Ki]);
    let o = ca(e);
    return o = requirePropDefined(Vi, o), [ o, t ];
  })(r, e);
  if (isUniformUnit(Math.max(a, i), s)) {
    return totalDayTimeDuration(o, a);
  }
  if (!s) {
    throw new RangeError(zr);
  }
  const [c, u, l] = createMarkerSystem(n, t, s), f = createMarkerToEpochNano(l), d = createMoveMarker(l), m = createDiffMarkers(l), p = d(u, c, o), h = m(u, c, p, a);
  return isUniformUnit(a, s) ? totalDayTimeDuration(h, a) : ((e, n, t, o, r, i, a) => {
    const s = computeDurationSign(e), [c, u] = clampRelativeDuration(o, bi(t, e), t, s, r, i, a), l = computeEpochNanoFrac(n, c, u);
    return e[F[t]] + l * s;
  })(h, f(p), a, u, c, f, d);
}

function totalDayTimeDuration(e, n) {
  return oe(durationFieldsToBigNano(e), Xr[n], 1);
}

function clampRelativeDuration(e, n, t, o, r, i, a) {
  const s = F[t], c = {
    ...n,
    [s]: n[s] + o
  }, u = a(e, r, n), l = a(e, r, c);
  return [ i(u), i(l) ];
}

function computeEpochNanoFrac(e, n, t) {
  const o = oe(re(n, t));
  if (!o) {
    throw new RangeError(vr);
  }
  return oe(re(n, e)) / o;
}

function ce(e, n) {
  const [t, o, r] = refineRoundingOptions(n, 5, 1);
  return _(roundBigNano(e.epochNanoseconds, t, o, r, 1));
}

function Pn(e, n, t) {
  let {epochNanoseconds: o, timeZone: r, calendar: i} = n;
  const [a, s, c] = refineRoundingOptions(t);
  if (0 === a && 1 === s) {
    return n;
  }
  const u = e(r);
  if (6 === a) {
    o = ((e, n, t, o) => {
      const r = fn(t, n), [i, a] = e(r), s = t.epochNanoseconds, c = we(n, i), u = we(n, a);
      if (bigNanoOutside(s, c, u)) {
        throw new RangeError(vr);
      }
      return roundWithMode(computeEpochNanoFrac(s, c, u), o) ? u : c;
    })(computeDayInterval, u, n, c);
  } else {
    const e = u.getOffsetNanosecondsFor(o);
    o = getMatchingInstantFor(u, roundDateTime(Ie(o, e), a, s, c), e, 2, 0, 1);
  }
  return Yn(o, r, i);
}

function dt(e, n) {
  return ee(roundDateTime(e, ...refineRoundingOptions(n)), e.calendar);
}

function Ee(e, n) {
  const [t, o, r] = refineRoundingOptions(n, 5);
  var i;
  return Ge((i = r, roundTimeToNano(e, computeNanoInc(t, o), i)[0]));
}

function dn(e, n) {
  const t = e(n.timeZone), o = fn(n, t), [r, i] = computeDayInterval(o), a = oe(re(we(t, r), we(t, i)), Kr, 1);
  if (a <= 0) {
    throw new RangeError(vr);
  }
  return a;
}

function Cn(e, n) {
  const {timeZone: t, calendar: o} = n, r = ((e, n, t) => we(n, e(fn(t, n))))(computeDayFloor, e(t), n);
  return Yn(r, t, o);
}

function roundDateTime(e, n, t, o) {
  return roundDateTimeToNano(e, computeNanoInc(n, t), o);
}

function roundDateTimeToNano(e, n, t) {
  const [o, r] = roundTimeToNano(e, n, t);
  return checkIsoDateTimeInBounds({
    ...moveByDays(e, r),
    ...o
  });
}

function roundTimeToNano(e, n, t) {
  return nanoToIsoTimeAndDay(roundByInc(isoTimeFieldsToNano(e), n, t));
}

function roundToMinute(e) {
  return roundByInc(e, Jr, 7);
}

function computeNanoInc(e, n) {
  return Xr[e] * n;
}

function computeDayInterval(e) {
  const n = computeDayFloor(e);
  return [ n, moveByDays(n, 1) ];
}

function computeDayFloor(e) {
  return Ci(6, e);
}

function roundDayTimeDurationByInc(e, n, t) {
  const o = Math.min(getMaxDurationUnit(e), 6);
  return nanoToDurationDayTimeFields(roundBigNanoByInc(durationFieldsToBigNano(e, o), n, t), o);
}

function roundRelativeDuration(e, n, t, o, r, i, a, s, c, u) {
  if (0 === o && 1 === r) {
    return e;
  }
  const l = isUniformUnit(o, s) ? isZonedEpochSlots(s) && o < 6 && t >= 6 ? nudgeZonedTimeDuration : nudgeDayTimeDuration : nudgeRelativeDuration;
  let [f, d, m] = l(e, n, t, o, r, i, a, s, c, u);
  return m && 7 !== o && (f = ((e, n, t, o, r, i, a, s) => {
    const c = computeDurationSign(e);
    for (let u = o + 1; u <= t; u++) {
      if (7 === u && 7 !== t) {
        continue;
      }
      const o = bi(u, e);
      o[F[u]] += c;
      const l = oe(re(a(s(r, i, o)), n));
      if (l && Math.sign(l) !== c) {
        break;
      }
      e = o;
    }
    return e;
  })(f, d, t, Math.max(6, o), a, s, c, u)), f;
}

function roundBigNano(e, n, t, o, r) {
  if (6 === n) {
    const n = (e => e[0] + e[1] / Qr)(e);
    return [ roundByInc(n, t, o), 0 ];
  }
  return roundBigNanoByInc(e, computeNanoInc(n, t), o, r);
}

function roundBigNanoByInc(e, n, t, o) {
  let [r, i] = e;
  o && i < 0 && (i += Qr, r -= 1);
  const [a, s] = divModFloor(roundByInc(i, n, t), Qr);
  return createBigNano(r + a, s);
}

function roundByInc(e, n, t) {
  return roundWithMode(e / n, t) * n;
}

function roundWithMode(e, n) {
  return ga[n](e);
}

function nudgeDayTimeDuration(e, n, t, o, r, i) {
  const a = computeDurationSign(e), s = durationFieldsToBigNano(e), c = roundBigNano(s, o, r, i), u = re(s, c), l = Math.sign(c[0] - s[0]) === a, f = nanoToDurationDayTimeFields(c, Math.min(t, 6));
  return [ {
    ...e,
    ...f
  }, addBigNanos(n, u), l ];
}

function nudgeZonedTimeDuration(e, n, t, o, r, i, a, s, c, u) {
  const l = computeDurationSign(e), f = oe(durationFieldsToBigNano(e, 5)), d = computeNanoInc(o, r);
  let m = roundByInc(f, d, i);
  const [p, h] = clampRelativeDuration(a, {
    ...e,
    ...Fi
  }, 6, l, s, c, u), g = m - oe(re(p, h));
  let T = 0;
  g && Math.sign(g) !== l ? n = moveBigNano(p, m) : (T += l, m = roundByInc(g, d, i), 
  n = moveBigNano(h, m));
  const D = nanoToDurationTimeFields(m);
  return [ {
    ...e,
    ...D,
    days: e.days + T
  }, n, Boolean(T) ];
}

function nudgeRelativeDuration(e, n, t, o, r, i, a, s, c, u) {
  const l = computeDurationSign(e), f = F[o], d = bi(o, e);
  7 === o && (e = {
    ...e,
    weeks: e.weeks + Math.trunc(e.days / 7)
  });
  const m = divTrunc(e[f], r) * r;
  d[f] = m;
  const [p, h] = clampRelativeDuration(a, d, o, r * l, s, c, u), g = m + computeEpochNanoFrac(n, p, h) * l * r, T = roundByInc(g, r, i), D = Math.sign(T - g) === l;
  return d[f] = T, [ d, D ? h : p, D ];
}

function me(e, n, t, o) {
  const [r, i, a, s] = (e => {
    const n = refineTimeDisplayTuple(e = normalizeOptions(e));
    return [ e.timeZone, ...n ];
  })(o), c = void 0 !== r;
  return ((e, n, t, o, r, i) => {
    t = roundBigNanoByInc(t, r, o, 1);
    const a = n.getOffsetNanosecondsFor(t);
    return formatIsoDateTimeFields(Ie(t, a), i) + (e ? Fe(roundToMinute(a)) : "Z");
  })(c, n(c ? e(r) : Ta), t.epochNanoseconds, i, a, s);
}

function In(e, n, t) {
  const [o, r, i, a, s, c] = (e => {
    e = normalizeOptions(e);
    const n = da(e), t = refineSubsecDigits(e), o = pa(e), r = ha(e, 4), i = aa(e, 4);
    return [ n, ma(e), o, r, ...refineSmallestUnitAndSubsecDigits(i, t) ];
  })(t);
  return ((e, n, t, o, r, i, a, s, c, u) => {
    o = roundBigNanoByInc(o, c, s, 1);
    const l = e(t).getOffsetNanosecondsFor(o);
    return formatIsoDateTimeFields(Ie(o, l), u) + Fe(roundToMinute(l), a) + ((e, n) => 1 !== n ? "[" + (2 === n ? "!" : "") + I(e) + "]" : "")(t, i) + formatCalendar(n, r);
  })(e, n.calendar, n.timeZone, n.epochNanoseconds, o, r, i, a, s, c);
}

function Tt(e, n) {
  const [t, o, r, i] = (e => (e = normalizeOptions(e), [ da(e), ...refineTimeDisplayTuple(e) ]))(n);
  return a = e.calendar, s = t, c = i, formatIsoDateTimeFields(roundDateTimeToNano(e, r, o), c) + formatCalendar(a, s);
  var a, s, c;
}

function yt(e, n) {
  return t = e.calendar, o = e, r = refineDateDisplayOptions(n), formatIsoDateFields(o) + formatCalendar(t, r);
  var t, o, r;
}

function et(e, n) {
  return formatDateLikeIso(e.calendar, formatIsoYearMonthFields, e, refineDateDisplayOptions(n));
}

function W(e, n) {
  return formatDateLikeIso(e.calendar, formatIsoMonthDayFields, e, refineDateDisplayOptions(n));
}

function qe(e, n) {
  const [t, o, r] = refineTimeDisplayOptions(n);
  return i = r, formatIsoTimeFields(roundTimeToNano(e, o, t)[0], i);
  var i;
}

function zt(e, n) {
  const [t, o, r] = refineTimeDisplayOptions(n, 3);
  return o > 1 && (e = {
    ...e,
    ...roundDayTimeDurationByInc(e, o, t)
  }), ((e, n) => {
    const {sign: t} = e, o = -1 === t ? negateDurationFields(e) : e, {hours: r, minutes: i} = o, [a, s] = divModBigNano(durationFieldsToBigNano(o, 3), _r, divModTrunc);
    checkDurationTimeUnit(a);
    const c = formatSubsecNano(s, n), u = n >= 0 || !t || c;
    return (t < 0 ? "-" : "") + "P" + formatDurationFragments({
      Y: formatDurationNumber(o.years),
      M: formatDurationNumber(o.months),
      W: formatDurationNumber(o.weeks),
      D: formatDurationNumber(o.days)
    }) + (r || i || a || u ? "T" + formatDurationFragments({
      H: formatDurationNumber(r),
      M: formatDurationNumber(i),
      S: formatDurationNumber(a, u) + c
    }) : "");
  })(e, r);
}

function formatDateLikeIso(e, n, t, o) {
  const r = I(e), i = o > 1 || 0 === o && r !== X;
  return 1 === o ? r === X ? n(t) : formatIsoDateFields(t) : i ? formatIsoDateFields(t) + formatCalendarId(r, 2 === o) : n(t);
}

function formatDurationFragments(e) {
  const n = [];
  for (const t in e) {
    const o = e[t];
    o && n.push(o, t);
  }
  return n.join("");
}

function formatIsoDateTimeFields(e, n) {
  return formatIsoDateFields(e) + "T" + formatIsoTimeFields(e, n);
}

function formatIsoDateFields(e) {
  return formatIsoYearMonthFields(e) + "-" + xr(e.isoDay);
}

function formatIsoYearMonthFields(e) {
  const {isoYear: n} = e;
  return (n < 0 || n > 9999 ? getSignStr(n) + padNumber(6, Math.abs(n)) : padNumber(4, n)) + "-" + xr(e.isoMonth);
}

function formatIsoMonthDayFields(e) {
  return xr(e.isoMonth) + "-" + xr(e.isoDay);
}

function formatIsoTimeFields(e, n) {
  const t = [ xr(e.isoHour), xr(e.isoMinute) ];
  return -1 !== n && t.push(xr(e.isoSecond) + ((e, n, t, o) => formatSubsecNano(e * be + n * Vr + t, o))(e.isoMillisecond, e.isoMicrosecond, e.isoNanosecond, n)), 
  t.join(":");
}

function Fe(e, n = 0) {
  if (1 === n) {
    return "";
  }
  const [t, o] = divModFloor(Math.abs(e), Kr), [r, i] = divModFloor(o, Jr), [a, s] = divModFloor(i, _r);
  return getSignStr(e) + xr(t) + ":" + xr(r) + (a || s ? ":" + xr(a) + formatSubsecNano(s) : "");
}

function formatCalendar(e, n) {
  if (1 !== n) {
    const t = I(e);
    if (n > 1 || 0 === n && t !== X) {
      return formatCalendarId(t, 2 === n);
    }
  }
  return "";
}

function formatCalendarId(e, n) {
  return "[" + (n ? "!" : "") + "u-ca=" + e + "]";
}

function formatSubsecNano(e, n) {
  let t = padNumber(9, e);
  return t = void 0 === n ? t.replace(Na, "") : t.slice(0, n), t ? "." + t : "";
}

function getSignStr(e) {
  return e < 0 ? "-" : "+";
}

function formatDurationNumber(e, n) {
  return e || n ? e.toLocaleString("fullwide", {
    useGrouping: 0
  }) : "";
}

function _zonedEpochSlotsToIso(e, n) {
  const {epochNanoseconds: t} = e, o = (n.getOffsetNanosecondsFor ? n : n(e.timeZone)).getOffsetNanosecondsFor(t), r = Ie(t, o);
  return {
    calendar: e.calendar,
    ...r,
    offsetNanoseconds: o
  };
}

function mn(e, n) {
  const t = fn(n, e);
  return {
    calendar: n.calendar,
    ...Vn(Yi, t),
    offset: Fe(t.offsetNanoseconds),
    timeZone: n.timeZone
  };
}

function getMatchingInstantFor(e, n, t, o = 0, r = 0, i, a) {
  if (void 0 !== t && 1 === o && (1 === o || a)) {
    return isoToEpochNanoWithOffset(n, t);
  }
  const s = e.getPossibleInstantsFor(n);
  if (void 0 !== t && 3 !== o) {
    const e = ((e, n, t, o) => {
      const r = isoToEpochNano(n);
      o && (t = roundToMinute(t));
      for (const n of e) {
        let e = oe(re(n, r));
        if (o && (e = roundToMinute(e)), e === t) {
          return n;
        }
      }
    })(s, n, t, i);
    if (void 0 !== e) {
      return e;
    }
    if (0 === o) {
      throw new RangeError(kr);
    }
  }
  return a ? isoToEpochNano(n) : we(e, n, r, s);
}

function we(e, n, t = 0, o = e.getPossibleInstantsFor(n)) {
  if (1 === o.length) {
    return o[0];
  }
  if (1 === t) {
    throw new RangeError(Yr);
  }
  if (o.length) {
    return o[3 === t ? 1 : 0];
  }
  const r = isoToEpochNano(n), i = ((e, n) => {
    const t = e.getOffsetNanosecondsFor(moveBigNano(n, -Qr));
    return ne(e.getOffsetNanosecondsFor(moveBigNano(n, Qr)) - t);
  })(e, r), a = i * (2 === t ? -1 : 1);
  return (o = e.getPossibleInstantsFor(Ie(r, a)))[2 === t ? 0 : o.length - 1];
}

function ae(e) {
  if (Math.abs(e) >= Qr) {
    throw new RangeError(wr);
  }
  return e;
}

function ne(e) {
  if (e > Qr) {
    throw new RangeError(Br);
  }
  return e;
}

function se(e, n, t) {
  return _(checkEpochNanoInBounds(addBigNanos(n.epochNanoseconds, (e => {
    if (durationHasDateParts(e)) {
      throw new RangeError(qr);
    }
    return durationFieldsToBigNano(e, 5);
  })(e ? negateDurationFields(t) : t))));
}

function hn(e, n, t, o, r, i = Object.create(null)) {
  const a = n(o.timeZone), s = e(o.calendar);
  return {
    ...o,
    ...moveZonedEpochs(a, s, o, t ? negateDurationFields(r) : r, i)
  };
}

function ct(e, n, t, o, r = Object.create(null)) {
  const {calendar: i} = t;
  return ee(moveDateTime(e(i), t, n ? negateDurationFields(o) : o, r), i);
}

function bt(e, n, t, o, r) {
  const {calendar: i} = t;
  return v(moveDate(e(i), t, n ? negateDurationFields(o) : o, r), i);
}

function Qe(e, n, t, o, r = Object.create(null)) {
  const i = t.calendar, a = e(i);
  let s = moveToDayOfMonthUnsafe(a, t);
  n && (o = xt(o)), o.sign < 0 && (s = a.dateAdd(s, {
    ...Si,
    months: 1
  }), s = moveByDays(s, -1));
  const c = a.dateAdd(s, o, r);
  return createPlainYearMonthSlots(moveToDayOfMonthUnsafe(a, c), i);
}

function Ye(e, n, t) {
  return Ge(moveTime(n, e ? negateDurationFields(t) : t)[0]);
}

function moveZonedEpochs(e, n, t, o, r) {
  const i = durationFieldsToBigNano(o, 5);
  let a = t.epochNanoseconds;
  if (durationHasDateParts(o)) {
    const s = fn(t, e);
    a = addBigNanos(we(e, {
      ...moveDate(n, s, {
        ...o,
        ...Fi
      }, r),
      ...Vn(j, s)
    }), i);
  } else {
    a = addBigNanos(a, i), H(r);
  }
  return {
    epochNanoseconds: checkEpochNanoInBounds(a)
  };
}

function moveDateTime(e, n, t, o) {
  const [r, i] = moveTime(n, t);
  return checkIsoDateTimeInBounds({
    ...moveDate(e, n, {
      ...t,
      ...Fi,
      days: t.days + i
    }, o),
    ...r
  });
}

function moveDate(e, n, t, o) {
  if (t.years || t.months || t.weeks) {
    return e.dateAdd(n, t, o);
  }
  H(o);
  const r = t.days + durationFieldsToBigNano(t, 5)[0];
  return r ? checkIsoDateInBounds(moveByDays(n, r)) : n;
}

function moveToDayOfMonthUnsafe(e, n, t = 1) {
  return moveByDays(n, t - e.day(n));
}

function moveTime(e, n) {
  const [t, o] = durationFieldsToBigNano(n, 5), [r, i] = nanoToIsoTimeAndDay(isoTimeFieldsToNano(e) + o);
  return [ r, t + i ];
}

function moveByDays(e, n) {
  return n ? {
    ...e,
    ...epochMilliToIso(isoToEpochMilli(e) + n * Gr)
  } : e;
}

function createMarkerSystem(e, n, t) {
  const o = e(t.calendar);
  return isZonedEpochSlots(t) ? [ t, o, n(t.timeZone) ] : [ {
    ...t,
    ...Dt
  }, o ];
}

function createMarkerToEpochNano(e) {
  return e ? extractEpochNano : isoToEpochNano;
}

function createMoveMarker(e) {
  return e ? E(moveZonedEpochs, e) : moveDateTime;
}

function createDiffMarkers(e) {
  return e ? E(diffZonedEpochsExact, e) : diffDateTimesExact;
}

function isZonedEpochSlots(e) {
  return e && e.epochNanoseconds;
}

function isUniformUnit(e, n) {
  return e <= 6 - (isZonedEpochSlots(n) ? 1 : 0);
}

function Wt(e, n, t, o, r, i, a) {
  const s = e(normalizeOptions(a).relativeTo), c = Math.max(getMaxDurationUnit(r), getMaxDurationUnit(i));
  if (isUniformUnit(c, s)) {
    return Vt(checkDurationUnits(((e, n, t, o) => {
      const r = addBigNanos(durationFieldsToBigNano(e), durationFieldsToBigNano(n), o ? -1 : 1);
      if (!Number.isFinite(r[0])) {
        throw new RangeError(Cr);
      }
      return {
        ...Si,
        ...nanoToDurationDayTimeFields(r, t)
      };
    })(r, i, c, o)));
  }
  if (!s) {
    throw new RangeError(zr);
  }
  o && (i = negateDurationFields(i));
  const [u, l, f] = createMarkerSystem(n, t, s), d = createMoveMarker(f), m = createDiffMarkers(f), p = d(l, u, r);
  return Vt(m(l, u, d(l, p, i), c));
}

function Gt(e, n, t, o, r) {
  const i = getMaxDurationUnit(o), [a, s, c, u, l] = ((e, n, t) => {
    e = normalizeOptionsOrString(e, Hi);
    let o = sa(e);
    const r = t(e[Ki]);
    let i = parseRoundingIncInteger(e);
    const a = ha(e, 7);
    let s = aa(e);
    if (void 0 === o && void 0 === s) {
      throw new RangeError(Ur);
    }
    return null == s && (s = 0), null == o && (o = Math.max(s, n)), checkLargestSmallestUnit(o, s), 
    i = refineRoundingInc(i, s, 1), [ o, s, i, a, r ];
  })(r, i, e), f = Math.max(i, a);
  if (!isZonedEpochSlots(l) && f <= 6) {
    return Vt(checkDurationUnits(((e, n, t, o, r) => {
      const i = roundBigNano(durationFieldsToBigNano(e), t, o, r);
      return {
        ...Si,
        ...nanoToDurationDayTimeFields(i, n)
      };
    })(o, a, s, c, u)));
  }
  if (!l) {
    throw new RangeError(zr);
  }
  const [d, m, p] = createMarkerSystem(n, t, l), h = createMarkerToEpochNano(p), g = createMoveMarker(p), T = createDiffMarkers(p), D = g(m, d, o);
  let I = T(m, d, D, a);
  const M = o.sign, N = computeDurationSign(I);
  if (M && N && M !== N) {
    throw new RangeError(vr);
  }
  return N && (I = roundRelativeDuration(I, h(D), a, s, c, u, m, d, h, g)), Vt(I);
}

function Rt(e) {
  return -1 === e.sign ? xt(e) : e;
}

function xt(e) {
  return Vt(negateDurationFields(e));
}

function negateDurationFields(e) {
  const n = {};
  for (const t of F) {
    n[t] = -1 * e[t] || 0;
  }
  return n;
}

function Jt(e) {
  return !e.sign;
}

function computeDurationSign(e, n = F) {
  let t = 0;
  for (const o of n) {
    const n = Math.sign(e[o]);
    if (n) {
      if (t && t !== n) {
        throw new RangeError(Rr);
      }
      t = n;
    }
  }
  return t;
}

function checkDurationUnits(e) {
  for (const n of vi) {
    clampEntity(n, e[n], -ya, ya, 1);
  }
  return checkDurationTimeUnit(oe(durationFieldsToBigNano(e), _r)), e;
}

function checkDurationTimeUnit(e) {
  if (!Number.isSafeInteger(e)) {
    throw new RangeError(Zr);
  }
}

function durationFieldsToBigNano(e, n = 6) {
  return givenFieldsToBigNano(e, n, F);
}

function nanoToDurationDayTimeFields(e, n = 6) {
  const [t, o] = e, r = nanoToGivenFields(o, n, F);
  if (r[F[n]] += t * (Qr / Xr[n]), !Number.isFinite(r[F[n]])) {
    throw new RangeError(Cr);
  }
  return r;
}

function nanoToDurationTimeFields(e, n = 5) {
  return nanoToGivenFields(e, n, F);
}

function durationHasDateParts(e) {
  return Boolean(computeDurationSign(e, Pi));
}

function getMaxDurationUnit(e) {
  let n = 9;
  for (;n > 0 && !e[F[n]]; n--) {}
  return n;
}

function createSplitTuple(e, n) {
  return [ e, n ];
}

function computePeriod(e) {
  const n = Math.floor(e / Da) * Da;
  return [ n, n + Da ];
}

function pe(e) {
  const n = parseDateTimeLike(e = toStringViaPrimitive(e));
  if (!n) {
    throw new RangeError(failedParse(e));
  }
  let t;
  if (n.m) {
    t = 0;
  } else {
    if (!n.offset) {
      throw new RangeError(failedParse(e));
    }
    t = parseOffsetNano(n.offset);
  }
  return n.timeZone && parseOffsetNanoMaybe(n.timeZone, 1), _(isoToEpochNanoWithOffset(checkIsoDateTimeFields(n), t));
}

function Xt(e) {
  const n = parseDateTimeLike(m(e));
  if (!n) {
    throw new RangeError(failedParse(e));
  }
  if (n.timeZone) {
    return finalizeZonedDateTime(n, n.offset ? parseOffsetNano(n.offset) : void 0);
  }
  if (n.m) {
    throw new RangeError(failedParse(e));
  }
  return finalizeDate(n);
}

function Mn(e, n) {
  const t = parseDateTimeLike(m(e));
  if (!t || !t.timeZone) {
    throw new RangeError(failedParse(e));
  }
  const {offset: o} = t, r = o ? parseOffsetNano(o) : void 0, [, i, a] = wn(n);
  return finalizeZonedDateTime(t, r, i, a);
}

function parseOffsetNano(e) {
  const n = parseOffsetNanoMaybe(e);
  if (void 0 === n) {
    throw new RangeError(failedParse(e));
  }
  return n;
}

function Ct(e) {
  const n = parseDateTimeLike(m(e));
  if (!n || n.m) {
    throw new RangeError(failedParse(e));
  }
  return ee(finalizeDateTime(n));
}

function At(e) {
  const n = parseDateTimeLike(m(e));
  if (!n || n.m) {
    throw new RangeError(failedParse(e));
  }
  return v(n.p ? finalizeDateTime(n) : finalizeDate(n));
}

function ot(e, n) {
  const t = parseYearMonthOnly(m(n));
  if (t) {
    return requireIsoCalendar(t), createPlainYearMonthSlots(checkIsoYearMonthInBounds(checkIsoDateFields(t)));
  }
  const o = At(n);
  return createPlainYearMonthSlots(moveToDayOfMonthUnsafe(e(o.calendar), o));
}

function requireIsoCalendar(e) {
  if (e.calendar !== X) {
    throw new RangeError(invalidSubstring(e.calendar));
  }
}

function Q(e, n) {
  const t = parseMonthDayOnly(m(n));
  if (t) {
    return requireIsoCalendar(t), createPlainMonthDaySlots(checkIsoDateFields(t));
  }
  const o = At(n), {calendar: r} = o, i = e(r), [a, s, c] = i.h(o), [u, l] = i.I(a, s), [f, d] = i.N(u, l, c);
  return createPlainMonthDaySlots(checkIsoDateInBounds(i.P(f, d, c)), r);
}

function ze(e) {
  let n, t = (e => {
    const n = Ca.exec(e);
    return n ? (organizeAnnotationParts(n[10]), organizeTimeParts(n)) : void 0;
  })(m(e));
  if (!t) {
    if (t = parseDateTimeLike(e), !t) {
      throw new RangeError(failedParse(e));
    }
    if (!t.p) {
      throw new RangeError(failedParse(e));
    }
    if (t.m) {
      throw new RangeError(invalidSubstring("Z"));
    }
    requireIsoCalendar(t);
  }
  if ((n = parseYearMonthOnly(e)) && isIsoDateFieldsValid(n)) {
    throw new RangeError(failedParse(e));
  }
  if ((n = parseMonthDayOnly(e)) && isIsoDateFieldsValid(n)) {
    throw new RangeError(failedParse(e));
  }
  return Ge(constrainIsoTimeFields(t, 1));
}

function Kt(e) {
  const n = (e => {
    const n = za.exec(e);
    return n ? (e => {
      function parseUnit(e, r, i) {
        let a = 0, s = 0;
        if (i && ([a, o] = divModFloor(o, Xr[i])), void 0 !== e) {
          if (t) {
            throw new RangeError(invalidSubstring(e));
          }
          s = (e => {
            const n = parseInt(e);
            if (!Number.isFinite(n)) {
              throw new RangeError(invalidSubstring(e));
            }
            return n;
          })(e), n = 1, r && (o = parseSubsecNano(r) * (Xr[i] / _r), t = 1);
        }
        return a + s;
      }
      let n = 0, t = 0, o = 0, r = {
        ...zipProps(F, [ parseUnit(e[2]), parseUnit(e[3]), parseUnit(e[4]), parseUnit(e[5]), parseUnit(e[6], e[7], 5), parseUnit(e[8], e[9], 4), parseUnit(e[10], e[11], 3) ]),
        ...nanoToGivenFields(o, 2, F)
      };
      if (!n) {
        throw new RangeError(noValidFields(F));
      }
      return parseSign(e[1]) < 0 && (r = negateDurationFields(r)), r;
    })(n) : void 0;
  })(m(e));
  if (!n) {
    throw new RangeError(failedParse(e));
  }
  return Vt(checkDurationUnits(n));
}

function sn(e) {
  const n = parseDateTimeLike(e) || parseYearMonthOnly(e) || parseMonthDayOnly(e);
  return n ? n.calendar : e;
}

function Ne(e) {
  const n = parseDateTimeLike(e);
  return n && (n.timeZone || n.m && Ta || n.offset) || e;
}

function finalizeZonedDateTime(e, n, t = 0, o = 0) {
  const r = ye(e.timeZone), i = ie(r);
  return Yn(getMatchingInstantFor(i, checkIsoDateTimeFields(e), n, t, o, !i.v, e.m), r, an(e.calendar));
}

function finalizeDateTime(e) {
  return resolveSlotsCalendar(checkIsoDateTimeInBounds(checkIsoDateTimeFields(e)));
}

function finalizeDate(e) {
  return resolveSlotsCalendar(checkIsoDateInBounds(checkIsoDateFields(e)));
}

function resolveSlotsCalendar(e) {
  return {
    ...e,
    calendar: an(e.calendar)
  };
}

function parseDateTimeLike(e) {
  const n = Ya.exec(e);
  return n ? (e => {
    const n = e[10], t = "Z" === (n || "").toUpperCase();
    return {
      isoYear: organizeIsoYearParts(e),
      isoMonth: parseInt(e[4]),
      isoDay: parseInt(e[5]),
      ...organizeTimeParts(e.slice(5)),
      ...organizeAnnotationParts(e[16]),
      p: Boolean(e[6]),
      m: t,
      offset: t ? void 0 : n
    };
  })(n) : void 0;
}

function parseYearMonthOnly(e) {
  const n = Ba.exec(e);
  return n ? (e => ({
    isoYear: organizeIsoYearParts(e),
    isoMonth: parseInt(e[4]),
    isoDay: 1,
    ...organizeAnnotationParts(e[5])
  }))(n) : void 0;
}

function parseMonthDayOnly(e) {
  const n = ka.exec(e);
  return n ? (e => ({
    isoYear: ji,
    isoMonth: parseInt(e[1]),
    isoDay: parseInt(e[2]),
    ...organizeAnnotationParts(e[3])
  }))(n) : void 0;
}

function parseOffsetNanoMaybe(e, n) {
  const t = Za.exec(e);
  return t ? ((e, n) => {
    const t = e[4] || e[5];
    if (n && t) {
      throw new RangeError(invalidSubstring(t));
    }
    return ae((parseInt0(e[2]) * Kr + parseInt0(e[3]) * Jr + parseInt0(e[4]) * _r + parseSubsecNano(e[5] || "")) * parseSign(e[1]));
  })(t, n) : void 0;
}

function organizeIsoYearParts(e) {
  const n = parseSign(e[1]), t = parseInt(e[2] || e[3]);
  if (n < 0 && !t) {
    throw new RangeError(invalidSubstring(-0));
  }
  return n * t;
}

function organizeTimeParts(e) {
  const n = parseInt0(e[3]);
  return {
    ...nanoToIsoTimeAndDay(parseSubsecNano(e[4] || ""))[0],
    isoHour: parseInt0(e[1]),
    isoMinute: parseInt0(e[2]),
    isoSecond: 60 === n ? 59 : n
  };
}

function organizeAnnotationParts(e) {
  let n, t;
  const o = [];
  if (e.replace(Ra, ((e, r, i) => {
    const a = Boolean(r), [s, c] = i.split("=").reverse();
    if (c) {
      if ("u-ca" === c) {
        o.push(s), n || (n = a);
      } else if (a || /[A-Z]/.test(c)) {
        throw new RangeError(invalidSubstring(e));
      }
    } else {
      if (t) {
        throw new RangeError(invalidSubstring(e));
      }
      t = s;
    }
    return "";
  })), o.length > 1 && n) {
    throw new RangeError(invalidSubstring(e));
  }
  return {
    timeZone: t,
    calendar: o[0] || X
  };
}

function parseSubsecNano(e) {
  return parseInt(e.padEnd(9, "0"));
}

function createRegExp(e) {
  return new RegExp(`^${e}$`, "i");
}

function parseSign(e) {
  return e && "+" !== e ? -1 : 1;
}

function parseInt0(e) {
  return void 0 === e ? 0 : parseInt(e);
}

function Me(e) {
  return ye(m(e));
}

function ye(e) {
  const n = getTimeZoneEssence(e);
  return "number" == typeof n ? Fe(n) : n ? (e => {
    if (Ua.test(e)) {
      throw new RangeError(br);
    }
    return e.toLowerCase().split("/").map(((e, n) => (e.length <= 3 || /\d/.test(e)) && !/etc|yap/.test(e) ? e.toUpperCase() : e.replace(/baja|dumont|[a-z]+/g, ((e, t) => e.length <= 2 && !n || "in" === e || "chat" === e ? e.toUpperCase() : e.length > 2 || !t ? capitalize(e).replace(/island|noronha|murdo|rivadavia|urville/, capitalize) : e)))).join("/");
  })(e) : Ta;
}

function getTimeZoneAtomic(e) {
  const n = getTimeZoneEssence(e);
  return "number" == typeof n ? n : n ? n.resolvedOptions().timeZone : Ta;
}

function getTimeZoneEssence(e) {
  const n = parseOffsetNanoMaybe(e = e.toUpperCase(), 1);
  return void 0 !== n ? n : e !== Ta ? qa(e) : void 0;
}

function Ze(e, n) {
  return te(e.epochNanoseconds, n.epochNanoseconds);
}

function yn(e, n) {
  return te(e.epochNanoseconds, n.epochNanoseconds);
}

function $t(e, n, t, o, r, i) {
  const a = e(normalizeOptions(i).relativeTo), s = Math.max(getMaxDurationUnit(o), getMaxDurationUnit(r));
  if (allPropsEqual(F, o, r)) {
    return 0;
  }
  if (isUniformUnit(s, a)) {
    return te(durationFieldsToBigNano(o), durationFieldsToBigNano(r));
  }
  if (!a) {
    throw new RangeError(zr);
  }
  const [c, u, l] = createMarkerSystem(n, t, a), f = createMarkerToEpochNano(l), d = createMoveMarker(l);
  return te(f(d(u, c, o)), f(d(u, c, r)));
}

function gt(e, n) {
  return rt(e, n) || He(e, n);
}

function rt(e, n) {
  return compareNumbers(isoToEpochMilli(e), isoToEpochMilli(n));
}

function He(e, n) {
  return compareNumbers(isoTimeFieldsToNano(e), isoTimeFieldsToNano(n));
}

function ue(e, n) {
  return !Ze(e, n);
}

function gn(e, n) {
  return !yn(e, n) && !!je(e.timeZone, n.timeZone) && isIdLikeEqual(e.calendar, n.calendar);
}

function ft(e, n) {
  return !gt(e, n) && isIdLikeEqual(e.calendar, n.calendar);
}

function It(e, n) {
  return !rt(e, n) && isIdLikeEqual(e.calendar, n.calendar);
}

function $e(e, n) {
  return !rt(e, n) && isIdLikeEqual(e.calendar, n.calendar);
}

function x(e, n) {
  return !rt(e, n) && isIdLikeEqual(e.calendar, n.calendar);
}

function Ve(e, n) {
  return !He(e, n);
}

function je(e, n) {
  if (e === n) {
    return 1;
  }
  const t = I(e), o = I(n);
  if (t === o) {
    return 1;
  }
  try {
    return getTimeZoneAtomic(t) === getTimeZoneAtomic(o);
  } catch (e) {}
}

function le(e, n, t, o) {
  const r = refineDiffOptions(e, U(o), 3, 5), i = diffEpochNanos(n.epochNanoseconds, t.epochNanoseconds, ...r);
  return Vt(e ? negateDurationFields(i) : i);
}

function Dn(e, n, t, o, r, i) {
  const a = getCommonCalendarSlot(o.calendar, r.calendar), s = U(i), [c, u, l, f] = refineDiffOptions(t, s, 5), d = o.epochNanoseconds, m = r.epochNanoseconds, p = te(m, d);
  let h;
  if (p) {
    if (c < 6) {
      h = diffEpochNanos(d, m, c, u, l, f);
    } else {
      const t = n(((e, n) => {
        if (!je(e, n)) {
          throw new RangeError(Fr);
        }
        return e;
      })(o.timeZone, r.timeZone)), i = e(a);
      h = diffZonedEpochsBig(i, t, o, r, p, c, s), h = roundRelativeDuration(h, m, c, u, l, f, i, o, extractEpochNano, E(moveZonedEpochs, t));
    }
  } else {
    h = Si;
  }
  return Vt(t ? negateDurationFields(h) : h);
}

function ut(e, n, t, o, r) {
  const i = getCommonCalendarSlot(t.calendar, o.calendar), a = U(r), [s, c, u, l] = refineDiffOptions(n, a, 6), f = isoToEpochNano(t), d = isoToEpochNano(o), m = te(d, f);
  let p;
  if (m) {
    if (s <= 6) {
      p = diffEpochNanos(f, d, s, c, u, l);
    } else {
      const n = e(i);
      p = diffDateTimesBig(n, t, o, m, s, a), p = roundRelativeDuration(p, d, s, c, u, l, n, t, isoToEpochNano, moveDateTime);
    }
  } else {
    p = Si;
  }
  return Vt(n ? negateDurationFields(p) : p);
}

function Ft(e, n, t, o, r) {
  const i = getCommonCalendarSlot(t.calendar, o.calendar), a = U(r);
  return diffDateLike(n, (() => e(i)), t, o, ...refineDiffOptions(n, a, 6, 9, 6), a);
}

function Xe(e, n, t, o, r) {
  const i = getCommonCalendarSlot(t.calendar, o.calendar), a = U(r), s = refineDiffOptions(n, a, 9, 9, 8), c = e(i);
  return diffDateLike(n, (() => c), moveToDayOfMonthUnsafe(c, t), moveToDayOfMonthUnsafe(c, o), ...s, a);
}

function diffDateLike(e, n, t, o, r, i, a, s, c) {
  const u = isoToEpochNano(t), l = isoToEpochNano(o);
  let f;
  if (te(l, u)) {
    if (6 === r) {
      f = diffEpochNanos(u, l, r, i, a, s);
    } else {
      const e = n();
      f = e.dateUntil(t, o, r, c), 6 === i && 1 === a || (f = roundRelativeDuration(f, l, r, i, a, s, e, t, isoToEpochNano, moveDate));
    }
  } else {
    f = Si;
  }
  return Vt(e ? negateDurationFields(f) : f);
}

function Ae(e, n, t, o) {
  const r = U(o), [i, a, s, c] = refineDiffOptions(e, r, 5, 5), u = roundByInc(diffTimes(n, t), computeNanoInc(a, s), c), l = {
    ...Si,
    ...nanoToDurationTimeFields(u, i)
  };
  return Vt(e ? negateDurationFields(l) : l);
}

function diffZonedEpochsExact(e, n, t, o, r, i) {
  const a = te(o.epochNanoseconds, t.epochNanoseconds);
  return a ? r < 6 ? diffEpochNanosExact(t.epochNanoseconds, o.epochNanoseconds, r) : diffZonedEpochsBig(n, e, t, o, a, r, i) : Si;
}

function diffDateTimesExact(e, n, t, o, r) {
  const i = isoToEpochNano(n), a = isoToEpochNano(t), s = te(a, i);
  return s ? o <= 6 ? diffEpochNanosExact(i, a, o) : diffDateTimesBig(e, n, t, s, o, r) : Si;
}

function diffZonedEpochsBig(e, n, t, o, r, i, a) {
  const [s, c, u] = ((e, n, t, o) => {
    function updateMid() {
      return l = {
        ...moveByDays(a, c++ * -o),
        ...i
      }, f = we(e, l), te(s, f) === -o;
    }
    const r = fn(n, e), i = Vn(j, r), a = fn(t, e), s = t.epochNanoseconds;
    let c = 0;
    const u = diffTimes(r, a);
    let l, f;
    if (Math.sign(u) === -o && c++, updateMid() && (-1 === o || updateMid())) {
      throw new RangeError(vr);
    }
    const d = oe(re(f, s));
    return [ r, l, d ];
  })(n, t, o, r);
  var l, f;
  return {
    ...6 === i ? (l = s, f = c, {
      ...Si,
      days: diffDays(l, f)
    }) : e.dateUntil(s, c, i, a),
    ...nanoToDurationTimeFields(u)
  };
}

function diffDateTimesBig(e, n, t, o, r, i) {
  const [a, s, c] = ((e, n, t) => {
    let o = n, r = diffTimes(e, n);
    return Math.sign(r) === -t && (o = moveByDays(n, -t), r += Qr * t), [ e, o, r ];
  })(n, t, o);
  return {
    ...e.dateUntil(a, s, r, i),
    ...nanoToDurationTimeFields(c)
  };
}

function diffEpochNanos(e, n, t, o, r, i) {
  return {
    ...Si,
    ...nanoToDurationDayTimeFields(roundBigNano(re(e, n), o, r, i), t)
  };
}

function diffEpochNanosExact(e, n, t) {
  return {
    ...Si,
    ...nanoToDurationDayTimeFields(re(e, n), t)
  };
}

function diffDays(e, n) {
  return diffEpochMilliByDay(isoToEpochMilli(e), isoToEpochMilli(n));
}

function diffEpochMilliByDay(e, n) {
  return Math.trunc((n - e) / Gr);
}

function diffTimes(e, n) {
  return isoTimeFieldsToNano(n) - isoTimeFieldsToNano(e);
}

function getCommonCalendarSlot(e, n) {
  if (!isIdLikeEqual(e, n)) {
    throw new RangeError(Er);
  }
  return e;
}

function createIntlCalendar(e) {
  function epochMilliToIntlFields(e) {
    return ((e, n) => ({
      ...parseIntlYear(e, n),
      F: e.month,
      day: parseInt(e.day)
    }))(hashIntlFormatParts(n, e), t);
  }
  const n = La(e), t = computeCalendarIdBase(e);
  return {
    id: e,
    O: createIntlFieldCache(epochMilliToIntlFields),
    B: createIntlYearDataCache(epochMilliToIntlFields)
  };
}

function createIntlFieldCache(e) {
  return Jn((n => {
    const t = isoToEpochMilli(n);
    return e(t);
  }), WeakMap);
}

function createIntlYearDataCache(e) {
  const n = e(0).year - Wi;
  return Jn((t => {
    let o, r = isoArgsToEpochMilli(t - n);
    const i = [], a = [];
    do {
      r += 400 * Gr;
    } while ((o = e(r)).year <= t);
    do {
      r += (1 - o.day) * Gr, o.year === t && (i.push(r), a.push(o.F)), r -= Gr;
    } while ((o = e(r)).year >= t);
    return {
      k: i.reverse(),
      C: Wr(a.reverse())
    };
  }));
}

function parseIntlYear(e, n) {
  let t, o, r = parseIntlPartsYear(e);
  if (e.era) {
    const i = Di[n];
    void 0 !== i && (t = "islamic" === n ? "ah" : e.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g, ""), 
    "bc" === t || "b" === t ? t = "bce" : "ad" !== t && "a" !== t || (t = "ce"), o = r, 
    r = eraYearToYear(o, i[t] || 0));
  }
  return {
    era: t,
    eraYear: o,
    year: r
  };
}

function parseIntlPartsYear(e) {
  return parseInt(e.relatedYear || e.year);
}

function computeIntlDateParts(e) {
  const {year: n, F: t, day: o} = this.O(e), {C: r} = this.B(n);
  return [ n, r[t] + 1, o ];
}

function computeIntlEpochMilli(e, n = 1, t = 1) {
  return this.B(e).k[n - 1] + (t - 1) * Gr;
}

function computeIntlLeapMonth(e) {
  const n = queryMonthStrings(this, e), t = queryMonthStrings(this, e - 1), o = n.length;
  if (o > t.length) {
    const e = getCalendarLeapMonthMeta(this);
    if (e < 0) {
      return -e;
    }
    for (let e = 0; e < o; e++) {
      if (n[e] !== t[e]) {
        return e + 1;
      }
    }
  }
}

function computeIntlDaysInYear(e) {
  return diffEpochMilliByDay(computeIntlEpochMilli.call(this, e), computeIntlEpochMilli.call(this, e + 1));
}

function computeIntlDaysInMonth(e, n) {
  const {k: t} = this.B(e);
  let o = n + 1, r = t;
  return o > t.length && (o = 1, r = this.B(e + 1).k), diffEpochMilliByDay(t[n - 1], r[o - 1]);
}

function computeIntlMonthsInYear(e) {
  return this.B(e).k.length;
}

function queryMonthStrings(e, n) {
  return Object.keys(e.B(n).C);
}

function rn(e) {
  return an(m(e));
}

function an(e) {
  if ((e = e.toLowerCase()) !== X && e !== gi && computeCalendarIdBase(e) !== computeCalendarIdBase(La(e).resolvedOptions().calendar)) {
    throw new RangeError(invalidCalendar(e));
  }
  return e;
}

function computeCalendarIdBase(e) {
  return "islamicc" === e && (e = "islamic"), e.split("-")[0];
}

function computeNativeWeekOfYear(e) {
  return this.R(e)[0];
}

function computeNativeYearOfWeek(e) {
  return this.R(e)[1];
}

function computeNativeDayOfYear(e) {
  const [n] = this.h(e);
  return diffEpochMilliByDay(this.q(n), isoToEpochMilli(e)) + 1;
}

function parseMonthCode(e) {
  const n = Wa.exec(e);
  if (!n) {
    throw new RangeError(invalidMonthCode(e));
  }
  return [ parseInt(n[1]), Boolean(n[2]) ];
}

function monthCodeNumberToMonth(e, n, t) {
  return e + (n || t && e >= t ? 1 : 0);
}

function monthToMonthCodeNumber(e, n) {
  return e - (n && e >= n ? 1 : 0);
}

function eraYearToYear(e, n) {
  return (n + e) * (Math.sign(n) || 1) || 0;
}

function getCalendarEraOrigins(e) {
  return Di[getCalendarIdBase(e)];
}

function getCalendarLeapMonthMeta(e) {
  return Ii[getCalendarIdBase(e)];
}

function getCalendarIdBase(e) {
  return computeCalendarIdBase(e.id || X);
}

function Qt(e, n, t, o) {
  const r = refineCalendarFields(t, o, en, [], ri);
  if (void 0 !== r.timeZone) {
    const o = t.dateFromFields(r), i = refineTimeBag(r), a = e(r.timeZone);
    return {
      epochNanoseconds: getMatchingInstantFor(n(a), {
        ...o,
        ...i
      }, void 0 !== r.offset ? parseOffsetNano(r.offset) : void 0),
      timeZone: a
    };
  }
  return {
    ...t.dateFromFields(r),
    ...Dt
  };
}

function jn(e, n, t, o, r, i) {
  const a = refineCalendarFields(t, r, en, ti, ri), s = e(a.timeZone), [c, u, l] = wn(i), f = t.dateFromFields(a, overrideOverflowOptions(i, c)), d = refineTimeBag(a, c);
  return Yn(getMatchingInstantFor(n(s), {
    ...f,
    ...d
  }, void 0 !== a.offset ? parseOffsetNano(a.offset) : void 0, u, l), s, o);
}

function Pt(e, n, t) {
  const o = refineCalendarFields(e, n, en, [], w), r = H(t);
  return ee(checkIsoDateTimeInBounds({
    ...e.dateFromFields(o, overrideOverflowOptions(t, r)),
    ...refineTimeBag(o, r)
  }));
}

function Yt(e, n, t, o = []) {
  const r = refineCalendarFields(e, n, en, o);
  return e.dateFromFields(r, t);
}

function nt(e, n, t, o) {
  const r = refineCalendarFields(e, n, fi, o);
  return e.yearMonthFromFields(r, t);
}

function K(e, n, t, o, r = []) {
  const i = refineCalendarFields(e, t, en, r);
  return n && void 0 !== i.month && void 0 === i.monthCode && void 0 === i.year && (i.year = ji), 
  e.monthDayFromFields(i, o);
}

function Ue(e, n) {
  const t = H(n);
  return Ge(refineTimeBag(refineFields(e, ei, [], 1), t));
}

function Ht(e) {
  const n = refineFields(e, Ni);
  return Vt(checkDurationUnits({
    ...Si,
    ...n
  }));
}

function refineCalendarFields(e, n, t, o = [], r = []) {
  return refineFields(n, [ ...e.fields(t), ...r ].sort(), o);
}

function refineFields(e, n, t, o = !t) {
  const r = {};
  let i, a = 0;
  for (const o of n) {
    if (o === i) {
      throw new RangeError(duplicateFields(o));
    }
    if ("constructor" === o || "__proto__" === o) {
      throw new RangeError(tn(o));
    }
    let n = e[o];
    if (void 0 !== n) {
      a = 1, Ga[o] && (n = Ga[o](n, o)), r[o] = n;
    } else if (t) {
      if (t.includes(o)) {
        throw new TypeError(missingField(o));
      }
      r[o] = hi[o];
    }
    i = o;
  }
  if (o && !a) {
    throw new TypeError(noValidFields(n));
  }
  return r;
}

function refineTimeBag(e, n) {
  return constrainIsoTimeFields(Ha({
    ...hi,
    ...e
  }), n);
}

function Sn(e, n, t, o, r, i) {
  const a = U(i), {calendar: s, timeZone: c} = t;
  return Yn(((e, n, t, o, r) => {
    const i = mergeCalendarFields(e, t, o, en, oi, ni), [a, s, c] = wn(r, 2);
    return getMatchingInstantFor(n, {
      ...e.dateFromFields(i, overrideOverflowOptions(r, a)),
      ...refineTimeBag(i, a)
    }, parseOffsetNano(i.offset), s, c);
  })(e(s), n(c), o, r, a), c, s);
}

function at(e, n, t, o, r) {
  const i = U(r);
  return ee(((e, n, t, o) => {
    const r = mergeCalendarFields(e, n, t, en, w), i = H(o);
    return checkIsoDateTimeInBounds({
      ...e.dateFromFields(r, overrideOverflowOptions(o, i)),
      ...refineTimeBag(r, i)
    });
  })(e(n.calendar), t, o, i));
}

function Zt(e, n, t, o, r) {
  const i = U(r);
  return ((e, n, t, o) => {
    const r = mergeCalendarFields(e, n, t, en);
    return e.dateFromFields(r, o);
  })(e(n.calendar), t, o, i);
}

function Ke(e, n, t, o, r) {
  const i = U(r);
  return createPlainYearMonthSlots(((e, n, t, o) => {
    const r = mergeCalendarFields(e, n, t, fi);
    return e.yearMonthFromFields(r, o);
  })(e(n.calendar), t, o, i));
}

function k(e, n, t, o, r) {
  const i = U(r);
  return ((e, n, t, o) => {
    const r = mergeCalendarFields(e, n, t, en);
    return e.monthDayFromFields(r, o);
  })(e(n.calendar), t, o, i);
}

function Be(e, n, t) {
  return Ge(((e, n, t) => {
    const o = H(t);
    return refineTimeBag({
      ...Vn(ei, e),
      ...refineFields(n, ei)
    }, o);
  })(e, n, t));
}

function kt(e, n) {
  return Vt((t = e, o = n, checkDurationUnits({
    ...t,
    ...refineFields(o, Ni)
  })));
  var t, o;
}

function mergeCalendarFields(e, n, t, o, r = [], i = []) {
  const a = [ ...e.fields(o), ...r ].sort();
  let s = refineFields(n, a, i);
  const c = refineFields(t, a);
  return s = e.mergeFields(s, c), refineFields(s, a, []);
}

function convertToPlainMonthDay(e, n) {
  const t = refineCalendarFields(e, n, pi);
  return e.monthDayFromFields(t);
}

function convertToPlainYearMonth(e, n, t) {
  const o = refineCalendarFields(e, n, di);
  return e.yearMonthFromFields(o, t);
}

function convertToIso(e, n, t, o, r) {
  n = Vn(t = e.fields(t), n), o = refineFields(o, r = e.fields(r), []);
  let i = e.mergeFields(n, o);
  return i = refineFields(i, [ ...t, ...r ].sort(), []), e.dateFromFields(i);
}

function refineYear(e, n) {
  let {era: t, eraYear: o, year: r} = n;
  const i = getCalendarEraOrigins(e);
  if (void 0 !== t || void 0 !== o) {
    if (void 0 === t || void 0 === o) {
      throw new TypeError(Dr);
    }
    if (!i) {
      throw new RangeError(gr);
    }
    const e = i[t];
    if (void 0 === e) {
      throw new RangeError(invalidEra(t));
    }
    const n = eraYearToYear(o, e);
    if (void 0 !== r && r !== n) {
      throw new RangeError(Ir);
    }
    r = n;
  } else if (void 0 === r) {
    throw new TypeError(missingYear(i));
  }
  return r;
}

function refineMonth(e, n, t, o) {
  let {month: r, monthCode: i} = n;
  if (void 0 !== i) {
    const n = ((e, n, t, o) => {
      const r = e.U(t), [i, a] = parseMonthCode(n);
      let s = monthCodeNumberToMonth(i, a, r);
      if (a) {
        const n = getCalendarLeapMonthMeta(e);
        if (void 0 === n) {
          throw new RangeError(Pr);
        }
        if (n > 0) {
          if (s > n) {
            throw new RangeError(Pr);
          }
          if (void 0 === r) {
            if (1 === o) {
              throw new RangeError(Pr);
            }
            s--;
          }
        } else {
          if (s !== -n) {
            throw new RangeError(Pr);
          }
          if (void 0 === r && 1 === o) {
            throw new RangeError(Pr);
          }
        }
      }
      return s;
    })(e, i, t, o);
    if (void 0 !== r && r !== n) {
      throw new RangeError(Mr);
    }
    r = n, o = 1;
  } else if (void 0 === r) {
    throw new TypeError(Nr);
  }
  return clampEntity("month", r, 1, e.L(t), o);
}

function refineDay(e, n, t, o, r) {
  return clampProp(n, "day", 1, e.j(o, t), r);
}

function spliceFields(e, n, t, o) {
  let r = 0;
  const i = [];
  for (const e of t) {
    void 0 !== n[e] ? r = 1 : i.push(e);
  }
  if (Object.assign(e, n), r) {
    for (const n of o || i) {
      delete e[n];
    }
  }
}

function Se(e) {
  return _(checkEpochNanoInBounds(bigIntToBigNano(toBigInt(e))));
}

function vn(e, n, t, o, r = X) {
  return Yn(checkEpochNanoInBounds(bigIntToBigNano(toBigInt(t))), n(o), e(r));
}

function pt(e, n, t, o, r = 0, i = 0, a = 0, s = 0, c = 0, u = 0, l = X) {
  return ee(checkIsoDateTimeInBounds(checkIsoDateTimeFields(T(toInteger, zipProps(wi, [ n, t, o, r, i, a, s, c, u ])))), e(l));
}

function Nt(e, n, t, o, r = X) {
  return v(checkIsoDateInBounds(checkIsoDateFields(T(toInteger, {
    isoYear: n,
    isoMonth: t,
    isoDay: o
  }))), e(r));
}

function tt(e, n, t, o = X, r = 1) {
  const i = toInteger(n), a = toInteger(t), s = e(o);
  return createPlainYearMonthSlots(checkIsoYearMonthInBounds(checkIsoDateFields({
    isoYear: i,
    isoMonth: a,
    isoDay: toInteger(r)
  })), s);
}

function G(e, n, t, o = X, r = ji) {
  const i = toInteger(n), a = toInteger(t), s = e(o);
  return createPlainMonthDaySlots(checkIsoDateInBounds(checkIsoDateFields({
    isoYear: toInteger(r),
    isoMonth: i,
    isoDay: a
  })), s);
}

function ke(e = 0, n = 0, t = 0, o = 0, r = 0, i = 0) {
  return Ge(constrainIsoTimeFields(T(toInteger, zipProps(j, [ e, n, t, o, r, i ])), 1));
}

function Lt(e = 0, n = 0, t = 0, o = 0, r = 0, i = 0, a = 0, s = 0, c = 0, u = 0) {
  return Vt(checkDurationUnits(T(toStrictInteger, zipProps(F, [ e, n, t, o, r, i, a, s, c, u ]))));
}

function fe(e, n, t = X) {
  return Yn(e.epochNanoseconds, n, t);
}

function Zn(e) {
  return _(e.epochNanoseconds);
}

function ht(e, n) {
  return ee(fn(n, e));
}

function Bt(e, n) {
  return v(fn(n, e));
}

function bn(e, n, t) {
  return convertToPlainYearMonth(e(n.calendar), t);
}

function Fn(e, n, t) {
  return convertToPlainMonthDay(e(n.calendar), t);
}

function Re(e, n) {
  return Ge(fn(n, e));
}

function mt(e, n, t, o) {
  const r = ((e, n, t, o) => {
    const r = ve(o);
    return we(e(n), t, r);
  })(e, t, n, o);
  return Yn(checkEpochNanoInBounds(r), t, n.calendar);
}

function St(e, n, t) {
  const o = e(n.calendar);
  return createPlainYearMonthSlots({
    ...n,
    ...convertToPlainYearMonth(o, t)
  });
}

function Ot(e, n, t) {
  return convertToPlainMonthDay(e(n.calendar), t);
}

function vt(e, n, t, o, r) {
  const i = e(r.timeZone), a = r.plainTime, s = void 0 !== a ? n(a) : Dt;
  return Yn(we(t(i), {
    ...o,
    ...s
  }), i, o.calendar);
}

function wt(e, n = Dt) {
  return ee(checkIsoDateTimeInBounds({
    ...e,
    ...n
  }));
}

function jt(e, n, t) {
  return convertToPlainYearMonth(e(n.calendar), t);
}

function Mt(e, n, t) {
  return convertToPlainMonthDay(e(n.calendar), t);
}

function _e(e, n, t, o) {
  return ((e, n, t) => convertToIso(e, n, di, de(t), li))(e(n.calendar), t, o);
}

function R(e, n, t, o) {
  return ((e, n, t) => convertToIso(e, n, pi, de(t), si))(e(n.calendar), t, o);
}

function Je(e, n, t, o, r) {
  const i = de(r), a = n(i.plainDate), s = e(i.timeZone);
  return Yn(we(t(s), {
    ...a,
    ...o
  }), s, a.calendar);
}

function Le(e, n) {
  return ee(checkIsoDateTimeInBounds({
    ...e,
    ...n
  }));
}

function De(e) {
  return _(checkEpochNanoInBounds(he(e, _r)));
}

function Pe(e) {
  return _(checkEpochNanoInBounds(he(e, be)));
}

function Ce(e) {
  return _(checkEpochNanoInBounds(bigIntToBigNano(toBigInt(e), Vr)));
}

function ge(e) {
  return _(checkEpochNanoInBounds(bigIntToBigNano(toBigInt(e))));
}

function pn(e, n, t = Dt) {
  const o = n.timeZone, r = e(o), i = {
    ...fn(n, r),
    ...t
  };
  return Yn(getMatchingInstantFor(r, i, i.offsetNanoseconds, 2), o, n.calendar);
}

function Tn(e, n, t) {
  const o = n.timeZone, r = e(o), i = {
    ...fn(n, r),
    ...t
  }, a = getPreferredCalendarSlot(n.calendar, t.calendar);
  return Yn(getMatchingInstantFor(r, i, i.offsetNanoseconds, 2), o, a);
}

function lt(e, n = Dt) {
  return ee({
    ...e,
    ...n
  });
}

function st(e, n) {
  return ee({
    ...e,
    ...n
  }, getPreferredCalendarSlot(e.calendar, n.calendar));
}

function it(e, n) {
  return {
    ...e,
    calendar: n
  };
}

function On(e, n) {
  return {
    ...e,
    timeZone: n
  };
}

function getPreferredCalendarSlot(e, n) {
  if (e === n) {
    return e;
  }
  const t = I(e), o = I(n);
  if (t === o || t === X) {
    return n;
  }
  if (o === X) {
    return e;
  }
  throw new RangeError(Er);
}

function createNativeOpsCreator(e, n) {
  return t => t === X ? e : t === gi || t === Ti ? Object.assign(Object.create(e), {
    id: t
  }) : Object.assign(Object.create(n), Aa(t));
}

function createOptionsTransformer(e, n, t) {
  const o = new Set(t);
  return r => (((e, n) => {
    for (const t of n) {
      if (t in e) {
        return 1;
      }
    }
    return 0;
  })(r = V(o, r), e) || Object.assign(r, n), t && (r.timeZone = Ta, [ "full", "long" ].includes(r.timeStyle) && (r.timeStyle = "medium")), 
  r);
}

function e(e, n = qn) {
  const [t, , , o] = e;
  return (r, i = Ns, ...a) => {
    const s = n(o && o(...a), r, i, t), c = s.resolvedOptions();
    return [ s, ...toEpochMillis(e, c, a) ];
  };
}

function qn(e, n, t, o) {
  if (t = o(t), e) {
    if (void 0 !== t.timeZone) {
      throw new TypeError(Lr);
    }
    t.timeZone = e;
  }
  return new En(n, t);
}

function toEpochMillis(e, n, t) {
  const [, o, r] = e;
  return t.map((e => (e.calendar && ((e, n, t) => {
    if ((t || e !== X) && e !== n) {
      throw new RangeError(Er);
    }
  })(I(e.calendar), n.calendar, r), o(e, n))));
}

function An(e) {
  const n = Bn();
  return Ie(n, e.getOffsetNanosecondsFor(n));
}

function Bn() {
  return he(Date.now(), be);
}

function Nn() {
  return ys || (ys = (new En).resolvedOptions().timeZone);
}

const expectedInteger = (e, n) => `Non-integer ${e}: ${n}`, expectedPositive = (e, n) => `Non-positive ${e}: ${n}`, expectedFinite = (e, n) => `Non-finite ${e}: ${n}`, forbiddenBigIntToNumber = e => `Cannot convert bigint to ${e}`, invalidBigInt = e => `Invalid bigint: ${e}`, pr = "Cannot convert Symbol to string", hr = "Invalid object", numberOutOfRange = (e, n, t, o, r) => r ? numberOutOfRange(e, r[n], r[t], r[o]) : invalidEntity(e, n) + `; must be between ${t}-${o}`, invalidEntity = (e, n) => `Invalid ${e}: ${n}`, missingField = e => `Missing ${e}`, tn = e => `Invalid field ${e}`, duplicateFields = e => `Duplicate field ${e}`, noValidFields = e => "No valid fields: " + e.join(), Z = "Invalid bag", invalidChoice = (e, n, t) => invalidEntity(e, n) + "; must be " + Object.keys(t).join(), A = "Cannot use valueOf", P = "Invalid calling context", gr = "Forbidden era/eraYear", Dr = "Mismatching era/eraYear", Ir = "Mismatching year/eraYear", invalidEra = e => `Invalid era: ${e}`, missingYear = e => "Missing year" + (e ? "/era/eraYear" : ""), invalidMonthCode = e => `Invalid monthCode: ${e}`, Mr = "Mismatching month/monthCode", Nr = "Missing month/monthCode", yr = "Cannot guess year", Pr = "Invalid leap month", g = "Invalid protocol", vr = "Invalid protocol results", Er = "Mismatching Calendars", invalidCalendar = e => `Invalid Calendar: ${e}`, Fr = "Mismatching TimeZones", br = "Forbidden ICU TimeZone", wr = "Out-of-bounds offset", Br = "Out-of-bounds TimeZone gap", kr = "Invalid TimeZone offset", Yr = "Ambiguous offset", Cr = "Out-of-bounds date", Zr = "Out-of-bounds duration", Rr = "Cannot mix duration signs", zr = "Missing relativeTo", qr = "Cannot use large units", Ur = "Required smallestUnit or largestUnit", Ar = "smallestUnit > largestUnit", failedParse = e => `Cannot parse: ${e}`, invalidSubstring = e => `Invalid substring: ${e}`, Ln = e => `Cannot format ${e}`, kn = "Mismatching types for formatting", Lr = "Cannot specify TimeZone", Wr = /*@__PURE__*/ E(b, ((e, n) => n)), jr = /*@__PURE__*/ E(b, ((e, n, t) => t)), xr = /*@__PURE__*/ E(padNumber, 2), $r = {
  nanosecond: 0,
  microsecond: 1,
  millisecond: 2,
  second: 3,
  minute: 4,
  hour: 5,
  day: 6,
  week: 7,
  month: 8,
  year: 9
}, Et = /*@__PURE__*/ Object.keys($r), Gr = 864e5, Hr = 1e3, Vr = 1e3, be = 1e6, _r = 1e9, Jr = 6e10, Kr = 36e11, Qr = 864e11, Xr = [ 1, Vr, be, _r, Jr, Kr, Qr ], w = /*@__PURE__*/ Et.slice(0, 6), ei = /*@__PURE__*/ sortStrings(w), ni = [ "offset" ], ti = [ "timeZone" ], oi = /*@__PURE__*/ w.concat(ni), ri = /*@__PURE__*/ oi.concat(ti), ii = [ "era", "eraYear" ], ai = /*@__PURE__*/ ii.concat([ "year" ]), si = [ "year" ], ci = [ "monthCode" ], ui = /*@__PURE__*/ [ "month" ].concat(ci), li = [ "day" ], fi = /*@__PURE__*/ ui.concat(si), di = /*@__PURE__*/ ci.concat(si), en = /*@__PURE__*/ li.concat(fi), mi = /*@__PURE__*/ li.concat(ui), pi = /*@__PURE__*/ li.concat(ci), hi = /*@__PURE__*/ jr(w, 0), X = "iso8601", gi = "gregory", Ti = "japanese", Di = {
  [gi]: {
    bce: -1,
    ce: 0
  },
  [Ti]: {
    bce: -1,
    ce: 0,
    meiji: 1867,
    taisho: 1911,
    showa: 1925,
    heisei: 1988,
    reiwa: 2018
  },
  ethioaa: {
    era0: 0
  },
  ethiopic: {
    era0: 0,
    era1: 5500
  },
  coptic: {
    era0: -1,
    era1: 0
  },
  roc: {
    beforeroc: -1,
    minguo: 0
  },
  buddhist: {
    be: 0
  },
  islamic: {
    ah: 0
  },
  indian: {
    saka: 0
  },
  persian: {
    ap: 0
  }
}, Ii = {
  chinese: 13,
  dangi: 13,
  hebrew: -6
}, m = /*@__PURE__*/ E(requireType, "string"), f = /*@__PURE__*/ E(requireType, "boolean"), Mi = /*@__PURE__*/ E(requireType, "number"), $ = /*@__PURE__*/ E(requireType, "function"), F = /*@__PURE__*/ Et.map((e => e + "s")), Ni = /*@__PURE__*/ sortStrings(F), yi = /*@__PURE__*/ F.slice(0, 6), Pi = /*@__PURE__*/ F.slice(6), vi = /*@__PURE__*/ Pi.slice(1), Ei = /*@__PURE__*/ Wr(F), Si = /*@__PURE__*/ jr(F, 0), Fi = /*@__PURE__*/ jr(yi, 0), bi = /*@__PURE__*/ E(zeroOutProps, F), j = [ "isoNanosecond", "isoMicrosecond", "isoMillisecond", "isoSecond", "isoMinute", "isoHour" ], Oi = [ "isoDay", "isoMonth", "isoYear" ], wi = /*@__PURE__*/ j.concat(Oi), Bi = /*@__PURE__*/ sortStrings(Oi), ki = /*@__PURE__*/ sortStrings(j), Yi = /*@__PURE__*/ sortStrings(wi), Dt = /*@__PURE__*/ jr(ki, 0), Ci = /*@__PURE__*/ E(zeroOutProps, wi), En = Intl.DateTimeFormat, Zi = "en-GB", Ri = 1e8, zi = Ri * Gr, qi = [ Ri, 0 ], Ui = [ -Ri, 0 ], Ai = 275760, Li = -271821, Wi = 1970, ji = 1972, xi = 12, $i = /*@__PURE__*/ isoArgsToEpochMilli(1868, 9, 8), Gi = /*@__PURE__*/ Jn(computeJapaneseEraParts, WeakMap), Hi = "smallestUnit", Vi = "unit", _i = "roundingIncrement", Ji = "fractionalSecondDigits", Ki = "relativeTo", Qi = {
  constrain: 0,
  reject: 1
}, Xi = /*@__PURE__*/ Object.keys(Qi), ea = {
  compatible: 0,
  reject: 1,
  earlier: 2,
  later: 3
}, na = {
  reject: 0,
  use: 1,
  prefer: 2,
  ignore: 3
}, ta = {
  auto: 0,
  never: 1,
  critical: 2,
  always: 3
}, oa = {
  auto: 0,
  never: 1,
  critical: 2
}, ra = {
  auto: 0,
  never: 1
}, ia = {
  floor: 0,
  halfFloor: 1,
  ceil: 2,
  halfCeil: 3,
  trunc: 4,
  halfTrunc: 5,
  expand: 6,
  halfExpand: 7,
  halfEven: 8
}, aa = /*@__PURE__*/ E(refineUnitOption, Hi), sa = /*@__PURE__*/ E(refineUnitOption, "largestUnit"), ca = /*@__PURE__*/ E(refineUnitOption, Vi), ua = /*@__PURE__*/ E(refineChoiceOption, "overflow", Qi), la = /*@__PURE__*/ E(refineChoiceOption, "disambiguation", ea), fa = /*@__PURE__*/ E(refineChoiceOption, "offset", na), da = /*@__PURE__*/ E(refineChoiceOption, "calendarName", ta), ma = /*@__PURE__*/ E(refineChoiceOption, "timeZoneName", oa), pa = /*@__PURE__*/ E(refineChoiceOption, "offset", ra), ha = /*@__PURE__*/ E(refineChoiceOption, "roundingMode", ia), L = "PlainYearMonth", q = "PlainMonthDay", J = "PlainDate", We = "PlainDateTime", xe = "PlainTime", Te = "ZonedDateTime", Oe = "Instant", qt = "Duration", ga = [ Math.floor, e => hasHalf(e) ? Math.floor(e) : Math.round(e), Math.ceil, e => hasHalf(e) ? Math.ceil(e) : Math.round(e), Math.trunc, e => hasHalf(e) ? Math.trunc(e) || 0 : Math.round(e), e => e < 0 ? Math.floor(e) : Math.ceil(e), e => Math.sign(e) * Math.round(Math.abs(e)) || 0, e => hasHalf(e) ? (e = Math.trunc(e) || 0) + e % 2 : Math.round(e) ], Ta = "UTC", Da = 5184e3, Ia = /*@__PURE__*/ isoArgsToEpochSec(1847), Ma = /*@__PURE__*/ isoArgsToEpochSec(/*@__PURE__*/ (/*@__PURE__*/ new Date).getUTCFullYear() + 10), Na = /0+$/, fn = /*@__PURE__*/ Jn(_zonedEpochSlotsToIso, WeakMap), ya = 2 ** 32 - 1, ie = /*@__PURE__*/ Jn((e => {
  const n = getTimeZoneEssence(e);
  return "object" == typeof n ? new IntlTimeZone(n) : new FixedTimeZone(n || 0);
}));

class FixedTimeZone {
  constructor(e) {
    this.v = e;
  }
  getOffsetNanosecondsFor() {
    return this.v;
  }
  getPossibleInstantsFor(e) {
    return [ isoToEpochNanoWithOffset(e, this.v) ];
  }
  l() {}
}

class IntlTimeZone {
  constructor(e) {
    this.$ = (e => {
      function getOffsetSec(e) {
        const i = clampNumber(e, o, r), [a, s] = computePeriod(i), c = n(a), u = n(s);
        return c === u ? c : pinch(t(a, s), c, u, e);
      }
      function pinch(n, t, o, r) {
        let i, a;
        for (;(void 0 === r || void 0 === (i = r < n[0] ? t : r >= n[1] ? o : void 0)) && (a = n[1] - n[0]); ) {
          const t = n[0] + Math.floor(a / 2);
          e(t) === o ? n[1] = t : n[0] = t + 1;
        }
        return i;
      }
      const n = Jn(e), t = Jn(createSplitTuple);
      let o = Ia, r = Ma;
      return {
        G(e) {
          const n = getOffsetSec(e - 86400), t = getOffsetSec(e + 86400), o = e - n, r = e - t;
          if (n === t) {
            return [ o ];
          }
          const i = getOffsetSec(o);
          return i === getOffsetSec(r) ? [ e - i ] : n > t ? [ o, r ] : [];
        },
        V: getOffsetSec,
        l(e, i) {
          const a = clampNumber(e, o, r);
          let [s, c] = computePeriod(a);
          const u = Da * i, l = i < 0 ? () => c > o || (o = a, 0) : () => s < r || (r = a, 
          0);
          for (;l(); ) {
            const o = n(s), r = n(c);
            if (o !== r) {
              const n = t(s, c);
              pinch(n, o, r);
              const a = n[0];
              if ((compareNumbers(a, e) || 1) === i) {
                return a;
              }
            }
            s += u, c += u;
          }
        }
      };
    })((e => n => {
      const t = hashIntlFormatParts(e, n * Hr);
      return isoArgsToEpochSec(parseIntlPartsYear(t), parseInt(t.month), parseInt(t.day), parseInt(t.hour), parseInt(t.minute), parseInt(t.second)) - n;
    })(e));
  }
  getOffsetNanosecondsFor(e) {
    return this.$.V(epochNanoToSec(e)) * _r;
  }
  getPossibleInstantsFor(e) {
    const [n, t] = [ isoArgsToEpochSec((o = e).isoYear, o.isoMonth, o.isoDay, o.isoHour, o.isoMinute, o.isoSecond), o.isoMillisecond * be + o.isoMicrosecond * Vr + o.isoNanosecond ];
    var o;
    return this.$.G(n).map((e => checkEpochNanoInBounds(moveBigNano(he(e, _r), t))));
  }
  l(e, n) {
    const [t, o] = epochNanoToSecMod(e), r = this.$.l(t + (n > 0 || o ? 1 : 0), n);
    if (void 0 !== r) {
      return he(r, _r);
    }
  }
}

const Pa = "([+−-])", va = "(?:[.,](\\d{1,9}))?", Ea = `(?:(?:${Pa}(\\d{6}))|(\\d{4}))-?(\\d{2})`, Sa = "(\\d{2})(?::?(\\d{2})(?::?(\\d{2})" + va + ")?)?", Fa = Pa + Sa, ba = Ea + "-?(\\d{2})(?:[T ]" + Sa + "(Z|" + Fa + ")?)?", Oa = "\\[(!?)([^\\]]*)\\]", wa = `((?:${Oa}){0,9})`, Ba = /*@__PURE__*/ createRegExp(Ea + wa), ka = /*@__PURE__*/ createRegExp("(?:--)?(\\d{2})-?(\\d{2})" + wa), Ya = /*@__PURE__*/ createRegExp(ba + wa), Ca = /*@__PURE__*/ createRegExp("T?" + Sa + "(?:" + Fa + ")?" + wa), Za = /*@__PURE__*/ createRegExp(Fa), Ra = /*@__PURE__*/ new RegExp(Oa, "g"), za = /*@__PURE__*/ createRegExp(`${Pa}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${va}H)?(?:(\\d+)${va}M)?(?:(\\d+)${va}S)?)?`), qa = /*@__PURE__*/ Jn((e => new En(Zi, {
  timeZone: e,
  era: "short",
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric"
}))), Ua = /^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/, Aa = /*@__PURE__*/ Jn(createIntlCalendar), La = /*@__PURE__*/ Jn((e => new En(Zi, {
  calendar: e,
  timeZone: Ta,
  era: "short",
  year: "numeric",
  month: "short",
  day: "numeric"
}))), Wa = /^M(\d{2})(L?)$/, ja = {
  era: toStringViaPrimitive,
  eraYear: toInteger,
  year: toInteger,
  month: toPositiveInteger,
  monthCode: toStringViaPrimitive,
  day: toPositiveInteger
}, xa = /*@__PURE__*/ jr(w, toInteger), $a = /*@__PURE__*/ jr(F, toStrictInteger), Ga = /*@__PURE__*/ Object.assign({}, ja, xa, $a, {
  offset: toStringViaPrimitive
}), Ha = /*@__PURE__*/ E(remapProps, w, j), Va = {
  dateAdd(e, n, t) {
    const o = H(t);
    let r, {years: i, months: a, weeks: s, days: c} = n;
    if (c += durationFieldsToBigNano(n, 5)[0], i || a) {
      r = ((e, n, t, o, r) => {
        let [i, a, s] = e.h(n);
        if (t) {
          const [n, o] = e.I(i, a);
          i += t, a = monthCodeNumberToMonth(n, o, e.U(i)), a = clampEntity("month", a, 1, e.L(i), r);
        }
        return o && ([i, a] = e._(i, a, o)), s = clampEntity("day", s, 1, e.j(i, a), r), 
        e.q(i, a, s);
      })(this, e, i, a, o);
    } else {
      if (!s && !c) {
        return e;
      }
      r = isoToEpochMilli(e);
    }
    return r += (7 * s + c) * Gr, checkIsoDateInBounds(epochMilliToIso(r));
  },
  dateUntil(e, n, t) {
    if (t <= 7) {
      let o = 0, r = diffDays({
        ...e,
        ...Dt
      }, {
        ...n,
        ...Dt
      });
      return 7 === t && ([o, r] = divModTrunc(r, 7)), {
        ...Si,
        weeks: o,
        days: r
      };
    }
    const o = this.h(e), r = this.h(n);
    let [i, a, s] = ((e, n, t, o, r, i, a) => {
      let s = r - n, c = i - t, u = a - o;
      if (s || c) {
        const l = Math.sign(s || c);
        let f = e.j(r, i), d = 0;
        if (Math.sign(u) === -l) {
          const o = f;
          [r, i] = e._(r, i, -l), s = r - n, c = i - t, f = e.j(r, i), d = l < 0 ? -o : f;
        }
        if (u = a - Math.min(o, f) + d, s) {
          const [o, a] = e.I(n, t), [u, f] = e.I(r, i);
          if (c = u - o || Number(f) - Number(a), Math.sign(c) === -l) {
            const t = l < 0 && -e.L(r);
            s = (r -= l) - n, c = i - monthCodeNumberToMonth(o, a, e.U(r)) + (t || e.L(r));
          }
        }
      }
      return [ s, c, u ];
    })(this, ...o, ...r);
    return 8 === t && (a += this.J(i, o[0]), i = 0), {
      ...Si,
      years: i,
      months: a,
      days: s
    };
  },
  dateFromFields(e, n) {
    const t = H(n), o = refineYear(this, e), r = refineMonth(this, e, o, t), i = refineDay(this, e, r, o, t);
    return v(checkIsoDateInBounds(this.P(o, r, i)), this.id || X);
  },
  yearMonthFromFields(e, n) {
    const t = H(n), o = refineYear(this, e), r = refineMonth(this, e, o, t);
    return createPlainYearMonthSlots(checkIsoYearMonthInBounds(this.P(o, r, 1)), this.id || X);
  },
  monthDayFromFields(e, n) {
    const t = H(n), o = !this.id, {monthCode: r, year: i, month: a} = e;
    let s, c, u, l, f;
    if (void 0 !== r) {
      [s, c] = parseMonthCode(r), f = getDefinedProp(e, "day");
      const n = this.N(s, c, f);
      if (!n) {
        throw new RangeError(yr);
      }
      if ([u, l] = n, void 0 !== a && a !== l) {
        throw new RangeError(Mr);
      }
      o && (l = clampEntity("month", l, 1, xi, 1), f = clampEntity("day", f, 1, computeIsoDaysInMonth(void 0 !== i ? i : u, l), t));
    } else {
      u = void 0 === i && o ? ji : refineYear(this, e), l = refineMonth(this, e, u, t), 
      f = refineDay(this, e, l, u, t);
      const n = this.U(u);
      c = l === n, s = monthToMonthCodeNumber(l, n);
      const r = this.N(s, c, f);
      if (!r) {
        throw new RangeError(yr);
      }
      [u, l] = r;
    }
    return createPlainMonthDaySlots(checkIsoDateInBounds(this.P(u, l, f)), this.id || X);
  },
  fields(e) {
    return getCalendarEraOrigins(this) && e.includes("year") ? [ ...e, ...ii ] : e;
  },
  mergeFields(e, n) {
    const t = Object.assign(Object.create(null), e);
    return spliceFields(t, n, ui), getCalendarEraOrigins(this) && (spliceFields(t, n, ai), 
    this.id === Ti && spliceFields(t, n, mi, ii)), t;
  },
  inLeapYear(e) {
    const [n] = this.h(e);
    return this.K(n);
  },
  monthsInYear(e) {
    const [n] = this.h(e);
    return this.L(n);
  },
  daysInMonth(e) {
    const [n, t] = this.h(e);
    return this.j(n, t);
  },
  daysInYear(e) {
    const [n] = this.h(e);
    return this.X(n);
  },
  dayOfYear: computeNativeDayOfYear,
  era(e) {
    return this.ee(e)[0];
  },
  eraYear(e) {
    return this.ee(e)[1];
  },
  monthCode(e) {
    const [n, t] = this.h(e), [o, r] = this.I(n, t);
    return ((e, n) => "M" + xr(e) + (n ? "L" : ""))(o, r);
  },
  dayOfWeek: computeIsoDayOfWeek,
  daysInWeek() {
    return 7;
  }
}, _a = {
  dayOfYear: computeNativeDayOfYear,
  h: computeIsoDateParts,
  q: isoArgsToEpochMilli
}, Ja = /*@__PURE__*/ Object.assign({}, _a, {
  weekOfYear: computeNativeWeekOfYear,
  yearOfWeek: computeNativeYearOfWeek,
  R(e) {
    function computeWeekShift(e) {
      return (7 - e < n ? 7 : 0) - e;
    }
    function computeWeeksInYear(e) {
      const n = computeIsoDaysInYear(l + e), t = e || 1, o = computeWeekShift(modFloor(a + n * t, 7));
      return c = (n + (o - s) * t) / 7;
    }
    const n = this.id ? 1 : 4, t = computeIsoDayOfWeek(e), o = this.dayOfYear(e), r = modFloor(t - 1, 7), i = o - 1, a = modFloor(r - i, 7), s = computeWeekShift(a);
    let c, u = Math.floor((i - s) / 7) + 1, l = e.isoYear;
    return u ? u > computeWeeksInYear(0) && (u = 1, l++) : (u = computeWeeksInYear(-1), 
    l--), [ u, l, c ];
  }
}), Ka = {
  dayOfYear: computeNativeDayOfYear,
  h: computeIntlDateParts,
  q: computeIntlEpochMilli,
  weekOfYear: computeNativeWeekOfYear,
  yearOfWeek: computeNativeYearOfWeek,
  R() {
    return [];
  }
}, Y = /*@__PURE__*/ createNativeOpsCreator(/*@__PURE__*/ Object.assign({}, Va, Ja, {
  h: computeIsoDateParts,
  ee(e) {
    return this.id === gi ? computeGregoryEraParts(e) : this.id === Ti ? Gi(e) : [];
  },
  I: (e, n) => [ n, 0 ],
  N(e, n) {
    if (!n) {
      return [ ji, e ];
    }
  },
  K: computeIsoInLeapYear,
  U() {},
  L: computeIsoMonthsInYear,
  J: e => e * xi,
  j: computeIsoDaysInMonth,
  X: computeIsoDaysInYear,
  P: (e, n, t) => ({
    isoYear: e,
    isoMonth: n,
    isoDay: t
  }),
  q: isoArgsToEpochMilli,
  _: (e, n, t) => (e += divTrunc(t, xi), (n += modTrunc(t, xi)) < 1 ? (e--, n += xi) : n > xi && (e++, 
  n -= xi), [ e, n ]),
  year(e) {
    return e.isoYear;
  },
  month(e) {
    return e.isoMonth;
  },
  day: e => e.isoDay
}), /*@__PURE__*/ Object.assign({}, Va, Ka, {
  h: computeIntlDateParts,
  ee(e) {
    const n = this.O(e);
    return [ n.era, n.eraYear ];
  },
  I(e, n) {
    const t = computeIntlLeapMonth.call(this, e);
    return [ monthToMonthCodeNumber(n, t), t === n ];
  },
  N(e, n, t) {
    let [o, r, i] = computeIntlDateParts.call(this, {
      isoYear: ji,
      isoMonth: xi,
      isoDay: 31
    });
    const a = computeIntlLeapMonth.call(this, o), s = r === a;
    1 === (compareNumbers(e, monthToMonthCodeNumber(r, a)) || compareNumbers(Number(n), Number(s)) || compareNumbers(t, i)) && o--;
    for (let r = 0; r < 100; r++) {
      const i = o - r, a = computeIntlLeapMonth.call(this, i), s = monthCodeNumberToMonth(e, n, a);
      if (n === (s === a) && t <= computeIntlDaysInMonth.call(this, i, s)) {
        return [ i, s ];
      }
    }
  },
  K(e) {
    const n = computeIntlDaysInYear.call(this, e);
    return n > computeIntlDaysInYear.call(this, e - 1) && n > computeIntlDaysInYear.call(this, e + 1);
  },
  U: computeIntlLeapMonth,
  L: computeIntlMonthsInYear,
  J(e, n) {
    const t = n + e, o = Math.sign(e), r = o < 0 ? -1 : 0;
    let i = 0;
    for (let e = n; e !== t; e += o) {
      i += computeIntlMonthsInYear.call(this, e + r);
    }
    return i;
  },
  j: computeIntlDaysInMonth,
  X: computeIntlDaysInYear,
  P(e, n, t) {
    return epochMilliToIso(computeIntlEpochMilli.call(this, e, n, t));
  },
  q: computeIntlEpochMilli,
  _(e, n, t) {
    if (t) {
      if (n += t, !Number.isSafeInteger(n)) {
        throw new RangeError(Cr);
      }
      if (t < 0) {
        for (;n < 1; ) {
          n += computeIntlMonthsInYear.call(this, --e);
        }
      } else {
        let t;
        for (;n > (t = computeIntlMonthsInYear.call(this, e)); ) {
          n -= t, e++;
        }
      }
    }
    return [ e, n ];
  },
  year(e) {
    return this.O(e).year;
  },
  month(e) {
    const {year: n, F: t} = this.O(e), {C: o} = this.B(n);
    return o[t] + 1;
  },
  day(e) {
    return this.O(e).day;
  }
})), Qa = "numeric", Xa = [ "timeZoneName" ], es = {
  month: Qa,
  day: Qa
}, ns = {
  year: Qa,
  month: Qa
}, ts = /*@__PURE__*/ Object.assign({}, ns, {
  day: Qa
}), os = {
  hour: Qa,
  minute: Qa,
  second: Qa
}, rs = /*@__PURE__*/ Object.assign({}, ts, os), is$3 = /*@__PURE__*/ Object.assign({}, rs, {
  timeZoneName: "short"
}), as = /*@__PURE__*/ Object.keys(ns), ss = /*@__PURE__*/ Object.keys(es), cs = /*@__PURE__*/ Object.keys(ts), us = /*@__PURE__*/ Object.keys(os), ls = [ "dateStyle" ], fs = /*@__PURE__*/ as.concat(ls), ds = /*@__PURE__*/ ss.concat(ls), ms = /*@__PURE__*/ cs.concat(ls, [ "weekday" ]), ps = /*@__PURE__*/ us.concat([ "dayPeriod", "timeStyle" ]), hs = /*@__PURE__*/ ms.concat(ps), gs = /*@__PURE__*/ hs.concat(Xa), Ts = /*@__PURE__*/ Xa.concat(ps), Ds = /*@__PURE__*/ Xa.concat(ms), Is$5 = /*@__PURE__*/ Xa.concat([ "day", "weekday" ], ps), Ms = /*@__PURE__*/ Xa.concat([ "year", "weekday" ], ps), Ns = {}, t = [ /*@__PURE__*/ createOptionsTransformer(hs, rs), y ], s = [ /*@__PURE__*/ createOptionsTransformer(gs, is$3), y, 0, (e, n) => {
  const t = I(e.timeZone);
  if (n && I(n.timeZone) !== t) {
    throw new RangeError(Fr);
  }
  return t;
} ], n = [ /*@__PURE__*/ createOptionsTransformer(hs, rs, Xa), isoToEpochMilli ], o = [ /*@__PURE__*/ createOptionsTransformer(ms, ts, Ts), isoToEpochMilli ], r = [ /*@__PURE__*/ createOptionsTransformer(ps, os, Ds), e => isoTimeFieldsToNano(e) / be ], a = [ /*@__PURE__*/ createOptionsTransformer(fs, ns, Is$5), isoToEpochMilli, 1 ], i = [ /*@__PURE__*/ createOptionsTransformer(ds, es, Ms), isoToEpochMilli, 1 ];

let ys;

function createSlotClass(e, t, n, o, r) {
  function Class(...e) {
    if (!(this instanceof Class)) {
      throw new TypeError(P);
    }
    oo(this, t(...e));
  }
  function bindMethod(e, t) {
    return Object.defineProperties((function(...t) {
      return e.call(this, getSpecificSlots(this), ...t);
    }), D(t));
  }
  function getSpecificSlots(t) {
    const n = no(t);
    if (!n || n.branding !== e) {
      throw new TypeError(P);
    }
    return n;
  }
  return Object.defineProperties(Class.prototype, {
    ...O(T(bindMethod, n)),
    ...p(T(bindMethod, o)),
    ...h("Temporal." + e)
  }), Object.defineProperties(Class, {
    ...p(r),
    ...D(e)
  }), [ Class, e => {
    const t = Object.create(Class.prototype);
    return oo(t, e), t;
  }, getSpecificSlots ];
}

function createProtocolValidator(e) {
  return e = e.concat("id").sort(), t => {
    if (!C(t, e)) {
      throw new TypeError(g);
    }
    return t;
  };
}

function rejectInvalidBag(e) {
  if (no(e) || void 0 !== e.calendar || void 0 !== e.timeZone) {
    throw new TypeError(Z);
  }
  return e;
}

function createCalendarFieldMethods(e, t) {
  const n = {};
  for (const o in e) {
    n[o] = ({o: e}, n) => {
      const r = no(n) || {}, {branding: a} = r, i = a === J || t.includes(a) ? r : toPlainDateSlots(n);
      return e[o](i);
    };
  }
  return n;
}

function createCalendarGetters(e) {
  const t = {};
  for (const n in e) {
    t[n] = e => {
      const {calendar: t} = e;
      return (o = t, "string" == typeof o ? Y(o) : (r = o, Object.assign(Object.create(co), {
        i: r
      })))[n](e);
      var o, r;
    };
  }
  return t;
}

function neverValueOf() {
  throw new TypeError(A);
}

function createCalendarFromSlots({calendar: e}) {
  return "string" == typeof e ? new lr(e) : e;
}

function toPlainMonthDaySlots(e, t) {
  if (t = U(t), z(e)) {
    const n = no(e);
    if (n && n.branding === q) {
      return H(t), n;
    }
    const o = extractCalendarSlotFromBag(e);
    return K(Qo(o || X), !o, e, t);
  }
  const n = Q(Y, e);
  return H(t), n;
}

function getOffsetNanosecondsForAdapter(e, t, n) {
  return o = t.call(e, Co(_(n))), ae(u(o));
  var o;
}

function createAdapterOps(e, t = ho) {
  const n = Object.keys(t).sort(), o = {};
  for (const r of n) {
    o[r] = E(t[r], e, $(e[r]));
  }
  return o;
}

function createTimeZoneOps(e, t) {
  return "string" == typeof e ? ie(e) : createAdapterOps(e, t);
}

function createTimeZoneOffsetOps(e) {
  return createTimeZoneOps(e, Do);
}

function toInstantSlots(e) {
  if (z(e)) {
    const t = no(e);
    if (t) {
      switch (t.branding) {
       case Oe:
        return t;

       case Te:
        return _(t.epochNanoseconds);
      }
    }
  }
  return pe(e);
}

function getImplTransition(e, t, n) {
  const o = t.l(toInstantSlots(n).epochNanoseconds, e);
  return o ? Co(_(o)) : null;
}

function refineTimeZoneSlot(e) {
  return z(e) ? (no(e) || {}).timeZone || Fo(e) : (e => ye(Ne(m(e))))(e);
}

function toPlainTimeSlots(e, t) {
  if (z(e)) {
    const n = no(e) || {};
    switch (n.branding) {
     case xe:
      return H(t), n;

     case We:
      return H(t), Ge(n);

     case Te:
      return H(t), Re(createTimeZoneOffsetOps, n);
    }
    return Ue(e, t);
  }
  return H(t), ze(e);
}

function optionalToPlainTimeFields(e) {
  return void 0 === e ? void 0 : toPlainTimeSlots(e);
}

function toPlainYearMonthSlots(e, t) {
  if (t = U(t), z(e)) {
    const n = no(e);
    return n && n.branding === L ? (H(t), n) : nt(Ho(getCalendarSlotFromBag(e)), e, t);
  }
  const n = ot(Y, e);
  return H(t), n;
}

function toPlainDateTimeSlots(e, t) {
  if (t = U(t), z(e)) {
    const n = no(e) || {};
    switch (n.branding) {
     case We:
      return H(t), n;

     case J:
      return H(t), ee({
        ...n,
        ...Dt
      });

     case Te:
      return H(t), ht(createTimeZoneOffsetOps, n);
    }
    return Pt(Ko(getCalendarSlotFromBag(e)), e, t);
  }
  const n = Ct(e);
  return H(t), n;
}

function toPlainDateSlots(e, t) {
  if (t = U(t), z(e)) {
    const n = no(e) || {};
    switch (n.branding) {
     case J:
      return H(t), n;

     case We:
      return H(t), v(n);

     case Te:
      return H(t), Bt(createTimeZoneOffsetOps, n);
    }
    return Yt(Ko(getCalendarSlotFromBag(e)), e, t);
  }
  const n = At(e);
  return H(t), n;
}

function dayAdapter(e, t, n) {
  return d(t.call(e, Yo(v(n, e))));
}

function createCompoundOpsCreator(e) {
  return t => "string" == typeof t ? Y(t) : ((e, t) => {
    const n = Object.keys(t).sort(), o = {};
    for (const r of n) {
      o[r] = E(t[r], e, e[r]);
    }
    return o;
  })(t, e);
}

function toDurationSlots(e) {
  if (z(e)) {
    const t = no(e);
    return t && t.branding === qt ? t : Ht(e);
  }
  return Kt(e);
}

function refinePublicRelativeTo(e) {
  if (void 0 !== e) {
    if (z(e)) {
      const t = no(e) || {};
      switch (t.branding) {
       case Te:
       case J:
        return t;

       case We:
        return v(t);
      }
      const n = getCalendarSlotFromBag(e);
      return {
        ...Qt(refineTimeZoneSlot, createTimeZoneOps, Ko(n), e),
        calendar: n
      };
    }
    return Xt(e);
  }
}

function getCalendarSlotFromBag(e) {
  return extractCalendarSlotFromBag(e) || X;
}

function extractCalendarSlotFromBag(e) {
  const {calendar: t} = e;
  if (void 0 !== t) {
    return refineCalendarSlot(t);
  }
}

function refineCalendarSlot(e) {
  return z(e) ? (no(e) || {}).calendar || cr(e) : (e => an(sn(m(e))))(e);
}

function toZonedDateTimeSlots(e, t) {
  if (t = U(t), z(e)) {
    const n = no(e);
    if (n && n.branding === Te) {
      return wn(t), n;
    }
    const o = getCalendarSlotFromBag(e);
    return jn(refineTimeZoneSlot, createTimeZoneOps, Ko(o), o, e, t);
  }
  return Mn(e, t);
}

function adaptDateMethods(e) {
  return T((e => t => e(slotsToIso(t))), e);
}

function slotsToIso(e) {
  return fn(e, createTimeZoneOffsetOps);
}

function createDateTimeFormatClass() {
  const e = En.prototype, t = Object.getOwnPropertyDescriptors(e), n = Object.getOwnPropertyDescriptors(En), DateTimeFormat = function(e, t = {}) {
    if (!(this instanceof DateTimeFormat)) {
      return new DateTimeFormat(e, t);
    }
    Or.set(this, ((e, t = {}) => {
      const n = new En(e, t), o = n.resolvedOptions(), r = o.locale, a = Vn(Object.keys(t), o), i = Jn(createFormatPrepperForBranding), prepFormat = (...e) => {
        let t;
        const o = e.map(((e, n) => {
          const o = no(e), r = (o || {}).branding;
          if (n && t && t !== r) {
            throw new TypeError(kn);
          }
          return t = r, o;
        }));
        return t ? i(t)(r, a, ...o) : [ n, ...e ];
      };
      return prepFormat.u = n, prepFormat;
    })(e, t));
  };
  for (const e in t) {
    const n = t[e], o = e.startsWith("format") && createFormatMethod(e);
    "function" == typeof n.value ? n.value = "constructor" === e ? DateTimeFormat : o || createProxiedMethod(e) : o && (n.get = function() {
      return o.bind(this);
    });
  }
  return n.prototype.value = Object.create(e, t), Object.defineProperties(DateTimeFormat, n), 
  DateTimeFormat;
}

function createFormatMethod(e) {
  return function(...t) {
    const n = Or.get(this), [o, ...r] = n(...t);
    return o[e](...r);
  };
}

function createProxiedMethod(e) {
  return function(...t) {
    return Or.get(this).u[e](...t);
  };
}

function createFormatPrepperForBranding(t) {
  const n = xn[t];
  if (!n) {
    throw new TypeError(Ln(t));
  }
  return e(n, Jn(qn));
}

const xn = {
  Instant: t,
  PlainDateTime: n,
  PlainDate: o,
  PlainTime: r,
  PlainYearMonth: a,
  PlainMonthDay: i
}, Rn = /*@__PURE__*/ e(t), Wn = /*@__PURE__*/ e(s), Gn = /*@__PURE__*/ e(n), Un = /*@__PURE__*/ e(o), zn = /*@__PURE__*/ e(r), Hn = /*@__PURE__*/ e(a), Kn = /*@__PURE__*/ e(i), Qn = {
  era: l,
  eraYear: c,
  year: u,
  month: d,
  daysInMonth: d,
  daysInYear: d,
  inLeapYear: f,
  monthsInYear: d
}, Xn = {
  monthCode: m
}, $n = {
  day: d
}, _n = {
  dayOfWeek: d,
  dayOfYear: d,
  weekOfYear: S,
  yearOfWeek: c,
  daysInWeek: d
}, eo = /*@__PURE__*/ Object.assign({}, Qn, Xn, $n, _n), to = /*@__PURE__*/ new WeakMap, no = /*@__PURE__*/ to.get.bind(to), oo = /*@__PURE__*/ to.set.bind(to), ro = {
  ...createCalendarFieldMethods(Qn, [ L ]),
  ...createCalendarFieldMethods(_n, []),
  ...createCalendarFieldMethods(Xn, [ L, q ]),
  ...createCalendarFieldMethods($n, [ q ])
}, ao = /*@__PURE__*/ createCalendarGetters(eo), io = /*@__PURE__*/ createCalendarGetters({
  ...Qn,
  ...Xn
}), so = /*@__PURE__*/ createCalendarGetters({
  ...Xn,
  ...$n
}), lo = {
  calendarId: e => I(e.calendar)
}, co = /*@__PURE__*/ T(((e, t) => function(n) {
  const {i: o} = this;
  return e(o[t](Yo(v(n, o))));
}), eo), uo = /*@__PURE__*/ b((e => t => t[e]), F.concat("sign")), fo = /*@__PURE__*/ b(((e, t) => e => e[j[t]]), w), mo = {
  epochSeconds: M,
  epochMilliseconds: y,
  epochMicroseconds: N,
  epochNanoseconds: B
}, So = /*@__PURE__*/ E(V, new Set([ "branding" ])), [Oo, To, po] = createSlotClass(q, E(G, refineCalendarSlot), {
  ...lo,
  ...so
}, {
  getISOFields: So,
  getCalendar: createCalendarFromSlots,
  with(e, t, n) {
    return To(k(_o, e, this, rejectInvalidBag(t), n));
  },
  equals: (e, t) => x(e, toPlainMonthDaySlots(t)),
  toPlainDate(e, t) {
    return Yo(R($o, e, this, t));
  },
  toLocaleString(e, t, n) {
    const [o, r] = Kn(t, n, e);
    return o.format(r);
  },
  toString: W,
  toJSON: e => W(e),
  valueOf: neverValueOf
}, {
  from: (e, t) => To(toPlainMonthDaySlots(e, t))
}), ho = {
  getOffsetNanosecondsFor: getOffsetNanosecondsForAdapter,
  getPossibleInstantsFor(e, t, n) {
    const o = [ ...t.call(e, No(ee(n, X))) ].map((e => go(e).epochNanoseconds)), r = o.length;
    return r > 1 && (o.sort(te), ne(oe(re(o[0], o[r - 1])))), o;
  }
}, Do = {
  getOffsetNanosecondsFor: getOffsetNanosecondsForAdapter
}, [Po, Co, go] = createSlotClass(Oe, Se, mo, {
  add: (e, t) => Co(se(0, e, toDurationSlots(t))),
  subtract: (e, t) => Co(se(1, e, toDurationSlots(t))),
  until: (e, t, n) => ar(le(0, e, toInstantSlots(t), n)),
  since: (e, t, n) => ar(le(1, e, toInstantSlots(t), n)),
  round: (e, t) => Co(ce(e, t)),
  equals: (e, t) => ue(e, toInstantSlots(t)),
  toZonedDateTime(e, t) {
    const n = de(t);
    return dr(fe(e, refineTimeZoneSlot(n.timeZone), refineCalendarSlot(n.calendar)));
  },
  toZonedDateTimeISO: (e, t) => dr(fe(e, refineTimeZoneSlot(t))),
  toLocaleString(e, t, n) {
    const [o, r] = Rn(t, n, e);
    return o.format(r);
  },
  toString: (e, t) => me(refineTimeZoneSlot, createTimeZoneOffsetOps, e, t),
  toJSON: e => me(refineTimeZoneSlot, createTimeZoneOffsetOps, e),
  valueOf: neverValueOf
}, {
  from: e => Co(toInstantSlots(e)),
  fromEpochSeconds: e => Co(De(e)),
  fromEpochMilliseconds: e => Co(Pe(e)),
  fromEpochMicroseconds: e => Co(Ce(e)),
  fromEpochNanoseconds: e => Co(ge(e)),
  compare: (e, t) => Ze(toInstantSlots(e), toInstantSlots(t))
}), [Zo, bo] = createSlotClass("TimeZone", (e => {
  const t = Me(e);
  return {
    branding: "TimeZone",
    id: t,
    o: ie(t)
  };
}), {
  id: e => e.id
}, {
  getPossibleInstantsFor: ({o: e}, t) => e.getPossibleInstantsFor(toPlainDateTimeSlots(t)).map((e => Co(_(e)))),
  getOffsetNanosecondsFor: ({o: e}, t) => e.getOffsetNanosecondsFor(toInstantSlots(t).epochNanoseconds),
  getOffsetStringFor(e, t) {
    const n = toInstantSlots(t).epochNanoseconds, o = createAdapterOps(this, Do).getOffsetNanosecondsFor(n);
    return Fe(o);
  },
  getPlainDateTimeFor(e, t, n = X) {
    const o = toInstantSlots(t).epochNanoseconds, r = createAdapterOps(this, Do).getOffsetNanosecondsFor(o);
    return No(ee(Ie(o, r), refineCalendarSlot(n)));
  },
  getInstantFor(e, t, n) {
    const o = toPlainDateTimeSlots(t), r = ve(n), a = createAdapterOps(this);
    return Co(_(we(a, o, r)));
  },
  getNextTransition: ({o: e}, t) => getImplTransition(1, e, t),
  getPreviousTransition: ({o: e}, t) => getImplTransition(-1, e, t),
  equals(e, t) {
    return !!je(this, refineTimeZoneSlot(t));
  },
  toString: e => e.id,
  toJSON: e => e.id
}, {
  from(e) {
    const t = refineTimeZoneSlot(e);
    return "string" == typeof t ? new Zo(t) : t;
  }
}), Fo = /*@__PURE__*/ createProtocolValidator(Object.keys(ho)), [Io, vo] = createSlotClass(xe, ke, fo, {
  getISOFields: So,
  with(e, t, n) {
    return vo(Be(this, rejectInvalidBag(t), n));
  },
  add: (e, t) => vo(Ye(0, e, toDurationSlots(t))),
  subtract: (e, t) => vo(Ye(1, e, toDurationSlots(t))),
  until: (e, t, n) => ar(Ae(0, e, toPlainTimeSlots(t), n)),
  since: (e, t, n) => ar(Ae(1, e, toPlainTimeSlots(t), n)),
  round: (e, t) => vo(Ee(e, t)),
  equals: (e, t) => Ve(e, toPlainTimeSlots(t)),
  toZonedDateTime: (e, t) => dr(Je(refineTimeZoneSlot, toPlainDateSlots, createTimeZoneOps, e, t)),
  toPlainDateTime: (e, t) => No(Le(e, toPlainDateSlots(t))),
  toLocaleString(e, t, n) {
    const [o, r] = zn(t, n, e);
    return o.format(r);
  },
  toString: qe,
  toJSON: e => qe(e),
  valueOf: neverValueOf
}, {
  from: (e, t) => vo(toPlainTimeSlots(e, t)),
  compare: (e, t) => He(toPlainTimeSlots(e), toPlainTimeSlots(t))
}), [wo, jo, Mo] = createSlotClass(L, E(tt, refineCalendarSlot), {
  ...lo,
  ...io
}, {
  getISOFields: So,
  getCalendar: createCalendarFromSlots,
  with(e, t, n) {
    return jo(Ke(Xo, e, this, rejectInvalidBag(t), n));
  },
  add: (e, t, n) => jo(Qe(nr, 0, e, toDurationSlots(t), n)),
  subtract: (e, t, n) => jo(Qe(nr, 1, e, toDurationSlots(t), n)),
  until: (e, t, n) => ar(Xe(or, 0, e, toPlainYearMonthSlots(t), n)),
  since: (e, t, n) => ar(Xe(or, 1, e, toPlainYearMonthSlots(t), n)),
  equals: (e, t) => $e(e, toPlainYearMonthSlots(t)),
  toPlainDate(e, t) {
    return Yo(_e($o, e, this, t));
  },
  toLocaleString(e, t, n) {
    const [o, r] = Hn(t, n, e);
    return o.format(r);
  },
  toString: et,
  toJSON: e => et(e),
  valueOf: neverValueOf
}, {
  from: (e, t) => jo(toPlainYearMonthSlots(e, t)),
  compare: (e, t) => rt(toPlainYearMonthSlots(e), toPlainYearMonthSlots(t))
}), [yo, No] = createSlotClass(We, E(pt, refineCalendarSlot), {
  ...lo,
  ...ao,
  ...fo
}, {
  getISOFields: So,
  getCalendar: createCalendarFromSlots,
  with(e, t, n) {
    return No(at($o, e, this, rejectInvalidBag(t), n));
  },
  withCalendar: (e, t) => No(it(e, refineCalendarSlot(t))),
  withPlainDate: (e, t) => No(st(e, toPlainDateSlots(t))),
  withPlainTime: (e, t) => No(lt(e, optionalToPlainTimeFields(t))),
  add: (e, t, n) => No(ct(er, 0, e, toDurationSlots(t), n)),
  subtract: (e, t, n) => No(ct(er, 1, e, toDurationSlots(t), n)),
  until: (e, t, n) => ar(ut(tr, 0, e, toPlainDateTimeSlots(t), n)),
  since: (e, t, n) => ar(ut(tr, 1, e, toPlainDateTimeSlots(t), n)),
  round: (e, t) => No(dt(e, t)),
  equals: (e, t) => ft(e, toPlainDateTimeSlots(t)),
  toZonedDateTime: (e, t, n) => dr(mt(createTimeZoneOps, e, refineTimeZoneSlot(t), n)),
  toPlainDate: e => Yo(v(e)),
  toPlainTime: e => vo(Ge(e)),
  toPlainYearMonth(e) {
    return jo(St(Ho, e, this));
  },
  toPlainMonthDay(e) {
    return To(Ot(Qo, e, this));
  },
  toLocaleString(e, t, n) {
    const [o, r] = Gn(t, n, e);
    return o.format(r);
  },
  toString: Tt,
  toJSON: e => Tt(e),
  valueOf: neverValueOf
}, {
  from: (e, t) => No(toPlainDateTimeSlots(e, t)),
  compare: (e, t) => gt(toPlainDateTimeSlots(e), toPlainDateTimeSlots(t))
}), [Bo, Yo, Ao] = createSlotClass(J, E(Nt, refineCalendarSlot), {
  ...lo,
  ...ao
}, {
  getISOFields: So,
  getCalendar: createCalendarFromSlots,
  with(e, t, n) {
    return Yo(Zt($o, e, this, rejectInvalidBag(t), n));
  },
  withCalendar: (e, t) => Yo(it(e, refineCalendarSlot(t))),
  add: (e, t, n) => Yo(bt(er, 0, e, toDurationSlots(t), n)),
  subtract: (e, t, n) => Yo(bt(er, 1, e, toDurationSlots(t), n)),
  until: (e, t, n) => ar(Ft(tr, 0, e, toPlainDateSlots(t), n)),
  since: (e, t, n) => ar(Ft(tr, 1, e, toPlainDateSlots(t), n)),
  equals: (e, t) => It(e, toPlainDateSlots(t)),
  toZonedDateTime(e, t) {
    const n = !z(t) || t instanceof Zo ? {
      timeZone: t
    } : t;
    return dr(vt(refineTimeZoneSlot, toPlainTimeSlots, createTimeZoneOps, e, n));
  },
  toPlainDateTime: (e, t) => No(wt(e, optionalToPlainTimeFields(t))),
  toPlainYearMonth(e) {
    return jo(jt(Ho, e, this));
  },
  toPlainMonthDay(e) {
    return To(Mt(Qo, e, this));
  },
  toLocaleString(e, t, n) {
    const [o, r] = Un(t, n, e);
    return o.format(r);
  },
  toString: yt,
  toJSON: e => yt(e),
  valueOf: neverValueOf
}, {
  from: (e, t) => Yo(toPlainDateSlots(e, t)),
  compare: (e, t) => rt(toPlainDateSlots(e), toPlainDateSlots(t))
}), Eo = {
  fields(e, t, n) {
    return [ ...t.call(e, n) ];
  }
}, Vo = /*@__PURE__*/ Object.assign({
  dateFromFields(e, t, n, o) {
    return Ao(t.call(e, Object.assign(Object.create(null), n), o));
  }
}, Eo), Jo = /*@__PURE__*/ Object.assign({
  yearMonthFromFields(e, t, n, o) {
    return Mo(t.call(e, Object.assign(Object.create(null), n), o));
  }
}, Eo), Lo = /*@__PURE__*/ Object.assign({
  monthDayFromFields(e, t, n, o) {
    return po(t.call(e, Object.assign(Object.create(null), n), o));
  }
}, Eo), qo = {
  mergeFields(e, t, n, o) {
    return de(t.call(e, Object.assign(Object.create(null), n), Object.assign(Object.create(null), o)));
  }
}, ko = /*@__PURE__*/ Object.assign({}, Vo, qo), xo = /*@__PURE__*/ Object.assign({}, Jo, qo), Ro = /*@__PURE__*/ Object.assign({}, Lo, qo), Wo = {
  dateAdd(e, t, n, o, r) {
    return Ao(t.call(e, Yo(v(n, e)), ar(Vt(o)), r));
  }
}, Go = /*@__PURE__*/ Object.assign({}, Wo, {
  dateUntil(e, t, n, o, r, a) {
    return ir(t.call(e, Yo(v(n, e)), Yo(v(o, e)), Object.assign(Object.create(null), a, {
      largestUnit: Et[r]
    })));
  }
}), Uo = /*@__PURE__*/ Object.assign({}, Wo, {
  day: dayAdapter
}), zo = /*@__PURE__*/ Object.assign({}, Go, {
  day: dayAdapter
}), Ho = /*@__PURE__*/ createCompoundOpsCreator(Jo), Ko = /*@__PURE__*/ createCompoundOpsCreator(Vo), Qo = /*@__PURE__*/ createCompoundOpsCreator(Lo), Xo = /*@__PURE__*/ createCompoundOpsCreator(xo), $o = /*@__PURE__*/ createCompoundOpsCreator(ko), _o = /*@__PURE__*/ createCompoundOpsCreator(Ro), er = /*@__PURE__*/ createCompoundOpsCreator(Wo), tr = /*@__PURE__*/ createCompoundOpsCreator(Go), nr = /*@__PURE__*/ createCompoundOpsCreator(Uo), or = /*@__PURE__*/ createCompoundOpsCreator(zo), [rr, ar, ir] = createSlotClass(qt, Lt, {
  ...uo,
  blank: Jt
}, {
  with: (e, t) => ar(kt(e, t)),
  negated: e => ar(xt(e)),
  abs: e => ar(Rt(e)),
  add: (e, t, n) => ar(Wt(refinePublicRelativeTo, tr, createTimeZoneOps, 0, e, toDurationSlots(t), n)),
  subtract: (e, t, n) => ar(Wt(refinePublicRelativeTo, tr, createTimeZoneOps, 1, e, toDurationSlots(t), n)),
  round: (e, t) => ar(Gt(refinePublicRelativeTo, tr, createTimeZoneOps, e, t)),
  total: (e, t) => Ut(refinePublicRelativeTo, tr, createTimeZoneOps, e, t),
  toLocaleString(e, t, n) {
    return Intl.DurationFormat ? new Intl.DurationFormat(t, n).format(this) : zt(e);
  },
  toString: zt,
  toJSON: e => zt(e),
  valueOf: neverValueOf
}, {
  from: e => ar(toDurationSlots(e)),
  compare: (e, t, n) => $t(refinePublicRelativeTo, er, createTimeZoneOps, toDurationSlots(e), toDurationSlots(t), n)
}), sr = {
  toString: e => e.id,
  toJSON: e => e.id,
  ...ro,
  dateAdd: ({id: e, o: t}, n, o, r) => Yo(v(t.dateAdd(toPlainDateSlots(n), toDurationSlots(o), r), e)),
  dateUntil: ({o: e}, t, n, o) => ar(Vt(e.dateUntil(toPlainDateSlots(t), toPlainDateSlots(n), _t(o)))),
  dateFromFields: ({id: e, o: t}, n, o) => Yo(Yt(t, n, o, ln(e))),
  yearMonthFromFields: ({id: e, o: t}, n, o) => jo(nt(t, n, o, un(e))),
  monthDayFromFields: ({id: e, o: t}, n, o) => To(K(t, 0, n, o, cn(e))),
  fields({o: e}, t) {
    const n = new Set(en), o = [];
    for (const e of t) {
      if (m(e), !n.has(e)) {
        throw new RangeError(tn(e));
      }
      n.delete(e), o.push(e);
    }
    return e.fields(o);
  },
  mergeFields: ({o: e}, t, n) => e.mergeFields(nn(on(t)), nn(on(n)))
}, [lr] = createSlotClass("Calendar", (e => {
  const t = rn(e);
  return {
    branding: "Calendar",
    id: t,
    o: Y(t)
  };
}), {
  id: e => e.id
}, sr, {
  from(e) {
    const t = refineCalendarSlot(e);
    return "string" == typeof t ? new lr(t) : t;
  }
}), cr = /*@__PURE__*/ createProtocolValidator(Object.keys(sr).slice(4)), [ur, dr] = createSlotClass(Te, E(vn, refineCalendarSlot, refineTimeZoneSlot), {
  ...mo,
  ...lo,
  ...adaptDateMethods(ao),
  ...adaptDateMethods(fo),
  offset: e => Fe(slotsToIso(e).offsetNanoseconds),
  offsetNanoseconds: e => slotsToIso(e).offsetNanoseconds,
  timeZoneId: e => I(e.timeZone),
  hoursInDay: e => dn(createTimeZoneOps, e)
}, {
  getISOFields: e => mn(createTimeZoneOffsetOps, e),
  getCalendar: createCalendarFromSlots,
  getTimeZone: ({timeZone: e}) => "string" == typeof e ? new Zo(e) : e,
  with(e, t, n) {
    return dr(Sn($o, createTimeZoneOps, e, this, rejectInvalidBag(t), n));
  },
  withCalendar: (e, t) => dr(it(e, refineCalendarSlot(t))),
  withTimeZone: (e, t) => dr(On(e, refineTimeZoneSlot(t))),
  withPlainDate: (e, t) => dr(Tn(createTimeZoneOps, e, toPlainDateSlots(t))),
  withPlainTime: (e, t) => dr(pn(createTimeZoneOps, e, optionalToPlainTimeFields(t))),
  add: (e, t, n) => dr(hn(er, createTimeZoneOps, 0, e, toDurationSlots(t), n)),
  subtract: (e, t, n) => dr(hn(er, createTimeZoneOps, 1, e, toDurationSlots(t), n)),
  until: (e, t, n) => ar(Vt(Dn(tr, createTimeZoneOps, 0, e, toZonedDateTimeSlots(t), n))),
  since: (e, t, n) => ar(Vt(Dn(tr, createTimeZoneOps, 1, e, toZonedDateTimeSlots(t), n))),
  round: (e, t) => dr(Pn(createTimeZoneOps, e, t)),
  startOfDay: e => dr(Cn(createTimeZoneOps, e)),
  equals: (e, t) => gn(e, toZonedDateTimeSlots(t)),
  toInstant: e => Co(Zn(e)),
  toPlainDateTime: e => No(ht(createTimeZoneOffsetOps, e)),
  toPlainDate: e => Yo(Bt(createTimeZoneOffsetOps, e)),
  toPlainTime: e => vo(Re(createTimeZoneOffsetOps, e)),
  toPlainYearMonth(e) {
    return jo(bn(Ho, e, this));
  },
  toPlainMonthDay(e) {
    return To(Fn(Qo, e, this));
  },
  toLocaleString(e, t, n = {}) {
    const [o, r] = Wn(t, n, e);
    return o.format(r);
  },
  toString: (e, t) => In(createTimeZoneOffsetOps, e, t),
  toJSON: e => In(createTimeZoneOffsetOps, e),
  valueOf: neverValueOf
}, {
  from: (e, t) => dr(toZonedDateTimeSlots(e, t)),
  compare: (e, t) => yn(toZonedDateTimeSlots(e), toZonedDateTimeSlots(t))
}), fr = /*@__PURE__*/ Object.defineProperties({}, {
  ...h("Temporal.Now"),
  ...p({
    timeZoneId: () => Nn(),
    instant: () => Co(_(Bn())),
    zonedDateTime: (e, t = Nn()) => dr(Yn(Bn(), refineTimeZoneSlot(t), refineCalendarSlot(e))),
    zonedDateTimeISO: (e = Nn()) => dr(Yn(Bn(), refineTimeZoneSlot(e), X)),
    plainDateTime: (e, t = Nn()) => No(ee(An(createTimeZoneOffsetOps(refineTimeZoneSlot(t))), refineCalendarSlot(e))),
    plainDateTimeISO: (e = Nn()) => No(ee(An(createTimeZoneOffsetOps(refineTimeZoneSlot(e))), X)),
    plainDate: (e, t = Nn()) => Yo(v(An(createTimeZoneOffsetOps(refineTimeZoneSlot(t))), refineCalendarSlot(e))),
    plainDateISO: (e = Nn()) => Yo(v(An(createTimeZoneOffsetOps(refineTimeZoneSlot(e))), X)),
    plainTimeISO: (e = Nn()) => vo(Ge(An(createTimeZoneOffsetOps(refineTimeZoneSlot(e)))))
  })
}), mr = /*@__PURE__*/ Object.defineProperties({}, {
  ...h("Temporal"),
  ...p({
    PlainYearMonth: wo,
    PlainMonthDay: Oo,
    PlainDate: Bo,
    PlainTime: Io,
    PlainDateTime: yo,
    ZonedDateTime: ur,
    Instant: Po,
    Calendar: lr,
    TimeZone: Zo,
    Duration: rr,
    Now: fr
  })
}), Sr = /*@__PURE__*/ createDateTimeFormatClass(), Or = /*@__PURE__*/ new WeakMap; /*@__PURE__*/ Object.defineProperties(Object.create(Intl), p({
  DateTimeFormat: Sr
}));

/**
 * Serialize the given TypeSpec value as a JSON object using the given type and its encoding annotations.
 * The Value MUST be assignable to the given type.
 */
function serializeValueAsJson(program, value, type, encodeAs) {
    if (type.kind === "ModelProperty") {
        return serializeValueAsJson(program, value, type.type, encodeAs ?? getEncode(program, type));
    }
    switch (value.valueKind) {
        case "NullValue":
            return null;
        case "BooleanValue":
        case "StringValue":
            return value.value;
        case "NumericValue":
            return value.value.asNumber();
        case "EnumValue":
            return value.value.value ?? value.value.name;
        case "ArrayValue":
            return value.values.map((v) => serializeValueAsJson(program, v, type));
        case "ObjectValue":
            return serializeObjectValueAsJson(program, value, type);
        case "ScalarValue":
            return serializeScalarValueAsJson(program, value, type, encodeAs);
    }
}
function serializeObjectValueAsJson(program, value, type) {
    const obj = {};
    for (const propValue of value.properties.values()) {
        const definition = type.properties.get(propValue.name);
        if (definition) {
            obj[propValue.name] = serializeValueAsJson(program, propValue.value, definition);
        }
    }
    return obj;
}
function resolveKnownScalar(program, scalar) {
    const encode = getEncode(program, scalar);
    if (program.checker.isStdType(scalar)) {
        switch (scalar.name) {
            case "utcDateTime":
            case "offsetDateTime":
            case "plainDate":
            case "plainTime":
            case "duration":
                return { scalar: scalar, encodeAs: encode };
            case "unixTimestamp32":
                break;
            default:
                return undefined;
        }
    }
    if (scalar.baseScalar) {
        const result = resolveKnownScalar(program, scalar.baseScalar);
        return result && { scalar: result.scalar, encodeAs: encode };
    }
    return undefined;
}
function serializeScalarValueAsJson(program, value, type, encodeAs) {
    const result = resolveKnownScalar(program, value.scalar);
    if (result === undefined) {
        return serializeValueAsJson(program, value.value.args[0], value.value.args[0].type);
    }
    encodeAs = encodeAs ?? result.encodeAs;
    switch (result.scalar.name) {
        case "utcDateTime":
            return ScalarSerializers.utcDateTime(value.value.args[0].value, encodeAs);
        case "offsetDateTime":
            return ScalarSerializers.offsetDateTime(value.value.args[0].value, encodeAs);
        case "plainDate":
            return ScalarSerializers.plainDate(value.value.args[0].value);
        case "plainTime":
            return ScalarSerializers.plainTime(value.value.args[0].value);
        case "duration":
            return ScalarSerializers.duration(value.value.args[0].value, encodeAs);
    }
}
const ScalarSerializers = {
    utcDateTime: (value, encodeAs) => {
        if (encodeAs === undefined || encodeAs.encoding === "rfc3339") {
            return value;
        }
        const date = new Date(value);
        switch (encodeAs.encoding) {
            case "unixTimestamp":
                return Math.floor(date.getTime() / 1000);
            case "rfc7231":
                return date.toUTCString();
            default:
                return date.toISOString();
        }
    },
    offsetDateTime: (value, encodeAs) => {
        if (encodeAs === undefined || encodeAs.encoding === "rfc3339") {
            return value;
        }
        const date = new Date(value);
        switch (encodeAs.encoding) {
            case "rfc7231":
                return date.toUTCString();
            default:
                return date.toISOString();
        }
    },
    plainDate: (value) => {
        return value;
    },
    plainTime: (value) => {
        return value;
    },
    duration: (value, encodeAs) => {
        const duration = mr.Duration.from(value);
        switch (encodeAs?.encoding) {
            case "seconds":
                if (isInteger(encodeAs.type)) {
                    return Math.floor(duration.total({ unit: "seconds" }));
                }
                else {
                    return duration.total({ unit: "seconds" });
                }
            default:
                return duration.toString();
        }
    },
};
function isInteger(scalar) {
    while (scalar.baseScalar) {
        scalar = scalar.baseScalar;
        if (scalar.name === "integer") {
            return true;
        }
    }
    return false;
}

const serviceDetailsKey = Symbol.for("@typespec/compiler.services");
function getServiceMap(program) {
    return program.stateMap(serviceDetailsKey);
}
/**
 * List all the services defined in the TypeSpec program
 * @param program Program
 * @returns List of service.
 */
function listServices(program) {
    return [...getServiceMap(program).values()];
}
/**
 * Get the service information for the given namespace.
 * @param program Program
 * @param namespace Service namespace
 * @returns Service information or undefined if namespace is not a service namespace.
 */
function getService(program, namespace) {
    return getServiceMap(program).get(namespace);
}
/**
 * Check if the namespace is defined as a service.
 * @param program Program
 * @param namespace Namespace
 * @returns Boolean
 */
function isService(program, namespace) {
    return getServiceMap(program).has(namespace);
}
/**
 * Mark the given namespace as a service.
 * @param program Program
 * @param namespace Namespace
 * @param details Service details
 */
function addService(program, namespace, details = {}) {
    const serviceMap = getServiceMap(program);
    const existing = serviceMap.get(namespace) ?? {};
    serviceMap.set(namespace, { ...existing, ...details, type: namespace });
}
const $service = (context, target, options) => {
    validateDecoratorUniqueOnNode(context, target, $service);
    if (options && options.kind !== "Model") {
        reportDiagnostic(context.program, {
            code: "invalid-argument",
            format: { value: options.kind, expected: "Model" },
            target: context.getArgumentTarget(0),
        });
        return;
    }
    const serviceDetails = {};
    const title = options?.properties.get("title")?.type;
    const versionProp = options?.properties.get("version");
    if (title) {
        if (title.kind === "String") {
            serviceDetails.title = title.value;
        }
        else {
            reportDiagnostic(context.program, {
                code: "unassignable",
                format: { value: getTypeName(title), targetType: "String" },
                target: context.getArgumentTarget(0),
            });
        }
    }
    if (versionProp) {
        const version = versionProp.type;
        reportDeprecated(context.program, "version: property is deprecated in @service. If wanting to describe a service versioning you can use the `@typespec/versioning` library. If wanting to describe the project version you can use the package.json version.", versionProp);
        if (version.kind === "String") {
            // eslint-disable-next-line deprecation/deprecation
            serviceDetails.version = version.value;
        }
        else {
            reportDiagnostic(context.program, {
                code: "unassignable",
                format: { value: getTypeName(version), targetType: "String" },
                target: context.getArgumentTarget(0),
            });
        }
    }
    addService(context.program, target, serviceDetails);
};

const namespace = "TypeSpec";
function replaceTemplatedStringFromProperties(formatString, sourceObject) {
    // Template parameters are not valid source objects, just skip them
    if (sourceObject.kind === "TemplateParameter") {
        return formatString;
    }
    return formatString.replace(/{(\w+)}/g, (_, propName) => {
        return sourceObject[propName];
    });
}
function createStateSymbol(name) {
    return Symbol.for(`TypeSpec.${name}`);
}
const summaryKey = createStateSymbol("summary");
/**
 * @summary attaches a documentation string. It is typically used to give a short, single-line
 * description, and can be used in combination with or instead of @doc.
 *
 * The first argument to @summary is a string, which may contain template parameters, enclosed in braces,
 * which are replaced with an attribute for the type (commonly "name") passed as the second (optional) argument.
 *
 * @summary can be specified on any language element -- a model, an operation, a namespace, etc.
 */
const $summary = (context, target, text, sourceObject) => {
    if (sourceObject) {
        text = replaceTemplatedStringFromProperties(text, sourceObject);
    }
    context.program.stateMap(summaryKey).set(target, text);
};
function getSummary(program, type) {
    return program.stateMap(summaryKey).get(type);
}
/**
 * @doc attaches a documentation string. Works great with multi-line string literals.
 *
 * The first argument to @doc is a string, which may contain template parameters, enclosed in braces,
 * which are replaced with an attribute for the type (commonly "name") passed as the second (optional) argument.
 *
 * @doc can be specified on any language element -- a model, an operation, a namespace, etc.
 */
const $doc = (context, target, text, sourceObject) => {
    validateDecoratorUniqueOnNode(context, target, $doc);
    if (sourceObject) {
        text = replaceTemplatedStringFromProperties(text, sourceObject);
    }
    setDocData(context.program, target, "self", { value: text, source: "decorator" });
};
/**
 * Get the documentation string for the given type.
 * @param program Program
 * @param target Type
 * @returns Documentation value
 */
function getDoc(program, target) {
    return getDocDataInternal(program, target, "self")?.value;
}
const $returnsDoc = (context, target, text) => {
    validateDecoratorUniqueOnNode(context, target, $doc);
    setDocData(context.program, target, "returns", { value: text, source: "decorator" });
};
/**
 * Get the documentation information for the return success types of an operation. In most cases you probably just want to use {@link getReturnsDoc}
 * @param program Program
 * @param target Type
 * @returns Doc data with source information.
 */
function getReturnsDocData(program, target) {
    return getDocDataInternal(program, target, "returns");
}
/**
 * Get the documentation string for the return success types of an operation.
 * @param program Program
 * @param target Type
 * @returns Documentation value
 */
function getReturnsDoc(program, target) {
    return getDocDataInternal(program, target, "returns")?.value;
}
const $errorsDoc = (context, target, text) => {
    validateDecoratorUniqueOnNode(context, target, $doc);
    setDocData(context.program, target, "errors", { value: text, source: "decorator" });
};
/**
 * Get the documentation information for the return errors types of an operation. In most cases you probably just want to use {@link getErrorsDoc}
 * @param program Program
 * @param target Type
 * @returns Doc data with source information.
 */
function getErrorsDocData(program, target) {
    return getDocDataInternal(program, target, "errors");
}
/**
 * Get the documentation string for the return errors types of an operation.
 * @param program Program
 * @param target Type
 * @returns Documentation value
 */
function getErrorsDoc(program, target) {
    return getDocDataInternal(program, target, "errors")?.value;
}
const $inspectType = (context, target, text) => {
    // eslint-disable-next-line no-console
    if (text)
        console.log(text);
    // eslint-disable-next-line no-console
    console.dir(target, { depth: 3 });
};
const $inspectTypeName = (context, target, text) => {
    // eslint-disable-next-line no-console
    if (text)
        console.log(text);
    // eslint-disable-next-line no-console
    console.log(getTypeName(target));
};
function isStringType(program, target) {
    const coreType = program.checker.getStdType("string");
    const stringType = target.projector ? target.projector.projectType(coreType) : coreType;
    return (target.kind === "Scalar" && program.checker.isTypeAssignableTo(target, stringType, target)[0]);
}
function isNumericType(program, target) {
    const coreType = program.checker.getStdType("numeric");
    const numericType = target.projector ? target.projector.projectType(coreType) : coreType;
    return (target.kind === "Scalar" && program.checker.isTypeAssignableTo(target, numericType, target)[0]);
}
/**
 * Check the given type is matching the given condition or is a union of null and types matching the condition.
 * @param type Type to test
 * @param condition Condition
 * @returns Boolean
 */
function isTypeIn(type, condition) {
    if (type.kind === "Union") {
        return [...type.variants.values()].some((v) => condition(v.type));
    }
    return condition(type);
}
function validateTargetingANumeric(context, target, decoratorName) {
    const valid = isTypeIn(getPropertyType(target), (x) => isNumericType(context.program, x));
    if (!valid) {
        reportDiagnostic(context.program, {
            code: "decorator-wrong-target",
            format: {
                decorator: decoratorName,
                to: `type it is not a numeric`,
            },
            target: context.decoratorTarget,
        });
    }
    return valid;
}
/**
 * Validate the given target is a string type or a union containing at least a string type.
 */
function validateTargetingAString(context, target, decoratorName) {
    const valid = isTypeIn(getPropertyType(target), (x) => isStringType(context.program, x));
    if (!valid) {
        reportDiagnostic(context.program, {
            code: "decorator-wrong-target",
            format: {
                decorator: decoratorName,
                to: `type it is not a string`,
            },
            target: context.decoratorTarget,
        });
    }
    return valid;
}
// -- @error decorator ----------------------
const errorKey = createStateSymbol("error");
/**
 * `@error` decorator marks a model as an error type.
 *  Any derived models (using extends) will also be seen as error types.
 */
const $error = (context, entity) => {
    validateDecoratorUniqueOnNode(context, entity, $error);
    context.program.stateSet(errorKey).add(entity);
};
/**
 * Check if the type is an error model or a descendant of an error model.
 */
function isErrorModel(program, target) {
    if (target.kind !== "Model") {
        return false;
    }
    let current = target;
    while (current) {
        if (program.stateSet(errorKey).has(current)) {
            return true;
        }
        current = current.baseModel;
    }
    return false;
}
// -- @format decorator ---------------------
const formatValuesKey = createStateSymbol("formatValues");
/**
 * `@format` - specify the data format hint for a string type
 *
 * The first argument is a string that identifies the format that the string type expects.  Any string
 * can be entered here, but a TypeSpec emitter must know how to interpret
 *
 * For TypeSpec specs that will be used with an OpenAPI emitter, the OpenAPI specification describes possible
 * valid values for a string type's format:
 *
 * https://github.com/OAI/OpenAPI-Specification/blob/3.0.3/versions/3.0.3.md#dataTypes
 *
 * `@format` can be specified on a type that extends from `string` or a `string`-typed model property.
 */
const $format = (context, target, format) => {
    validateDecoratorUniqueOnNode(context, target, $format);
    if (!validateTargetingAString(context, target, "@format")) {
        return;
    }
    const targetType = getPropertyType(target);
    if (targetType.kind === "Scalar" && isIntrinsicType(context.program, targetType, "bytes")) {
        reportDeprecated(context.program, "Using `@format` on a bytes scalar is deprecated. Use `@encode` instead. https://github.com/microsoft/typespec/issues/1873", target);
    }
    context.program.stateMap(formatValuesKey).set(target, format);
};
function getFormat(program, target) {
    return program.stateMap(formatValuesKey).get(target);
}
// -- @pattern decorator ---------------------
const patternValuesKey = createStateSymbol("patternValues");
const $pattern = (context, target, pattern, validationMessage) => {
    validateDecoratorUniqueOnNode(context, target, $pattern);
    if (!validateTargetingAString(context, target, "@pattern")) {
        return;
    }
    const patternData = {
        pattern,
        validationMessage,
    };
    context.program.stateMap(patternValuesKey).set(target, patternData);
};
/**
 * Gets the pattern regular expression associated with a given type, if one has been set.
 *
 * @see getPatternData
 *
 * @param program - the Program containing the target Type
 * @param target - the type to get the pattern for
 * @returns the pattern string, if one was set
 */
function getPattern(program, target) {
    return getPatternData(program, target)?.pattern;
}
/**
 * Gets the associated pattern data, including the pattern regular expression and optional validation message, if any
 * has been set.
 *
 * @param program - the Program containing the target Type
 * @param target - the type to get the pattern data for
 * @returns the pattern data, if any was set
 */
function getPatternData(program, target) {
    return program.stateMap(patternValuesKey).get(target);
}
// -- @minLength decorator ---------------------
const $minLength = (context, target, minLength) => {
    validateDecoratorUniqueOnNode(context, target, $minLength);
    if (!validateTargetingAString(context, target, "@minLength") ||
        !validateRange(context, minLength, getMaxLengthAsNumeric(context.program, target))) {
        return;
    }
    setMinLength(context.program, target, minLength);
};
// -- @maxLength decorator ---------------------
const $maxLength = (context, target, maxLength) => {
    validateDecoratorUniqueOnNode(context, target, $maxLength);
    if (!validateTargetingAString(context, target, "@maxLength") ||
        !validateRange(context, getMinLengthAsNumeric(context.program, target), maxLength)) {
        return;
    }
    setMaxLength(context.program, target, maxLength);
};
// -- @minItems decorator ---------------------
const $minItems = (context, target, minItems) => {
    validateDecoratorUniqueOnNode(context, target, $minItems);
    if (!isArrayModelType(context.program, target.kind === "Model" ? target : target.type)) {
        reportDiagnostic(context.program, {
            code: "decorator-wrong-target",
            format: {
                decorator: "@minItems",
                to: `non Array type`,
            },
            target: context.decoratorTarget,
        });
    }
    if (!validateRange(context, minItems, getMaxItemsAsNumeric(context.program, target))) {
        return;
    }
    setMinItems(context.program, target, minItems);
};
// -- @maxLength decorator ---------------------
const $maxItems = (context, target, maxItems) => {
    validateDecoratorUniqueOnNode(context, target, $maxItems);
    if (!isArrayModelType(context.program, target.kind === "Model" ? target : target.type)) {
        reportDiagnostic(context.program, {
            code: "decorator-wrong-target",
            format: {
                decorator: "@maxItems",
                to: `non Array type`,
            },
            target: context.decoratorTarget,
        });
    }
    if (!validateRange(context, getMinItemsAsNumeric(context.program, target), maxItems)) {
        return;
    }
    setMaxItems(context.program, target, maxItems);
};
// -- @minValue decorator ---------------------
const $minValue = (context, target, minValue) => {
    validateDecoratorUniqueOnNode(context, target, $minValue);
    validateDecoratorNotOnType(context, target, $minValueExclusive, $minValue);
    const { program } = context;
    if (!validateTargetingANumeric(context, target, "@minValue")) {
        return;
    }
    if (!validateRange(context, minValue, getMaxValueAsNumeric(context.program, target) ??
        getMaxValueExclusiveAsNumeric(context.program, target))) {
        return;
    }
    setMinValue(program, target, minValue);
};
// -- @maxValue decorator ---------------------
const $maxValue = (context, target, maxValue) => {
    validateDecoratorUniqueOnNode(context, target, $maxValue);
    validateDecoratorNotOnType(context, target, $maxValueExclusive, $maxValue);
    const { program } = context;
    if (!validateTargetingANumeric(context, target, "@maxValue")) {
        return;
    }
    if (!validateRange(context, getMinValueAsNumeric(context.program, target) ??
        getMinValueExclusiveAsNumeric(context.program, target), maxValue)) {
        return;
    }
    setMaxValue(program, target, maxValue);
};
// -- @minValueExclusive decorator ---------------------
const $minValueExclusive = (context, target, minValueExclusive) => {
    validateDecoratorUniqueOnNode(context, target, $minValueExclusive);
    validateDecoratorNotOnType(context, target, $minValue, $minValueExclusive);
    const { program } = context;
    if (!validateTargetingANumeric(context, target, "@minValueExclusive")) {
        return;
    }
    if (!validateRange(context, minValueExclusive, getMaxValueAsNumeric(context.program, target) ??
        getMaxValueExclusiveAsNumeric(context.program, target))) {
        return;
    }
    setMinValueExclusive(program, target, minValueExclusive);
};
// -- @maxValueExclusive decorator ---------------------
const $maxValueExclusive = (context, target, maxValueExclusive) => {
    validateDecoratorUniqueOnNode(context, target, $maxValueExclusive);
    validateDecoratorNotOnType(context, target, $maxValue, $maxValueExclusive);
    const { program } = context;
    if (!validateTargetingANumeric(context, target, "@maxValueExclusive")) {
        return;
    }
    if (!validateRange(context, getMinValueAsNumeric(context.program, target) ??
        getMinValueExclusiveAsNumeric(context.program, target), maxValueExclusive)) {
        return;
    }
    setMaxValueExclusive(program, target, maxValueExclusive);
};
// -- @secret decorator ---------------------
const secretTypesKey = createStateSymbol("secretTypes");
/**
 * Mark a string as a secret value that should be treated carefully to avoid exposure
 * @param context Decorator context
 * @param target Decorator target, either a string model or a property with type string.
 */
const $secret = (context, target) => {
    validateDecoratorUniqueOnNode(context, target, $secret);
    if (!validateTargetingAString(context, target, "@secret")) {
        return;
    }
    context.program.stateMap(secretTypesKey).set(target, true);
};
function isSecret(program, target) {
    return program.stateMap(secretTypesKey).get(target);
}
const encodeKey = createStateSymbol("encode");
const $encode = (context, target, encoding, encodeAs) => {
    validateDecoratorUniqueOnNode(context, target, $encode);
    const encodingStr = computeEncoding(encoding);
    if (encodingStr === undefined) {
        return;
    }
    const encodeData = {
        encoding: encodingStr,
        type: encodeAs ?? context.program.checker.getStdType("string"),
    };
    const targetType = getPropertyType(target);
    validateEncodeData(context, targetType, encodeData);
    context.program.stateMap(encodeKey).set(target, encodeData);
};
function computeEncoding(encoding) {
    if (typeof encoding === "string") {
        return encoding;
    }
    switch (encoding.kind) {
        case "String":
            return encoding.value;
        case "EnumMember":
            if (encoding.value && typeof encoding.value === "string") {
                return encoding.value;
            }
            else {
                return getTypeName(encoding);
            }
        default:
            return undefined;
    }
}
function validateEncodeData(context, target, encodeData) {
    function check(validTargets, validEncodeTypes) {
        const checker = context.program.checker;
        const isTargetValid = isTypeIn(target.projectionBase ?? target, (type) => validTargets.some((validTarget) => {
            return ignoreDiagnostics(checker.isTypeAssignableTo(type, checker.getStdType(validTarget), target));
        }));
        if (!isTargetValid) {
            reportDiagnostic(context.program, {
                code: "invalid-encode",
                messageId: "wrongType",
                format: {
                    encoding: encodeData.encoding,
                    type: getTypeName(target),
                    expected: validTargets.join(", "),
                },
                target: context.decoratorTarget,
            });
        }
        const isEncodingTypeValid = validEncodeTypes.some((validEncoding) => {
            return ignoreDiagnostics(checker.isTypeAssignableTo(encodeData.type.projectionBase ?? encodeData.type, checker.getStdType(validEncoding), target));
        });
        if (!isEncodingTypeValid) {
            const typeName = getTypeName(encodeData.type.projectionBase ?? encodeData.type);
            reportDiagnostic(context.program, {
                code: "invalid-encode",
                messageId: ["unixTimestamp", "seconds"].includes(encodeData.encoding)
                    ? "wrongNumericEncodingType"
                    : "wrongEncodingType",
                format: {
                    encoding: encodeData.encoding,
                    type: getTypeName(target),
                    expected: validEncodeTypes.join(", "),
                    actual: typeName,
                },
                target: context.decoratorTarget,
            });
        }
    }
    switch (encodeData.encoding) {
        case "rfc3339":
            return check(["utcDateTime", "offsetDateTime"], ["string"]);
        case "rfc7231":
            return check(["utcDateTime", "offsetDateTime"], ["string"]);
        case "unixTimestamp":
            return check(["utcDateTime"], ["integer"]);
        case "seconds":
            return check(["duration"], ["numeric"]);
        case "base64":
            return check(["bytes"], ["string"]);
        case "base64url":
            return check(["bytes"], ["string"]);
    }
}
function getEncode(program, target) {
    return program.stateMap(encodeKey).get(target);
}
// -- @visibility decorator ---------------------
const visibilitySettingsKey = createStateSymbol("visibilitySettings");
const $visibility = (context, target, ...visibilities) => {
    validateDecoratorUniqueOnNode(context, target, $visibility);
    context.program.stateMap(visibilitySettingsKey).set(target, visibilities);
};
function getVisibility(program, target) {
    return program.stateMap(visibilitySettingsKey).get(target);
}
function clearVisibilities(program, target) {
    program.stateMap(visibilitySettingsKey).delete(target);
}
const $withVisibility = (context, target, ...visibilities) => {
    filterModelPropertiesInPlace(target, (p) => isVisible(context.program, p, visibilities));
    [...target.properties.values()].forEach((p) => clearVisibilities(context.program, p));
};
function isVisible(program, property, visibilities) {
    const propertyVisibilities = getVisibility(program, property);
    return !propertyVisibilities || propertyVisibilities.some((v) => visibilities.includes(v));
}
function filterModelPropertiesInPlace(model, filter) {
    for (const [key, prop] of model.properties) {
        if (!filter(prop)) {
            model.properties.delete(key);
        }
    }
}
// -- @withOptionalProperties decorator ---------------------
const $withOptionalProperties = (context, target) => {
    // Make all properties of the target type optional
    target.properties.forEach((p) => (p.optional = true));
};
// -- @withUpdateableProperties decorator ----------------------
const $withUpdateableProperties = (context, target) => {
    if (!validateDecoratorTarget(context, target, "@withUpdateableProperties", "Model")) {
        return;
    }
    filterModelPropertiesInPlace(target, (p) => isVisible(context.program, p, ["update"]));
};
// -- @withoutOmittedProperties decorator ----------------------
const $withoutOmittedProperties = (context, target, omitProperties) => {
    // Get the property or properties to omit
    const omitNames = new Set();
    if (omitProperties.kind === "String") {
        omitNames.add(omitProperties.value);
    }
    else if (omitProperties.kind === "Union") {
        for (const variant of omitProperties.variants.values()) {
            if (variant.type.kind === "String") {
                omitNames.add(variant.type.value);
            }
        }
    }
    // Remove all properties to be omitted
    filterModelPropertiesInPlace(target, (prop) => !omitNames.has(prop.name));
};
// -- @withPickedProperties decorator ----------------------
const $withPickedProperties = (context, target, pickedProperties) => {
    // Get the property or properties to pick
    const pickedNames = new Set();
    if (pickedProperties.kind === "String") {
        pickedNames.add(pickedProperties.value);
    }
    else if (pickedProperties.kind === "Union") {
        for (const variant of pickedProperties.variants.values()) {
            if (variant.type.kind === "String") {
                pickedNames.add(variant.type.value);
            }
        }
    }
    // Remove all properties not picked
    filterModelPropertiesInPlace(target, (prop) => pickedNames.has(prop.name));
};
// -- @withoutDefaultValues decorator ----------------------
const $withoutDefaultValues = (context, target) => {
    // remove all read-only properties from the target type
    target.properties.forEach((p) => {
        // eslint-disable-next-line deprecation/deprecation
        delete p.default;
        delete p.defaultValue;
    });
};
// -- @list decorator ---------------------
const listPropertiesKey = createStateSymbol("listProperties");
/**
 * @deprecated Use the `listsResource` decorator in `@typespec/rest` instead.
 */
// eslint-disable-next-line deprecation/deprecation
const $list = (context, target, listedType) => {
    if (listedType && listedType.kind === "TemplateParameter") {
        // Silently return because this is probably being used in a templated interface
        return;
    }
    if (listedType && listedType.kind !== "Model") {
        reportDiagnostic(context.program, {
            code: "list-type-not-model",
            target: context.getArgumentTarget(0),
        });
        return;
    }
    context.program.stateMap(listPropertiesKey).set(target, listedType);
};
/**
 * @deprecated This function is unused and will be removed in a future release.
 */
function getListOperationType(program, target) {
    return program.stateMap(listPropertiesKey).get(target);
}
/**
 * @deprecated Use `isListOperation` in `@typespec/rest` instead.
 */
function isListOperation(program, target) {
    // The type stored for the operation
    return program.stateMap(listPropertiesKey).has(target);
}
// -- @tag decorator ---------------------
const tagPropertiesKey = createStateSymbol("tagProperties");
// Set a tag on an operation, interface, or namespace.  There can be multiple tags on an
// operation, interface, or namespace.
const $tag = (context, target, tag) => {
    const tags = context.program.stateMap(tagPropertiesKey).get(target);
    if (tags) {
        tags.push(tag);
    }
    else {
        context.program.stateMap(tagPropertiesKey).set(target, [tag]);
    }
};
// Return the tags set on an operation or namespace
function getTags(program, target) {
    return program.stateMap(tagPropertiesKey).get(target) || [];
}
// Merge the tags for a operation with the tags that are on the namespace or
// interface it resides within.
function getAllTags(program, target) {
    const tags = new Set();
    let current = target;
    while (current !== undefined) {
        for (const t of getTags(program, current)) {
            tags.add(t);
        }
        // Move up to the parent
        if (current.kind === "Operation") {
            current = current.interface ?? current.namespace;
        }
        else {
            // Type is a namespace or interface
            current = current.namespace;
        }
    }
    return tags.size > 0 ? Array.from(tags).reverse() : undefined;
}
// -- @friendlyName decorator ---------------------
const friendlyNamesKey = createStateSymbol("friendlyNames");
const $friendlyName = (context, target, friendlyName, sourceObject) => {
    // workaround for current lack of functionality in compiler
    // https://github.com/microsoft/typespec/issues/2717
    if (target.kind === "Model" || target.kind === "Operation") {
        if (context.decoratorTarget.kind === SyntaxKind.AugmentDecoratorStatement) {
            if (ignoreDiagnostics(context.program.checker.resolveTypeReference(context.decoratorTarget.targetType))?.node !== target.node) {
                return;
            }
        }
        if (context.decoratorTarget.kind === SyntaxKind.DecoratorExpression) {
            if (context.decoratorTarget.parent !== target.node) {
                return;
            }
        }
    }
    // If an object was passed in, use it to format the friendly name
    if (sourceObject) {
        friendlyName = replaceTemplatedStringFromProperties(friendlyName, sourceObject);
    }
    context.program.stateMap(friendlyNamesKey).set(target, friendlyName);
};
function getFriendlyName(program, target) {
    return program.stateMap(friendlyNamesKey).get(target);
}
const knownValuesKey = createStateSymbol("knownValues");
/**
 * `@knownValues` marks a string type with an enum that contains all known values
 *
 * The first parameter is a reference to an enum type that describes all possible values that the
 * type accepts.
 *
 * `@knownValues` can only be applied to model types that extend `string`.
 *
 * @param target Decorator target. Must be a string. (model Foo extends string)
 * @param knownValues Must be an enum.
 */
const $knownValues = (context, target, knownValues) => {
    const type = getPropertyType(target);
    if (!isStringType(context.program, type) && !isNumericType(context.program, type)) {
        context.program.reportDiagnostic(createDiagnostic({
            code: "decorator-wrong-target",
            format: { decorator: "@knownValues", to: "type, it is  not a string or numeric" },
            target,
        }));
        return;
    }
    for (const member of knownValues.members.values()) {
        const propertyType = getPropertyType(target);
        if (!isEnumMemberAssignableToType(context.program, propertyType, member)) {
            reportDiagnostic(context.program, {
                code: "known-values-invalid-enum",
                format: {
                    member: member.name,
                    type: getTypeName(propertyType),
                },
                target,
            });
            return;
        }
    }
    context.program.stateMap(knownValuesKey).set(target, knownValues);
};
function isEnumMemberAssignableToType(program, typeName, member) {
    const memberType = member.value !== undefined ? typeof member.value : "string";
    switch (memberType) {
        case "string":
            return isStringType(program, typeName);
        case "number":
            return isNumericType(program, typeName);
        default:
            return false;
    }
}
function getKnownValues(program, target) {
    return program.stateMap(knownValuesKey).get(target);
}
const keyKey = createStateSymbol("key");
/**
 * `@key` - mark a model property as the key to identify instances of that type
 *
 * The optional first argument accepts an alternate key name which may be used by emitters.
 * Otherwise, the name of the target property will be used.
 *
 * `@key` can only be applied to model properties.
 */
const $key = (context, entity, altName) => {
    // Ensure that the key property is not marked as optional
    if (entity.optional) {
        reportDiagnostic(context.program, {
            code: "no-optional-key",
            format: { propertyName: entity.name },
            target: entity,
        });
        return;
    }
    // Register the key property
    context.program.stateMap(keyKey).set(entity, altName || entity.name);
};
function isKey(program, property) {
    return program.stateMap(keyKey).has(property);
}
function getKeyName(program, property) {
    return program.stateMap(keyKey).get(property);
}
const $withDefaultKeyVisibility = (context, entity, visibility) => {
    const keyProperties = [];
    entity.properties.forEach((prop) => {
        // Keep track of any key property without a visibility
        if (isKey(context.program, prop) && !getVisibility(context.program, prop)) {
            keyProperties.push(prop);
        }
    });
    // For each key property without a visibility, clone it and add the specified
    // default visibility value
    keyProperties.forEach((keyProp) => {
        entity.properties.set(keyProp.name, context.program.checker.cloneType(keyProp, {
            decorators: [
                ...keyProp.decorators,
                {
                    decorator: $visibility,
                    args: [
                        { value: context.program.checker.createLiteralType(visibility), jsValue: visibility },
                    ],
                },
            ],
        }));
    });
};
/**
 * Mark a type as deprecated
 * @param context DecoratorContext
 * @param target Decorator target
 * @param message Deprecation target.
 *
 * @example
 * ``` @deprecated("Foo is deprecated, use Bar instead.")
 *     model Foo {}
 * ```
 */
// eslint-disable-next-line deprecation/deprecation
const $deprecated = (context, target, message) => {
    markDeprecated(context.program, target, { message });
};
/**
 * Return the deprecated message or undefined if not deprecated
 * @param program Program
 * @param type Type
 */
function getDeprecated(program, type) {
    return getDeprecationDetails(program, type)?.message;
}
const overloadedByKey = createStateSymbol("overloadedByKey");
const overloadsOperationKey = createStateSymbol("overloadsOperation");
/**
 * `@overload` - Indicate that the target overloads (specializes) the overloads type.
 * @param context DecoratorContext
 * @param target The specializing operation declaration
 * @param overloadBase The operation to be overloaded.
 */
const $overload = (context, target, overloadBase) => {
    // Ensure that the overloaded method arguments are a subtype of the original operation.
    const [paramValid, paramDiagnostics] = context.program.checker.isTypeAssignableTo(target.parameters.projectionBase ?? target.parameters, overloadBase.parameters.projectionBase ?? overloadBase.parameters, target);
    if (!paramValid)
        context.program.reportDiagnostics(paramDiagnostics);
    const [returnTypeValid, returnTypeDiagnostics] = context.program.checker.isTypeAssignableTo(target.returnType.projectionBase ?? target.returnType, overloadBase.returnType.projectionBase ?? overloadBase.returnType, target);
    if (!returnTypeValid)
        context.program.reportDiagnostics(returnTypeDiagnostics);
    if (!areOperationsInSameContainer(target, overloadBase)) {
        reportDiagnostic(context.program, {
            code: "overload-same-parent",
            target: context.decoratorTarget,
        });
    }
    // Save the information about the overloaded operation
    context.program.stateMap(overloadsOperationKey).set(target, overloadBase);
    const existingOverloads = getOverloads(context.program, overloadBase) || new Array();
    context.program.stateMap(overloadedByKey).set(overloadBase, existingOverloads.concat(target));
};
function areOperationsInSameContainer(op1, op2) {
    return op1.interface || op2.interface
        ? equalsWithoutProjection(op1.interface, op2.interface)
        : op1.namespace === op2.namespace;
}
// note: because the 'interface' property of Operation types is projected after the
// type is finalized, the target operation or overloadBase may reference an un-projected
// interface at the time of decorator execution during projections.  This normalizes
// the interfaces to their unprojected form before comparison.
function equalsWithoutProjection(interface1, interface2) {
    if (interface1 === undefined || interface2 === undefined)
        return false;
    return getBaseInterface(interface1) === getBaseInterface(interface2);
}
function getBaseInterface(int1) {
    return int1.projectionSource === undefined
        ? int1
        : getBaseInterface(int1.projectionSource);
}
/**
 * Get all operations that are marked as overloads of the given operation
 * @param program Program
 * @param operation Operation
 * @returns An array of operations that overload the given operation.
 */
function getOverloads(program, operation) {
    return program.stateMap(overloadedByKey).get(operation);
}
/**
 * If the given operation overloads another operation, return that operation.
 * @param program Program
 * @param operation The operation to check for an overload target.
 * @returns The operation this operation overloads, if any.
 */
function getOverloadedOperation(program, operation) {
    return program.stateMap(overloadsOperationKey).get(operation);
}
const projectedNameKey = createStateSymbol("projectedNameKey");
/**
 * `@projectedName` - Indicate that this entity should be renamed according to the given projection.
 * @param context DecoratorContext
 * @param target The that should have a different name.
 * @param projectionName Name of the projection (e.g. "toJson", "toCSharp")
 * @param projectedName Name of the type should have in the scope of the projection specified.
 */
const $projectedName = (context, target, projectionName, projectedName) => {
    let map = context.program.stateMap(projectedNameKey).get(target);
    if (map === undefined) {
        map = new Map();
        context.program.stateMap(projectedNameKey).set(target, map);
    }
    map.set(projectionName, projectedName);
};
/**
 * @param program Program
 * @param target Target
 * @returns Map of the projected names for the given entity.
 */
function getProjectedNames(program, target) {
    return program.stateMap(projectedNameKey).get(target);
}
/**
 * Get the projected name of the given entity for the given projection.
 * @param program Program
 * @param target Target
 * @returns Projected name for the given projection
 */
function getProjectedName(program, target, projectionName) {
    return getProjectedNames(program, target)?.get(projectionName);
}
/**
 * Get the projected name of the given entity for the given projection.
 * @param program Program
 * @param target Target
 * @returns Projected name for the given projection
 */
function hasProjectedName(program, target, projectionName) {
    return getProjectedNames(program, target)?.has(projectionName) ?? false;
}
function validateRange(context, min, max) {
    if (min === undefined || max === undefined) {
        return true;
    }
    if (min.gt(max)) {
        reportDiagnostic(context.program, {
            code: "invalid-range",
            format: { start: min.toString(), end: max.toString() },
            target: context.decoratorTarget,
        });
        return false;
    }
    return true;
}
const $discriminator = (context, entity, propertyName) => {
    const discriminator = { propertyName };
    if (entity.kind === "Union") {
        // we can validate discriminator up front for unions. Models are validated in the accessor as we might not have the reference to all derived types at this time.
        const [, diagnostics] = getDiscriminatedUnion(entity, discriminator);
        if (diagnostics.length > 0) {
            context.program.reportDiagnostics(diagnostics);
            return;
        }
    }
    setDiscriminator(context.program, entity, discriminator);
};
const parameterVisibilityKey = createStateSymbol("parameterVisibility");
const $parameterVisibility = (context, entity, ...visibilities) => {
    validateDecoratorUniqueOnNode(context, entity, $parameterVisibility);
    context.program.stateMap(parameterVisibilityKey).set(entity, visibilities);
};
/**
 * Returns the visibilities of the parameters of the given operation, if provided with `@parameterVisibility`.
 *
 * @see {@link $parameterVisibility}
 */
function getParameterVisibility(program, entity) {
    return program.stateMap(parameterVisibilityKey).get(entity);
}
const returnTypeVisibilityKey = createStateSymbol("returnTypeVisibility");
const $returnTypeVisibility = (context, entity, ...visibilities) => {
    validateDecoratorUniqueOnNode(context, entity, $returnTypeVisibility);
    context.program.stateMap(returnTypeVisibilityKey).set(entity, visibilities);
};
/**
 * Returns the visibilities of the return type of the given operation, if provided with `@returnTypeVisibility`.
 *
 * @see {@link $returnTypeVisibility}
 */
function getReturnTypeVisibility(program, entity) {
    return program.stateMap(returnTypeVisibilityKey).get(entity);
}
const exampleKey = createStateSymbol("examples");
const $example = (context, target, _example, options // TODO: change `options?: ExampleOptions` when tspd supports it
) => {
    const decorator = target.decorators.find((d) => d.decorator === $example && d.node === context.decoratorTarget);
    compilerAssert(decorator, `Couldn't find @example decorator`, context.decoratorTarget);
    const rawExample = decorator.args[0].value;
    // skip validation in projections
    if (target.projectionBase === undefined) {
        if (!checkExampleValid(context.program, rawExample, target.kind === "ModelProperty" ? target.type : target, context.getArgumentTarget(0))) {
            return;
        }
    }
    let list = context.program.stateMap(exampleKey).get(target);
    if (list === undefined) {
        list = [];
        context.program.stateMap(exampleKey).set(target, list);
    }
    list.push({ value: rawExample, ...options });
};
function getExamples(program, target) {
    return program.stateMap(exampleKey).get(target) ?? [];
}
const opExampleKey = createStateSymbol("opExamples");
const $opExample = (context, target, _example, options // TODO: change `options?: ExampleOptions` when tspd supports it
) => {
    const decorator = target.decorators.find((d) => d.decorator === $opExample && d.node === context.decoratorTarget);
    compilerAssert(decorator, `Couldn't find @opExample decorator`, context.decoratorTarget);
    const rawExampleConfig = decorator.args[0].value;
    const parameters = rawExampleConfig.properties.get("parameters")?.value;
    const returnType = rawExampleConfig.properties.get("returnType")?.value;
    // skip validation in projections
    if (target.projectionBase === undefined) {
        if (parameters &&
            !checkExampleValid(context.program, parameters, target.parameters, context.getArgumentTarget(0))) {
            return;
        }
        if (returnType &&
            !checkExampleValid(context.program, returnType, target.returnType, context.getArgumentTarget(0))) {
            return;
        }
    }
    let list = context.program.stateMap(opExampleKey).get(target);
    if (list === undefined) {
        list = [];
        context.program.stateMap(opExampleKey).set(target, list);
    }
    list.push({ parameters, returnType, ...options });
};
function checkExampleValid(program, value, target, diagnosticTarget) {
    const exactType = program.checker.getValueExactType(value);
    const [assignable, diagnostics] = program.checker.isTypeAssignableTo(exactType ?? value.type, target, diagnosticTarget);
    if (!assignable) {
        program.reportDiagnostics(diagnostics);
    }
    return assignable;
}
function getOpExamples(program, target) {
    return program.stateMap(opExampleKey).get(target) ?? [];
}

var f1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    $deprecated: $deprecated,
    $discriminator: $discriminator,
    $doc: $doc,
    $encode: $encode,
    $encodedName: $encodedName,
    $error: $error,
    $errorsDoc: $errorsDoc,
    $example: $example,
    $format: $format,
    $friendlyName: $friendlyName,
    $inspectType: $inspectType,
    $inspectTypeName: $inspectTypeName,
    $key: $key,
    $knownValues: $knownValues,
    $list: $list,
    $maxItems: $maxItems,
    $maxLength: $maxLength,
    $maxValue: $maxValue,
    $maxValueExclusive: $maxValueExclusive,
    $minItems: $minItems,
    $minLength: $minLength,
    $minValue: $minValue,
    $minValueExclusive: $minValueExclusive,
    $opExample: $opExample,
    $overload: $overload,
    $parameterVisibility: $parameterVisibility,
    $pattern: $pattern,
    $projectedName: $projectedName,
    $returnTypeVisibility: $returnTypeVisibility,
    $returnsDoc: $returnsDoc,
    $secret: $secret,
    $service: $service,
    $summary: $summary,
    $tag: $tag,
    $visibility: $visibility,
    $withDefaultKeyVisibility: $withDefaultKeyVisibility,
    $withOptionalProperties: $withOptionalProperties,
    $withPickedProperties: $withPickedProperties,
    $withUpdateableProperties: $withUpdateableProperties,
    $withVisibility: $withVisibility,
    $withoutDefaultValues: $withoutDefaultValues,
    $withoutOmittedProperties: $withoutOmittedProperties,
    addService: addService,
    getAllTags: getAllTags,
    getDeprecated: getDeprecated,
    getDoc: getDoc,
    getEncode: getEncode,
    getErrorsDoc: getErrorsDoc,
    getErrorsDocData: getErrorsDocData,
    getExamples: getExamples,
    getFormat: getFormat,
    getFriendlyName: getFriendlyName,
    getKeyName: getKeyName,
    getKnownValues: getKnownValues,
    getListOperationType: getListOperationType,
    getOpExamples: getOpExamples,
    getOverloadedOperation: getOverloadedOperation,
    getOverloads: getOverloads,
    getParameterVisibility: getParameterVisibility,
    getPattern: getPattern,
    getPatternData: getPatternData,
    getProjectedName: getProjectedName,
    getProjectedNames: getProjectedNames,
    getReturnTypeVisibility: getReturnTypeVisibility,
    getReturnsDoc: getReturnsDoc,
    getReturnsDocData: getReturnsDocData,
    getService: getService,
    getSummary: getSummary,
    getTags: getTags,
    getVisibility: getVisibility,
    hasProjectedName: hasProjectedName,
    isErrorModel: isErrorModel,
    isKey: isKey,
    isListOperation: isListOperation,
    isNumericType: isNumericType,
    isSecret: isSecret,
    isService: isService,
    isStringType: isStringType,
    isVisible: isVisible,
    listServices: listServices,
    namespace: namespace,
    resolveEncodedName: resolveEncodedName,
    serializeValueAsJson: serializeValueAsJson
});

/**
 * TypeSpec Language configuration. Format: https://code.visualstudio.com/api/language-extensions/language-configuration-guide
 * @hidden Typedoc causing issue with this
 */
const TypeSpecLanguageConfiguration = {
    comments: {
        lineComment: "//",
        blockComment: ["/*", "*/"],
    },
    brackets: [
        ["{", "}"],
        ["[", "]"],
        ["(", ")"],
    ],
    autoClosingPairs: [
        { open: "{", close: "}" },
        { open: "[", close: "]" },
        { open: "(", close: ")" },
        // NOTE: autoclose for double quotes may interfere with typing """
        { open: '"', close: '"' },
        { open: "/**", close: " */", notIn: ["string"] },
    ],
    surroundingPairs: [
        { open: "{", close: "}" },
        { open: "[", close: "]" },
        { open: "(", close: ")" },
        { open: '"', close: '"' },
    ],
    // From https://github.com/microsoft/vscode/blob/main/extensions/javascript/javascript-language-configuration.json
    indentationRules: {
        decreaseIndentPattern: {
            pattern: "^((?!.*?/\\*).*\\*/)?\\s*[\\}\\]].*$",
        },
        increaseIndentPattern: {
            pattern: "^((?!//).)*(\\{([^}\"'`/]*|(\\t|[ ])*//.*)|\\([^)\"'`/]*|\\[[^\\]\"'`/]*)$",
        },
        // e.g.  * ...| or */| or *-----*/|
        unIndentedLinePattern: {
            pattern: "^(\\t|[ ])*[ ]\\*[^/]*\\*/\\s*$|^(\\t|[ ])*[ ]\\*/\\s*$|^(\\t|[ ])*[ ]\\*([ ]([^\\*]|\\*(?!/))*)?$",
        },
    },
    onEnterRules: [
        {
            // e.g. /** | */
            beforeText: {
                pattern: "^\\s*/\\*\\*(?!/)([^\\*]|\\*(?!/))*$",
            },
            afterText: {
                pattern: "^\\s*\\*/$",
            },
            action: {
                indent: "indentOutdent",
                appendText: " * ",
            },
        },
        {
            // e.g. /** ...|
            beforeText: {
                pattern: "^\\s*/\\*\\*(?!/)([^\\*]|\\*(?!/))*$",
            },
            action: {
                indent: "none",
                appendText: " * ",
            },
        },
        {
            // e.g.  * ...|
            beforeText: {
                pattern: "^(\\t|[ ])*[ ]\\*([ ]([^\\*]|\\*(?!/))*)?$",
            },
            previousLineText: {
                pattern: "(?=^(\\s*(/\\*\\*|\\*)).*)(?=(?!(\\s*\\*/)))",
            },
            action: {
                indent: "none",
                appendText: "* ",
            },
        },
        {
            // e.g.  */|
            beforeText: {
                pattern: "^(\\t|[ ])*[ ]\\*/\\s*$",
            },
            action: {
                indent: "none",
                removeText: 1,
            },
        },
        {
            // e.g.  *-----*/|
            beforeText: {
                pattern: "^(\\t|[ ])*[ ]\\*[^/]*\\*/\\s*$",
            },
            action: {
                indent: "none",
                removeText: 1,
            },
        },
    ],
};
/**
 * @deprecated Use TypeSpecLanguageConfiguration
 * @hidden
 */
const CadlLanguageConfiguration = TypeSpecLanguageConfiguration;

var main$3 = {};

var api$2 = {};

var semanticTokens = {};

var main$2 = {};

var main$1 = {};

var ril = {};

var api$1 = {};

var messages$1 = {};

var is$2 = {};

var hasRequiredIs;

function requireIs () {
	if (hasRequiredIs) return is$2;
	hasRequiredIs = 1;
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(is$2, "__esModule", { value: true });
	is$2.stringArray = is$2.array = is$2.func = is$2.error = is$2.number = is$2.string = is$2.boolean = void 0;
	function boolean(value) {
	    return value === true || value === false;
	}
	is$2.boolean = boolean;
	function string(value) {
	    return typeof value === 'string' || value instanceof String;
	}
	is$2.string = string;
	function number(value) {
	    return typeof value === 'number' || value instanceof Number;
	}
	is$2.number = number;
	function error(value) {
	    return value instanceof Error;
	}
	is$2.error = error;
	function func(value) {
	    return typeof value === 'function';
	}
	is$2.func = func;
	function array(value) {
	    return Array.isArray(value);
	}
	is$2.array = array;
	function stringArray(value) {
	    return array(value) && value.every(elem => string(elem));
	}
	is$2.stringArray = stringArray;
	return is$2;
}

var hasRequiredMessages;

function requireMessages () {
	if (hasRequiredMessages) return messages$1;
	hasRequiredMessages = 1;
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(messages$1, "__esModule", { value: true });
	messages$1.Message = messages$1.NotificationType9 = messages$1.NotificationType8 = messages$1.NotificationType7 = messages$1.NotificationType6 = messages$1.NotificationType5 = messages$1.NotificationType4 = messages$1.NotificationType3 = messages$1.NotificationType2 = messages$1.NotificationType1 = messages$1.NotificationType0 = messages$1.NotificationType = messages$1.RequestType9 = messages$1.RequestType8 = messages$1.RequestType7 = messages$1.RequestType6 = messages$1.RequestType5 = messages$1.RequestType4 = messages$1.RequestType3 = messages$1.RequestType2 = messages$1.RequestType1 = messages$1.RequestType = messages$1.RequestType0 = messages$1.AbstractMessageSignature = messages$1.ParameterStructures = messages$1.ResponseError = messages$1.ErrorCodes = void 0;
	const is = requireIs();
	/**
	 * Predefined error codes.
	 */
	var ErrorCodes;
	(function (ErrorCodes) {
	    // Defined by JSON RPC
	    ErrorCodes.ParseError = -32700;
	    ErrorCodes.InvalidRequest = -32600;
	    ErrorCodes.MethodNotFound = -32601;
	    ErrorCodes.InvalidParams = -32602;
	    ErrorCodes.InternalError = -32603;
	    /**
	     * This is the start range of JSON RPC reserved error codes.
	     * It doesn't denote a real error code. No application error codes should
	     * be defined between the start and end range. For backwards
	     * compatibility the `ServerNotInitialized` and the `UnknownErrorCode`
	     * are left in the range.
	     *
	     * @since 3.16.0
	    */
	    ErrorCodes.jsonrpcReservedErrorRangeStart = -32099;
	    /** @deprecated use  jsonrpcReservedErrorRangeStart */
	    ErrorCodes.serverErrorStart = -32099;
	    /**
	     * An error occurred when write a message to the transport layer.
	     */
	    ErrorCodes.MessageWriteError = -32099;
	    /**
	     * An error occurred when reading a message from the transport layer.
	     */
	    ErrorCodes.MessageReadError = -32098;
	    /**
	     * The connection got disposed or lost and all pending responses got
	     * rejected.
	     */
	    ErrorCodes.PendingResponseRejected = -32097;
	    /**
	     * The connection is inactive and a use of it failed.
	     */
	    ErrorCodes.ConnectionInactive = -32096;
	    /**
	     * Error code indicating that a server received a notification or
	     * request before the server has received the `initialize` request.
	     */
	    ErrorCodes.ServerNotInitialized = -32002;
	    ErrorCodes.UnknownErrorCode = -32001;
	    /**
	     * This is the end range of JSON RPC reserved error codes.
	     * It doesn't denote a real error code.
	     *
	     * @since 3.16.0
	    */
	    ErrorCodes.jsonrpcReservedErrorRangeEnd = -32000;
	    /** @deprecated use  jsonrpcReservedErrorRangeEnd */
	    ErrorCodes.serverErrorEnd = -32000;
	})(ErrorCodes || (messages$1.ErrorCodes = ErrorCodes = {}));
	/**
	 * An error object return in a response in case a request
	 * has failed.
	 */
	class ResponseError extends Error {
	    constructor(code, message, data) {
	        super(message);
	        this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
	        this.data = data;
	        Object.setPrototypeOf(this, ResponseError.prototype);
	    }
	    toJson() {
	        const result = {
	            code: this.code,
	            message: this.message
	        };
	        if (this.data !== undefined) {
	            result.data = this.data;
	        }
	        return result;
	    }
	}
	messages$1.ResponseError = ResponseError;
	class ParameterStructures {
	    constructor(kind) {
	        this.kind = kind;
	    }
	    static is(value) {
	        return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;
	    }
	    toString() {
	        return this.kind;
	    }
	}
	messages$1.ParameterStructures = ParameterStructures;
	/**
	 * The parameter structure is automatically inferred on the number of parameters
	 * and the parameter type in case of a single param.
	 */
	ParameterStructures.auto = new ParameterStructures('auto');
	/**
	 * Forces `byPosition` parameter structure. This is useful if you have a single
	 * parameter which has a literal type.
	 */
	ParameterStructures.byPosition = new ParameterStructures('byPosition');
	/**
	 * Forces `byName` parameter structure. This is only useful when having a single
	 * parameter. The library will report errors if used with a different number of
	 * parameters.
	 */
	ParameterStructures.byName = new ParameterStructures('byName');
	/**
	 * An abstract implementation of a MessageType.
	 */
	class AbstractMessageSignature {
	    constructor(method, numberOfParams) {
	        this.method = method;
	        this.numberOfParams = numberOfParams;
	    }
	    get parameterStructures() {
	        return ParameterStructures.auto;
	    }
	}
	messages$1.AbstractMessageSignature = AbstractMessageSignature;
	/**
	 * Classes to type request response pairs
	 */
	class RequestType0 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 0);
	    }
	}
	messages$1.RequestType0 = RequestType0;
	class RequestType extends AbstractMessageSignature {
	    constructor(method, _parameterStructures = ParameterStructures.auto) {
	        super(method, 1);
	        this._parameterStructures = _parameterStructures;
	    }
	    get parameterStructures() {
	        return this._parameterStructures;
	    }
	}
	messages$1.RequestType = RequestType;
	class RequestType1 extends AbstractMessageSignature {
	    constructor(method, _parameterStructures = ParameterStructures.auto) {
	        super(method, 1);
	        this._parameterStructures = _parameterStructures;
	    }
	    get parameterStructures() {
	        return this._parameterStructures;
	    }
	}
	messages$1.RequestType1 = RequestType1;
	class RequestType2 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 2);
	    }
	}
	messages$1.RequestType2 = RequestType2;
	class RequestType3 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 3);
	    }
	}
	messages$1.RequestType3 = RequestType3;
	class RequestType4 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 4);
	    }
	}
	messages$1.RequestType4 = RequestType4;
	class RequestType5 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 5);
	    }
	}
	messages$1.RequestType5 = RequestType5;
	class RequestType6 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 6);
	    }
	}
	messages$1.RequestType6 = RequestType6;
	class RequestType7 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 7);
	    }
	}
	messages$1.RequestType7 = RequestType7;
	class RequestType8 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 8);
	    }
	}
	messages$1.RequestType8 = RequestType8;
	class RequestType9 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 9);
	    }
	}
	messages$1.RequestType9 = RequestType9;
	class NotificationType extends AbstractMessageSignature {
	    constructor(method, _parameterStructures = ParameterStructures.auto) {
	        super(method, 1);
	        this._parameterStructures = _parameterStructures;
	    }
	    get parameterStructures() {
	        return this._parameterStructures;
	    }
	}
	messages$1.NotificationType = NotificationType;
	class NotificationType0 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 0);
	    }
	}
	messages$1.NotificationType0 = NotificationType0;
	class NotificationType1 extends AbstractMessageSignature {
	    constructor(method, _parameterStructures = ParameterStructures.auto) {
	        super(method, 1);
	        this._parameterStructures = _parameterStructures;
	    }
	    get parameterStructures() {
	        return this._parameterStructures;
	    }
	}
	messages$1.NotificationType1 = NotificationType1;
	class NotificationType2 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 2);
	    }
	}
	messages$1.NotificationType2 = NotificationType2;
	class NotificationType3 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 3);
	    }
	}
	messages$1.NotificationType3 = NotificationType3;
	class NotificationType4 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 4);
	    }
	}
	messages$1.NotificationType4 = NotificationType4;
	class NotificationType5 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 5);
	    }
	}
	messages$1.NotificationType5 = NotificationType5;
	class NotificationType6 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 6);
	    }
	}
	messages$1.NotificationType6 = NotificationType6;
	class NotificationType7 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 7);
	    }
	}
	messages$1.NotificationType7 = NotificationType7;
	class NotificationType8 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 8);
	    }
	}
	messages$1.NotificationType8 = NotificationType8;
	class NotificationType9 extends AbstractMessageSignature {
	    constructor(method) {
	        super(method, 9);
	    }
	}
	messages$1.NotificationType9 = NotificationType9;
	var Message;
	(function (Message) {
	    /**
	     * Tests if the given message is a request message
	     */
	    function isRequest(message) {
	        const candidate = message;
	        return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
	    }
	    Message.isRequest = isRequest;
	    /**
	     * Tests if the given message is a notification message
	     */
	    function isNotification(message) {
	        const candidate = message;
	        return candidate && is.string(candidate.method) && message.id === void 0;
	    }
	    Message.isNotification = isNotification;
	    /**
	     * Tests if the given message is a response message
	     */
	    function isResponse(message) {
	        const candidate = message;
	        return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
	    }
	    Message.isResponse = isResponse;
	})(Message || (messages$1.Message = Message = {}));
	return messages$1;
}

var linkedMap = {};

var hasRequiredLinkedMap;

function requireLinkedMap () {
	if (hasRequiredLinkedMap) return linkedMap;
	hasRequiredLinkedMap = 1;
	/*---------------------------------------------------------------------------------------------
	 *  Copyright (c) Microsoft Corporation. All rights reserved.
	 *  Licensed under the MIT License. See License.txt in the project root for license information.
	 *--------------------------------------------------------------------------------------------*/
	var _a;
	Object.defineProperty(linkedMap, "__esModule", { value: true });
	linkedMap.LRUCache = linkedMap.LinkedMap = linkedMap.Touch = void 0;
	var Touch;
	(function (Touch) {
	    Touch.None = 0;
	    Touch.First = 1;
	    Touch.AsOld = Touch.First;
	    Touch.Last = 2;
	    Touch.AsNew = Touch.Last;
	})(Touch || (linkedMap.Touch = Touch = {}));
	class LinkedMap {
	    constructor() {
	        this[_a] = 'LinkedMap';
	        this._map = new Map();
	        this._head = undefined;
	        this._tail = undefined;
	        this._size = 0;
	        this._state = 0;
	    }
	    clear() {
	        this._map.clear();
	        this._head = undefined;
	        this._tail = undefined;
	        this._size = 0;
	        this._state++;
	    }
	    isEmpty() {
	        return !this._head && !this._tail;
	    }
	    get size() {
	        return this._size;
	    }
	    get first() {
	        return this._head?.value;
	    }
	    get last() {
	        return this._tail?.value;
	    }
	    has(key) {
	        return this._map.has(key);
	    }
	    get(key, touch = Touch.None) {
	        const item = this._map.get(key);
	        if (!item) {
	            return undefined;
	        }
	        if (touch !== Touch.None) {
	            this.touch(item, touch);
	        }
	        return item.value;
	    }
	    set(key, value, touch = Touch.None) {
	        let item = this._map.get(key);
	        if (item) {
	            item.value = value;
	            if (touch !== Touch.None) {
	                this.touch(item, touch);
	            }
	        }
	        else {
	            item = { key, value, next: undefined, previous: undefined };
	            switch (touch) {
	                case Touch.None:
	                    this.addItemLast(item);
	                    break;
	                case Touch.First:
	                    this.addItemFirst(item);
	                    break;
	                case Touch.Last:
	                    this.addItemLast(item);
	                    break;
	                default:
	                    this.addItemLast(item);
	                    break;
	            }
	            this._map.set(key, item);
	            this._size++;
	        }
	        return this;
	    }
	    delete(key) {
	        return !!this.remove(key);
	    }
	    remove(key) {
	        const item = this._map.get(key);
	        if (!item) {
	            return undefined;
	        }
	        this._map.delete(key);
	        this.removeItem(item);
	        this._size--;
	        return item.value;
	    }
	    shift() {
	        if (!this._head && !this._tail) {
	            return undefined;
	        }
	        if (!this._head || !this._tail) {
	            throw new Error('Invalid list');
	        }
	        const item = this._head;
	        this._map.delete(item.key);
	        this.removeItem(item);
	        this._size--;
	        return item.value;
	    }
	    forEach(callbackfn, thisArg) {
	        const state = this._state;
	        let current = this._head;
	        while (current) {
	            if (thisArg) {
	                callbackfn.bind(thisArg)(current.value, current.key, this);
	            }
	            else {
	                callbackfn(current.value, current.key, this);
	            }
	            if (this._state !== state) {
	                throw new Error(`LinkedMap got modified during iteration.`);
	            }
	            current = current.next;
	        }
	    }
	    keys() {
	        const state = this._state;
	        let current = this._head;
	        const iterator = {
	            [Symbol.iterator]: () => {
	                return iterator;
	            },
	            next: () => {
	                if (this._state !== state) {
	                    throw new Error(`LinkedMap got modified during iteration.`);
	                }
	                if (current) {
	                    const result = { value: current.key, done: false };
	                    current = current.next;
	                    return result;
	                }
	                else {
	                    return { value: undefined, done: true };
	                }
	            }
	        };
	        return iterator;
	    }
	    values() {
	        const state = this._state;
	        let current = this._head;
	        const iterator = {
	            [Symbol.iterator]: () => {
	                return iterator;
	            },
	            next: () => {
	                if (this._state !== state) {
	                    throw new Error(`LinkedMap got modified during iteration.`);
	                }
	                if (current) {
	                    const result = { value: current.value, done: false };
	                    current = current.next;
	                    return result;
	                }
	                else {
	                    return { value: undefined, done: true };
	                }
	            }
	        };
	        return iterator;
	    }
	    entries() {
	        const state = this._state;
	        let current = this._head;
	        const iterator = {
	            [Symbol.iterator]: () => {
	                return iterator;
	            },
	            next: () => {
	                if (this._state !== state) {
	                    throw new Error(`LinkedMap got modified during iteration.`);
	                }
	                if (current) {
	                    const result = { value: [current.key, current.value], done: false };
	                    current = current.next;
	                    return result;
	                }
	                else {
	                    return { value: undefined, done: true };
	                }
	            }
	        };
	        return iterator;
	    }
	    [(_a = Symbol.toStringTag, Symbol.iterator)]() {
	        return this.entries();
	    }
	    trimOld(newSize) {
	        if (newSize >= this.size) {
	            return;
	        }
	        if (newSize === 0) {
	            this.clear();
	            return;
	        }
	        let current = this._head;
	        let currentSize = this.size;
	        while (current && currentSize > newSize) {
	            this._map.delete(current.key);
	            current = current.next;
	            currentSize--;
	        }
	        this._head = current;
	        this._size = currentSize;
	        if (current) {
	            current.previous = undefined;
	        }
	        this._state++;
	    }
	    addItemFirst(item) {
	        // First time Insert
	        if (!this._head && !this._tail) {
	            this._tail = item;
	        }
	        else if (!this._head) {
	            throw new Error('Invalid list');
	        }
	        else {
	            item.next = this._head;
	            this._head.previous = item;
	        }
	        this._head = item;
	        this._state++;
	    }
	    addItemLast(item) {
	        // First time Insert
	        if (!this._head && !this._tail) {
	            this._head = item;
	        }
	        else if (!this._tail) {
	            throw new Error('Invalid list');
	        }
	        else {
	            item.previous = this._tail;
	            this._tail.next = item;
	        }
	        this._tail = item;
	        this._state++;
	    }
	    removeItem(item) {
	        if (item === this._head && item === this._tail) {
	            this._head = undefined;
	            this._tail = undefined;
	        }
	        else if (item === this._head) {
	            // This can only happened if size === 1 which is handle
	            // by the case above.
	            if (!item.next) {
	                throw new Error('Invalid list');
	            }
	            item.next.previous = undefined;
	            this._head = item.next;
	        }
	        else if (item === this._tail) {
	            // This can only happened if size === 1 which is handle
	            // by the case above.
	            if (!item.previous) {
	                throw new Error('Invalid list');
	            }
	            item.previous.next = undefined;
	            this._tail = item.previous;
	        }
	        else {
	            const next = item.next;
	            const previous = item.previous;
	            if (!next || !previous) {
	                throw new Error('Invalid list');
	            }
	            next.previous = previous;
	            previous.next = next;
	        }
	        item.next = undefined;
	        item.previous = undefined;
	        this._state++;
	    }
	    touch(item, touch) {
	        if (!this._head || !this._tail) {
	            throw new Error('Invalid list');
	        }
	        if ((touch !== Touch.First && touch !== Touch.Last)) {
	            return;
	        }
	        if (touch === Touch.First) {
	            if (item === this._head) {
	                return;
	            }
	            const next = item.next;
	            const previous = item.previous;
	            // Unlink the item
	            if (item === this._tail) {
	                // previous must be defined since item was not head but is tail
	                // So there are more than on item in the map
	                previous.next = undefined;
	                this._tail = previous;
	            }
	            else {
	                // Both next and previous are not undefined since item was neither head nor tail.
	                next.previous = previous;
	                previous.next = next;
	            }
	            // Insert the node at head
	            item.previous = undefined;
	            item.next = this._head;
	            this._head.previous = item;
	            this._head = item;
	            this._state++;
	        }
	        else if (touch === Touch.Last) {
	            if (item === this._tail) {
	                return;
	            }
	            const next = item.next;
	            const previous = item.previous;
	            // Unlink the item.
	            if (item === this._head) {
	                // next must be defined since item was not tail but is head
	                // So there are more than on item in the map
	                next.previous = undefined;
	                this._head = next;
	            }
	            else {
	                // Both next and previous are not undefined since item was neither head nor tail.
	                next.previous = previous;
	                previous.next = next;
	            }
	            item.next = undefined;
	            item.previous = this._tail;
	            this._tail.next = item;
	            this._tail = item;
	            this._state++;
	        }
	    }
	    toJSON() {
	        const data = [];
	        this.forEach((value, key) => {
	            data.push([key, value]);
	        });
	        return data;
	    }
	    fromJSON(data) {
	        this.clear();
	        for (const [key, value] of data) {
	            this.set(key, value);
	        }
	    }
	}
	linkedMap.LinkedMap = LinkedMap;
	class LRUCache extends LinkedMap {
	    constructor(limit, ratio = 1) {
	        super();
	        this._limit = limit;
	        this._ratio = Math.min(Math.max(0, ratio), 1);
	    }
	    get limit() {
	        return this._limit;
	    }
	    set limit(limit) {
	        this._limit = limit;
	        this.checkTrim();
	    }
	    get ratio() {
	        return this._ratio;
	    }
	    set ratio(ratio) {
	        this._ratio = Math.min(Math.max(0, ratio), 1);
	        this.checkTrim();
	    }
	    get(key, touch = Touch.AsNew) {
	        return super.get(key, touch);
	    }
	    peek(key) {
	        return super.get(key, Touch.None);
	    }
	    set(key, value) {
	        super.set(key, value, Touch.Last);
	        this.checkTrim();
	        return this;
	    }
	    checkTrim() {
	        if (this.size > this._limit) {
	            this.trimOld(Math.round(this._limit * this._ratio));
	        }
	    }
	}
	linkedMap.LRUCache = LRUCache;
	return linkedMap;
}

var disposable = {};

var hasRequiredDisposable;

function requireDisposable () {
	if (hasRequiredDisposable) return disposable;
	hasRequiredDisposable = 1;
	/*---------------------------------------------------------------------------------------------
	 *  Copyright (c) Microsoft Corporation. All rights reserved.
	 *  Licensed under the MIT License. See License.txt in the project root for license information.
	 *--------------------------------------------------------------------------------------------*/
	Object.defineProperty(disposable, "__esModule", { value: true });
	disposable.Disposable = void 0;
	var Disposable;
	(function (Disposable) {
	    function create(func) {
	        return {
	            dispose: func
	        };
	    }
	    Disposable.create = create;
	})(Disposable || (disposable.Disposable = Disposable = {}));
	return disposable;
}

var events = {};

var ral = {};

var hasRequiredRal;

function requireRal () {
	if (hasRequiredRal) return ral;
	hasRequiredRal = 1;
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(ral, "__esModule", { value: true });
	let _ral;
	function RAL() {
	    if (_ral === undefined) {
	        throw new Error(`No runtime abstraction layer installed`);
	    }
	    return _ral;
	}
	(function (RAL) {
	    function install(ral) {
	        if (ral === undefined) {
	            throw new Error(`No runtime abstraction layer provided`);
	        }
	        _ral = ral;
	    }
	    RAL.install = install;
	})(RAL || (RAL = {}));
	ral.default = RAL;
	return ral;
}

var hasRequiredEvents;

function requireEvents () {
	if (hasRequiredEvents) return events;
	hasRequiredEvents = 1;
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(events, "__esModule", { value: true });
	events.Emitter = events.Event = void 0;
	const ral_1 = requireRal();
	var Event;
	(function (Event) {
	    const _disposable = { dispose() { } };
	    Event.None = function () { return _disposable; };
	})(Event || (events.Event = Event = {}));
	class CallbackList {
	    add(callback, context = null, bucket) {
	        if (!this._callbacks) {
	            this._callbacks = [];
	            this._contexts = [];
	        }
	        this._callbacks.push(callback);
	        this._contexts.push(context);
	        if (Array.isArray(bucket)) {
	            bucket.push({ dispose: () => this.remove(callback, context) });
	        }
	    }
	    remove(callback, context = null) {
	        if (!this._callbacks) {
	            return;
	        }
	        let foundCallbackWithDifferentContext = false;
	        for (let i = 0, len = this._callbacks.length; i < len; i++) {
	            if (this._callbacks[i] === callback) {
	                if (this._contexts[i] === context) {
	                    // callback & context match => remove it
	                    this._callbacks.splice(i, 1);
	                    this._contexts.splice(i, 1);
	                    return;
	                }
	                else {
	                    foundCallbackWithDifferentContext = true;
	                }
	            }
	        }
	        if (foundCallbackWithDifferentContext) {
	            throw new Error('When adding a listener with a context, you should remove it with the same context');
	        }
	    }
	    invoke(...args) {
	        if (!this._callbacks) {
	            return [];
	        }
	        const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
	        for (let i = 0, len = callbacks.length; i < len; i++) {
	            try {
	                ret.push(callbacks[i].apply(contexts[i], args));
	            }
	            catch (e) {
	                // eslint-disable-next-line no-console
	                (0, ral_1.default)().console.error(e);
	            }
	        }
	        return ret;
	    }
	    isEmpty() {
	        return !this._callbacks || this._callbacks.length === 0;
	    }
	    dispose() {
	        this._callbacks = undefined;
	        this._contexts = undefined;
	    }
	}
	class Emitter {
	    constructor(_options) {
	        this._options = _options;
	    }
	    /**
	     * For the public to allow to subscribe
	     * to events from this Emitter
	     */
	    get event() {
	        if (!this._event) {
	            this._event = (listener, thisArgs, disposables) => {
	                if (!this._callbacks) {
	                    this._callbacks = new CallbackList();
	                }
	                if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
	                    this._options.onFirstListenerAdd(this);
	                }
	                this._callbacks.add(listener, thisArgs);
	                const result = {
	                    dispose: () => {
	                        if (!this._callbacks) {
	                            // disposable is disposed after emitter is disposed.
	                            return;
	                        }
	                        this._callbacks.remove(listener, thisArgs);
	                        result.dispose = Emitter._noop;
	                        if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
	                            this._options.onLastListenerRemove(this);
	                        }
	                    }
	                };
	                if (Array.isArray(disposables)) {
	                    disposables.push(result);
	                }
	                return result;
	            };
	        }
	        return this._event;
	    }
	    /**
	     * To be kept private to fire an event to
	     * subscribers
	     */
	    fire(event) {
	        if (this._callbacks) {
	            this._callbacks.invoke.call(this._callbacks, event);
	        }
	    }
	    dispose() {
	        if (this._callbacks) {
	            this._callbacks.dispose();
	            this._callbacks = undefined;
	        }
	    }
	}
	events.Emitter = Emitter;
	Emitter._noop = function () { };
	return events;
}

var cancellation = {};

var hasRequiredCancellation;

function requireCancellation () {
	if (hasRequiredCancellation) return cancellation;
	hasRequiredCancellation = 1;
	/*---------------------------------------------------------------------------------------------
	 *  Copyright (c) Microsoft Corporation. All rights reserved.
	 *  Licensed under the MIT License. See License.txt in the project root for license information.
	 *--------------------------------------------------------------------------------------------*/
	Object.defineProperty(cancellation, "__esModule", { value: true });
	cancellation.CancellationTokenSource = cancellation.CancellationToken = void 0;
	const ral_1 = requireRal();
	const Is = requireIs();
	const events_1 = requireEvents();
	var CancellationToken;
	(function (CancellationToken) {
	    CancellationToken.None = Object.freeze({
	        isCancellationRequested: false,
	        onCancellationRequested: events_1.Event.None
	    });
	    CancellationToken.Cancelled = Object.freeze({
	        isCancellationRequested: true,
	        onCancellationRequested: events_1.Event.None
	    });
	    function is(value) {
	        const candidate = value;
	        return candidate && (candidate === CancellationToken.None
	            || candidate === CancellationToken.Cancelled
	            || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
	    }
	    CancellationToken.is = is;
	})(CancellationToken || (cancellation.CancellationToken = CancellationToken = {}));
	const shortcutEvent = Object.freeze(function (callback, context) {
	    const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
	    return { dispose() { handle.dispose(); } };
	});
	class MutableToken {
	    constructor() {
	        this._isCancelled = false;
	    }
	    cancel() {
	        if (!this._isCancelled) {
	            this._isCancelled = true;
	            if (this._emitter) {
	                this._emitter.fire(undefined);
	                this.dispose();
	            }
	        }
	    }
	    get isCancellationRequested() {
	        return this._isCancelled;
	    }
	    get onCancellationRequested() {
	        if (this._isCancelled) {
	            return shortcutEvent;
	        }
	        if (!this._emitter) {
	            this._emitter = new events_1.Emitter();
	        }
	        return this._emitter.event;
	    }
	    dispose() {
	        if (this._emitter) {
	            this._emitter.dispose();
	            this._emitter = undefined;
	        }
	    }
	}
	class CancellationTokenSource {
	    get token() {
	        if (!this._token) {
	            // be lazy and create the token only when
	            // actually needed
	            this._token = new MutableToken();
	        }
	        return this._token;
	    }
	    cancel() {
	        if (!this._token) {
	            // save an object by returning the default
	            // cancelled token when cancellation happens
	            // before someone asks for the token
	            this._token = CancellationToken.Cancelled;
	        }
	        else {
	            this._token.cancel();
	        }
	    }
	    dispose() {
	        if (!this._token) {
	            // ensure to initialize with an empty token if we had none
	            this._token = CancellationToken.None;
	        }
	        else if (this._token instanceof MutableToken) {
	            // actually dispose
	            this._token.dispose();
	        }
	    }
	}
	cancellation.CancellationTokenSource = CancellationTokenSource;
	return cancellation;
}

var sharedArrayCancellation = {};

var hasRequiredSharedArrayCancellation;

function requireSharedArrayCancellation () {
	if (hasRequiredSharedArrayCancellation) return sharedArrayCancellation;
	hasRequiredSharedArrayCancellation = 1;
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(sharedArrayCancellation, "__esModule", { value: true });
	sharedArrayCancellation.SharedArrayReceiverStrategy = sharedArrayCancellation.SharedArraySenderStrategy = void 0;
	const cancellation_1 = requireCancellation();
	var CancellationState;
	(function (CancellationState) {
	    CancellationState.Continue = 0;
	    CancellationState.Cancelled = 1;
	})(CancellationState || (CancellationState = {}));
	class SharedArraySenderStrategy {
	    constructor() {
	        this.buffers = new Map();
	    }
	    enableCancellation(request) {
	        if (request.id === null) {
	            return;
	        }
	        const buffer = new SharedArrayBuffer(4);
	        const data = new Int32Array(buffer, 0, 1);
	        data[0] = CancellationState.Continue;
	        this.buffers.set(request.id, buffer);
	        request.$cancellationData = buffer;
	    }
	    async sendCancellation(_conn, id) {
	        const buffer = this.buffers.get(id);
	        if (buffer === undefined) {
	            return;
	        }
	        const data = new Int32Array(buffer, 0, 1);
	        Atomics.store(data, 0, CancellationState.Cancelled);
	    }
	    cleanup(id) {
	        this.buffers.delete(id);
	    }
	    dispose() {
	        this.buffers.clear();
	    }
	}
	sharedArrayCancellation.SharedArraySenderStrategy = SharedArraySenderStrategy;
	class SharedArrayBufferCancellationToken {
	    constructor(buffer) {
	        this.data = new Int32Array(buffer, 0, 1);
	    }
	    get isCancellationRequested() {
	        return Atomics.load(this.data, 0) === CancellationState.Cancelled;
	    }
	    get onCancellationRequested() {
	        throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
	    }
	}
	class SharedArrayBufferCancellationTokenSource {
	    constructor(buffer) {
	        this.token = new SharedArrayBufferCancellationToken(buffer);
	    }
	    cancel() {
	    }
	    dispose() {
	    }
	}
	class SharedArrayReceiverStrategy {
	    constructor() {
	        this.kind = 'request';
	    }
	    createCancellationTokenSource(request) {
	        const buffer = request.$cancellationData;
	        if (buffer === undefined) {
	            return new cancellation_1.CancellationTokenSource();
	        }
	        return new SharedArrayBufferCancellationTokenSource(buffer);
	    }
	}
	sharedArrayCancellation.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;
	return sharedArrayCancellation;
}

var messageReader = {};

var semaphore = {};

var hasRequiredSemaphore;

function requireSemaphore () {
	if (hasRequiredSemaphore) return semaphore;
	hasRequiredSemaphore = 1;
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(semaphore, "__esModule", { value: true });
	semaphore.Semaphore = void 0;
	const ral_1 = requireRal();
	class Semaphore {
	    constructor(capacity = 1) {
	        if (capacity <= 0) {
	            throw new Error('Capacity must be greater than 0');
	        }
	        this._capacity = capacity;
	        this._active = 0;
	        this._waiting = [];
	    }
	    lock(thunk) {
	        return new Promise((resolve, reject) => {
	            this._waiting.push({ thunk, resolve, reject });
	            this.runNext();
	        });
	    }
	    get active() {
	        return this._active;
	    }
	    runNext() {
	        if (this._waiting.length === 0 || this._active === this._capacity) {
	            return;
	        }
	        (0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
	    }
	    doRunNext() {
	        if (this._waiting.length === 0 || this._active === this._capacity) {
	            return;
	        }
	        const next = this._waiting.shift();
	        this._active++;
	        if (this._active > this._capacity) {
	            throw new Error(`To many thunks active`);
	        }
	        try {
	            const result = next.thunk();
	            if (result instanceof Promise) {
	                result.then((value) => {
	                    this._active--;
	                    next.resolve(value);
	                    this.runNext();
	                }, (err) => {
	                    this._active--;
	                    next.reject(err);
	                    this.runNext();
	                });
	            }
	            else {
	                this._active--;
	                next.resolve(result);
	                this.runNext();
	            }
	        }
	        catch (err) {
	            this._active--;
	            next.reject(err);
	            this.runNext();
	        }
	    }
	}
	semaphore.Semaphore = Semaphore;
	return semaphore;
}

var hasRequiredMessageReader;

function requireMessageReader () {
	if (hasRequiredMessageReader) return messageReader;
	hasRequiredMessageReader = 1;
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(messageReader, "__esModule", { value: true });
	messageReader.ReadableStreamMessageReader = messageReader.AbstractMessageReader = messageReader.MessageReader = void 0;
	const ral_1 = requireRal();
	const Is = requireIs();
	const events_1 = requireEvents();
	const semaphore_1 = requireSemaphore();
	var MessageReader;
	(function (MessageReader) {
	    function is(value) {
	        let candidate = value;
	        return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
	            Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
	    }
	    MessageReader.is = is;
	})(MessageReader || (messageReader.MessageReader = MessageReader = {}));
	class AbstractMessageReader {
	    constructor() {
	        this.errorEmitter = new events_1.Emitter();
	        this.closeEmitter = new events_1.Emitter();
	        this.partialMessageEmitter = new events_1.Emitter();
	    }
	    dispose() {
	        this.errorEmitter.dispose();
	        this.closeEmitter.dispose();
	    }
	    get onError() {
	        return this.errorEmitter.event;
	    }
	    fireError(error) {
	        this.errorEmitter.fire(this.asError(error));
	    }
	    get onClose() {
	        return this.closeEmitter.event;
	    }
	    fireClose() {
	        this.closeEmitter.fire(undefined);
	    }
	    get onPartialMessage() {
	        return this.partialMessageEmitter.event;
	    }
	    firePartialMessage(info) {
	        this.partialMessageEmitter.fire(info);
	    }
	    asError(error) {
	        if (error instanceof Error) {
	            return error;
	        }
	        else {
	            return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
	        }
	    }
	}
	messageReader.AbstractMessageReader = AbstractMessageReader;
	var ResolvedMessageReaderOptions;
	(function (ResolvedMessageReaderOptions) {
	    function fromOptions(options) {
	        let charset;
	        let contentDecoder;
	        const contentDecoders = new Map();
	        let contentTypeDecoder;
	        const contentTypeDecoders = new Map();
	        if (options === undefined || typeof options === 'string') {
	            charset = options ?? 'utf-8';
	        }
	        else {
	            charset = options.charset ?? 'utf-8';
	            if (options.contentDecoder !== undefined) {
	                contentDecoder = options.contentDecoder;
	                contentDecoders.set(contentDecoder.name, contentDecoder);
	            }
	            if (options.contentDecoders !== undefined) {
	                for (const decoder of options.contentDecoders) {
	                    contentDecoders.set(decoder.name, decoder);
	                }
	            }
	            if (options.contentTypeDecoder !== undefined) {
	                contentTypeDecoder = options.contentTypeDecoder;
	                contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
	            }
	            if (options.contentTypeDecoders !== undefined) {
	                for (const decoder of options.contentTypeDecoders) {
	                    contentTypeDecoders.set(decoder.name, decoder);
	                }
	            }
	        }
	        if (contentTypeDecoder === undefined) {
	            contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
	            contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
	        }
	        return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
	    }
	    ResolvedMessageReaderOptions.fromOptions = fromOptions;
	})(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
	class ReadableStreamMessageReader extends AbstractMessageReader {
	    constructor(readable, options) {
	        super();
	        this.readable = readable;
	        this.options = ResolvedMessageReaderOptions.fromOptions(options);
	        this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
	        this._partialMessageTimeout = 10000;
	        this.nextMessageLength = -1;
	        this.messageToken = 0;
	        this.readSemaphore = new semaphore_1.Semaphore(1);
	    }
	    set partialMessageTimeout(timeout) {
	        this._partialMessageTimeout = timeout;
	    }
	    get partialMessageTimeout() {
	        return this._partialMessageTimeout;
	    }
	    listen(callback) {
	        this.nextMessageLength = -1;
	        this.messageToken = 0;
	        this.partialMessageTimer = undefined;
	        this.callback = callback;
	        const result = this.readable.onData((data) => {
	            this.onData(data);
	        });
	        this.readable.onError((error) => this.fireError(error));
	        this.readable.onClose(() => this.fireClose());
	        return result;
	    }
	    onData(data) {
	        try {
	            this.buffer.append(data);
	            while (true) {
	                if (this.nextMessageLength === -1) {
	                    const headers = this.buffer.tryReadHeaders(true);
	                    if (!headers) {
	                        return;
	                    }
	                    const contentLength = headers.get('content-length');
	                    if (!contentLength) {
	                        this.fireError(new Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(headers))}`));
	                        return;
	                    }
	                    const length = parseInt(contentLength);
	                    if (isNaN(length)) {
	                        this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));
	                        return;
	                    }
	                    this.nextMessageLength = length;
	                }
	                const body = this.buffer.tryReadBody(this.nextMessageLength);
	                if (body === undefined) {
	                    /** We haven't received the full message yet. */
	                    this.setPartialMessageTimer();
	                    return;
	                }
	                this.clearPartialMessageTimer();
	                this.nextMessageLength = -1;
	                // Make sure that we convert one received message after the
	                // other. Otherwise it could happen that a decoding of a second
	                // smaller message finished before the decoding of a first larger
	                // message and then we would deliver the second message first.
	                this.readSemaphore.lock(async () => {
	                    const bytes = this.options.contentDecoder !== undefined
	                        ? await this.options.contentDecoder.decode(body)
	                        : body;
	                    const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
	                    this.callback(message);
	                }).catch((error) => {
	                    this.fireError(error);
	                });
	            }
	        }
	        catch (error) {
	            this.fireError(error);
	        }
	    }
	    clearPartialMessageTimer() {
	        if (this.partialMessageTimer) {
	            this.partialMessageTimer.dispose();
	            this.partialMessageTimer = undefined;
	        }
	    }
	    setPartialMessageTimer() {
	        this.clearPartialMessageTimer();
	        if (this._partialMessageTimeout <= 0) {
	            return;
	        }
	        this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
	            this.partialMessageTimer = undefined;
	            if (token === this.messageToken) {
	                this.firePartialMessage({ messageToken: token, waitingTime: timeout });
	                this.setPartialMessageTimer();
	            }
	        }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
	    }
	}
	messageReader.ReadableStreamMessageReader = ReadableStreamMessageReader;
	return messageReader;
}

var messageWriter = {};

var hasRequiredMessageWriter;

function requireMessageWriter () {
	if (hasRequiredMessageWriter) return messageWriter;
	hasRequiredMessageWriter = 1;
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(messageWriter, "__esModule", { value: true });
	messageWriter.WriteableStreamMessageWriter = messageWriter.AbstractMessageWriter = messageWriter.MessageWriter = void 0;
	const ral_1 = requireRal();
	const Is = requireIs();
	const semaphore_1 = requireSemaphore();
	const events_1 = requireEvents();
	const ContentLength = 'Content-Length: ';
	const CRLF = '\r\n';
	var MessageWriter;
	(function (MessageWriter) {
	    function is(value) {
	        let candidate = value;
	        return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
	            Is.func(candidate.onError) && Is.func(candidate.write);
	    }
	    MessageWriter.is = is;
	})(MessageWriter || (messageWriter.MessageWriter = MessageWriter = {}));
	class AbstractMessageWriter {
	    constructor() {
	        this.errorEmitter = new events_1.Emitter();
	        this.closeEmitter = new events_1.Emitter();
	    }
	    dispose() {
	        this.errorEmitter.dispose();
	        this.closeEmitter.dispose();
	    }
	    get onError() {
	        return this.errorEmitter.event;
	    }
	    fireError(error, message, count) {
	        this.errorEmitter.fire([this.asError(error), message, count]);
	    }
	    get onClose() {
	        return this.closeEmitter.event;
	    }
	    fireClose() {
	        this.closeEmitter.fire(undefined);
	    }
	    asError(error) {
	        if (error instanceof Error) {
	            return error;
	        }
	        else {
	            return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
	        }
	    }
	}
	messageWriter.AbstractMessageWriter = AbstractMessageWriter;
	var ResolvedMessageWriterOptions;
	(function (ResolvedMessageWriterOptions) {
	    function fromOptions(options) {
	        if (options === undefined || typeof options === 'string') {
	            return { charset: options ?? 'utf-8', contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
	        }
	        else {
	            return { charset: options.charset ?? 'utf-8', contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };
	        }
	    }
	    ResolvedMessageWriterOptions.fromOptions = fromOptions;
	})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
	class WriteableStreamMessageWriter extends AbstractMessageWriter {
	    constructor(writable, options) {
	        super();
	        this.writable = writable;
	        this.options = ResolvedMessageWriterOptions.fromOptions(options);
	        this.errorCount = 0;
	        this.writeSemaphore = new semaphore_1.Semaphore(1);
	        this.writable.onError((error) => this.fireError(error));
	        this.writable.onClose(() => this.fireClose());
	    }
	    async write(msg) {
	        return this.writeSemaphore.lock(async () => {
	            const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
	                if (this.options.contentEncoder !== undefined) {
	                    return this.options.contentEncoder.encode(buffer);
	                }
	                else {
	                    return buffer;
	                }
	            });
	            return payload.then((buffer) => {
	                const headers = [];
	                headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
	                headers.push(CRLF);
	                return this.doWrite(msg, headers, buffer);
	            }, (error) => {
	                this.fireError(error);
	                throw error;
	            });
	        });
	    }
	    async doWrite(msg, headers, data) {
	        try {
	            await this.writable.write(headers.join(''), 'ascii');
	            return this.writable.write(data);
	        }
	        catch (error) {
	            this.handleError(error, msg);
	            return Promise.reject(error);
	        }
	    }
	    handleError(error, msg) {
	        this.errorCount++;
	        this.fireError(error, msg, this.errorCount);
	    }
	    end() {
	        this.writable.end();
	    }
	}
	messageWriter.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
	return messageWriter;
}

var messageBuffer = {};

var hasRequiredMessageBuffer;

function requireMessageBuffer () {
	if (hasRequiredMessageBuffer) return messageBuffer;
	hasRequiredMessageBuffer = 1;
	/*---------------------------------------------------------------------------------------------
	 *  Copyright (c) Microsoft Corporation. All rights reserved.
	 *  Licensed under the MIT License. See License.txt in the project root for license information.
	 *--------------------------------------------------------------------------------------------*/
	Object.defineProperty(messageBuffer, "__esModule", { value: true });
	messageBuffer.AbstractMessageBuffer = void 0;
	const CR = 13;
	const LF = 10;
	const CRLF = '\r\n';
	class AbstractMessageBuffer {
	    constructor(encoding = 'utf-8') {
	        this._encoding = encoding;
	        this._chunks = [];
	        this._totalLength = 0;
	    }
	    get encoding() {
	        return this._encoding;
	    }
	    append(chunk) {
	        const toAppend = typeof chunk === 'string' ? this.fromString(chunk, this._encoding) : chunk;
	        this._chunks.push(toAppend);
	        this._totalLength += toAppend.byteLength;
	    }
	    tryReadHeaders(lowerCaseKeys = false) {
	        if (this._chunks.length === 0) {
	            return undefined;
	        }
	        let state = 0;
	        let chunkIndex = 0;
	        let offset = 0;
	        let chunkBytesRead = 0;
	        row: while (chunkIndex < this._chunks.length) {
	            const chunk = this._chunks[chunkIndex];
	            offset = 0;
	            while (offset < chunk.length) {
	                const value = chunk[offset];
	                switch (value) {
	                    case CR:
	                        switch (state) {
	                            case 0:
	                                state = 1;
	                                break;
	                            case 2:
	                                state = 3;
	                                break;
	                            default:
	                                state = 0;
	                        }
	                        break;
	                    case LF:
	                        switch (state) {
	                            case 1:
	                                state = 2;
	                                break;
	                            case 3:
	                                state = 4;
	                                offset++;
	                                break row;
	                            default:
	                                state = 0;
	                        }
	                        break;
	                    default:
	                        state = 0;
	                }
	                offset++;
	            }
	            chunkBytesRead += chunk.byteLength;
	            chunkIndex++;
	        }
	        if (state !== 4) {
	            return undefined;
	        }
	        // The buffer contains the two CRLF at the end. So we will
	        // have two empty lines after the split at the end as well.
	        const buffer = this._read(chunkBytesRead + offset);
	        const result = new Map();
	        const headers = this.toString(buffer, 'ascii').split(CRLF);
	        if (headers.length < 2) {
	            return result;
	        }
	        for (let i = 0; i < headers.length - 2; i++) {
	            const header = headers[i];
	            const index = header.indexOf(':');
	            if (index === -1) {
	                throw new Error(`Message header must separate key and value using ':'\n${header}`);
	            }
	            const key = header.substr(0, index);
	            const value = header.substr(index + 1).trim();
	            result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
	        }
	        return result;
	    }
	    tryReadBody(length) {
	        if (this._totalLength < length) {
	            return undefined;
	        }
	        return this._read(length);
	    }
	    get numberOfBytes() {
	        return this._totalLength;
	    }
	    _read(byteCount) {
	        if (byteCount === 0) {
	            return this.emptyBuffer();
	        }
	        if (byteCount > this._totalLength) {
	            throw new Error(`Cannot read so many bytes!`);
	        }
	        if (this._chunks[0].byteLength === byteCount) {
	            // super fast path, precisely first chunk must be returned
	            const chunk = this._chunks[0];
	            this._chunks.shift();
	            this._totalLength -= byteCount;
	            return this.asNative(chunk);
	        }
	        if (this._chunks[0].byteLength > byteCount) {
	            // fast path, the reading is entirely within the first chunk
	            const chunk = this._chunks[0];
	            const result = this.asNative(chunk, byteCount);
	            this._chunks[0] = chunk.slice(byteCount);
	            this._totalLength -= byteCount;
	            return result;
	        }
	        const result = this.allocNative(byteCount);
	        let resultOffset = 0;
	        let chunkIndex = 0;
	        while (byteCount > 0) {
	            const chunk = this._chunks[chunkIndex];
	            if (chunk.byteLength > byteCount) {
	                // this chunk will survive
	                const chunkPart = chunk.slice(0, byteCount);
	                result.set(chunkPart, resultOffset);
	                resultOffset += byteCount;
	                this._chunks[chunkIndex] = chunk.slice(byteCount);
	                this._totalLength -= byteCount;
	                byteCount -= byteCount;
	            }
	            else {
	                // this chunk will be entirely read
	                result.set(chunk, resultOffset);
	                resultOffset += chunk.byteLength;
	                this._chunks.shift();
	                this._totalLength -= chunk.byteLength;
	                byteCount -= chunk.byteLength;
	            }
	        }
	        return result;
	    }
	}
	messageBuffer.AbstractMessageBuffer = AbstractMessageBuffer;
	return messageBuffer;
}

var connection$1 = {};

var hasRequiredConnection;

function requireConnection () {
	if (hasRequiredConnection) return connection$1;
	hasRequiredConnection = 1;
	(function (exports) {
		/* --------------------------------------------------------------------------------------------
		 * Copyright (c) Microsoft Corporation. All rights reserved.
		 * Licensed under the MIT License. See License.txt in the project root for license information.
		 * ------------------------------------------------------------------------------------------ */
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0;
		const ral_1 = requireRal();
		const Is = requireIs();
		const messages_1 = requireMessages();
		const linkedMap_1 = requireLinkedMap();
		const events_1 = requireEvents();
		const cancellation_1 = requireCancellation();
		var CancelNotification;
		(function (CancelNotification) {
		    CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
		})(CancelNotification || (CancelNotification = {}));
		var ProgressToken;
		(function (ProgressToken) {
		    function is(value) {
		        return typeof value === 'string' || typeof value === 'number';
		    }
		    ProgressToken.is = is;
		})(ProgressToken || (exports.ProgressToken = ProgressToken = {}));
		var ProgressNotification;
		(function (ProgressNotification) {
		    ProgressNotification.type = new messages_1.NotificationType('$/progress');
		})(ProgressNotification || (ProgressNotification = {}));
		class ProgressType {
		    constructor() {
		    }
		}
		exports.ProgressType = ProgressType;
		var StarRequestHandler;
		(function (StarRequestHandler) {
		    function is(value) {
		        return Is.func(value);
		    }
		    StarRequestHandler.is = is;
		})(StarRequestHandler || (StarRequestHandler = {}));
		exports.NullLogger = Object.freeze({
		    error: () => { },
		    warn: () => { },
		    info: () => { },
		    log: () => { }
		});
		var Trace;
		(function (Trace) {
		    Trace[Trace["Off"] = 0] = "Off";
		    Trace[Trace["Messages"] = 1] = "Messages";
		    Trace[Trace["Compact"] = 2] = "Compact";
		    Trace[Trace["Verbose"] = 3] = "Verbose";
		})(Trace || (exports.Trace = Trace = {}));
		var TraceValues;
		(function (TraceValues) {
		    /**
		     * Turn tracing off.
		     */
		    TraceValues.Off = 'off';
		    /**
		     * Trace messages only.
		     */
		    TraceValues.Messages = 'messages';
		    /**
		     * Compact message tracing.
		     */
		    TraceValues.Compact = 'compact';
		    /**
		     * Verbose message tracing.
		     */
		    TraceValues.Verbose = 'verbose';
		})(TraceValues || (exports.TraceValues = TraceValues = {}));
		(function (Trace) {
		    function fromString(value) {
		        if (!Is.string(value)) {
		            return Trace.Off;
		        }
		        value = value.toLowerCase();
		        switch (value) {
		            case 'off':
		                return Trace.Off;
		            case 'messages':
		                return Trace.Messages;
		            case 'compact':
		                return Trace.Compact;
		            case 'verbose':
		                return Trace.Verbose;
		            default:
		                return Trace.Off;
		        }
		    }
		    Trace.fromString = fromString;
		    function toString(value) {
		        switch (value) {
		            case Trace.Off:
		                return 'off';
		            case Trace.Messages:
		                return 'messages';
		            case Trace.Compact:
		                return 'compact';
		            case Trace.Verbose:
		                return 'verbose';
		            default:
		                return 'off';
		        }
		    }
		    Trace.toString = toString;
		})(Trace || (exports.Trace = Trace = {}));
		var TraceFormat;
		(function (TraceFormat) {
		    TraceFormat["Text"] = "text";
		    TraceFormat["JSON"] = "json";
		})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
		(function (TraceFormat) {
		    function fromString(value) {
		        if (!Is.string(value)) {
		            return TraceFormat.Text;
		        }
		        value = value.toLowerCase();
		        if (value === 'json') {
		            return TraceFormat.JSON;
		        }
		        else {
		            return TraceFormat.Text;
		        }
		    }
		    TraceFormat.fromString = fromString;
		})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
		var SetTraceNotification;
		(function (SetTraceNotification) {
		    SetTraceNotification.type = new messages_1.NotificationType('$/setTrace');
		})(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {}));
		var LogTraceNotification;
		(function (LogTraceNotification) {
		    LogTraceNotification.type = new messages_1.NotificationType('$/logTrace');
		})(LogTraceNotification || (exports.LogTraceNotification = LogTraceNotification = {}));
		var ConnectionErrors;
		(function (ConnectionErrors) {
		    /**
		     * The connection is closed.
		     */
		    ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
		    /**
		     * The connection got disposed.
		     */
		    ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
		    /**
		     * The connection is already in listening mode.
		     */
		    ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
		})(ConnectionErrors || (exports.ConnectionErrors = ConnectionErrors = {}));
		class ConnectionError extends Error {
		    constructor(code, message) {
		        super(message);
		        this.code = code;
		        Object.setPrototypeOf(this, ConnectionError.prototype);
		    }
		}
		exports.ConnectionError = ConnectionError;
		var ConnectionStrategy;
		(function (ConnectionStrategy) {
		    function is(value) {
		        const candidate = value;
		        return candidate && Is.func(candidate.cancelUndispatched);
		    }
		    ConnectionStrategy.is = is;
		})(ConnectionStrategy || (exports.ConnectionStrategy = ConnectionStrategy = {}));
		var IdCancellationReceiverStrategy;
		(function (IdCancellationReceiverStrategy) {
		    function is(value) {
		        const candidate = value;
		        return candidate && (candidate.kind === undefined || candidate.kind === 'id') && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));
		    }
		    IdCancellationReceiverStrategy.is = is;
		})(IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));
		var RequestCancellationReceiverStrategy;
		(function (RequestCancellationReceiverStrategy) {
		    function is(value) {
		        const candidate = value;
		        return candidate && candidate.kind === 'request' && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));
		    }
		    RequestCancellationReceiverStrategy.is = is;
		})(RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));
		var CancellationReceiverStrategy;
		(function (CancellationReceiverStrategy) {
		    CancellationReceiverStrategy.Message = Object.freeze({
		        createCancellationTokenSource(_) {
		            return new cancellation_1.CancellationTokenSource();
		        }
		    });
		    function is(value) {
		        return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
		    }
		    CancellationReceiverStrategy.is = is;
		})(CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));
		var CancellationSenderStrategy;
		(function (CancellationSenderStrategy) {
		    CancellationSenderStrategy.Message = Object.freeze({
		        sendCancellation(conn, id) {
		            return conn.sendNotification(CancelNotification.type, { id });
		        },
		        cleanup(_) { }
		    });
		    function is(value) {
		        const candidate = value;
		        return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
		    }
		    CancellationSenderStrategy.is = is;
		})(CancellationSenderStrategy || (exports.CancellationSenderStrategy = CancellationSenderStrategy = {}));
		var CancellationStrategy;
		(function (CancellationStrategy) {
		    CancellationStrategy.Message = Object.freeze({
		        receiver: CancellationReceiverStrategy.Message,
		        sender: CancellationSenderStrategy.Message
		    });
		    function is(value) {
		        const candidate = value;
		        return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
		    }
		    CancellationStrategy.is = is;
		})(CancellationStrategy || (exports.CancellationStrategy = CancellationStrategy = {}));
		var MessageStrategy;
		(function (MessageStrategy) {
		    function is(value) {
		        const candidate = value;
		        return candidate && Is.func(candidate.handleMessage);
		    }
		    MessageStrategy.is = is;
		})(MessageStrategy || (exports.MessageStrategy = MessageStrategy = {}));
		var ConnectionOptions;
		(function (ConnectionOptions) {
		    function is(value) {
		        const candidate = value;
		        return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));
		    }
		    ConnectionOptions.is = is;
		})(ConnectionOptions || (exports.ConnectionOptions = ConnectionOptions = {}));
		var ConnectionState;
		(function (ConnectionState) {
		    ConnectionState[ConnectionState["New"] = 1] = "New";
		    ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
		    ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
		    ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
		})(ConnectionState || (ConnectionState = {}));
		function createMessageConnection(messageReader, messageWriter, _logger, options) {
		    const logger = _logger !== undefined ? _logger : exports.NullLogger;
		    let sequenceNumber = 0;
		    let notificationSequenceNumber = 0;
		    let unknownResponseSequenceNumber = 0;
		    const version = '2.0';
		    let starRequestHandler = undefined;
		    const requestHandlers = new Map();
		    let starNotificationHandler = undefined;
		    const notificationHandlers = new Map();
		    const progressHandlers = new Map();
		    let timer;
		    let messageQueue = new linkedMap_1.LinkedMap();
		    let responsePromises = new Map();
		    let knownCanceledRequests = new Set();
		    let requestTokens = new Map();
		    let trace = Trace.Off;
		    let traceFormat = TraceFormat.Text;
		    let tracer;
		    let state = ConnectionState.New;
		    const errorEmitter = new events_1.Emitter();
		    const closeEmitter = new events_1.Emitter();
		    const unhandledNotificationEmitter = new events_1.Emitter();
		    const unhandledProgressEmitter = new events_1.Emitter();
		    const disposeEmitter = new events_1.Emitter();
		    const cancellationStrategy = (options && options.cancellationStrategy) ? options.cancellationStrategy : CancellationStrategy.Message;
		    function createRequestQueueKey(id) {
		        if (id === null) {
		            throw new Error(`Can't send requests with id null since the response can't be correlated.`);
		        }
		        return 'req-' + id.toString();
		    }
		    function createResponseQueueKey(id) {
		        if (id === null) {
		            return 'res-unknown-' + (++unknownResponseSequenceNumber).toString();
		        }
		        else {
		            return 'res-' + id.toString();
		        }
		    }
		    function createNotificationQueueKey() {
		        return 'not-' + (++notificationSequenceNumber).toString();
		    }
		    function addMessageToQueue(queue, message) {
		        if (messages_1.Message.isRequest(message)) {
		            queue.set(createRequestQueueKey(message.id), message);
		        }
		        else if (messages_1.Message.isResponse(message)) {
		            queue.set(createResponseQueueKey(message.id), message);
		        }
		        else {
		            queue.set(createNotificationQueueKey(), message);
		        }
		    }
		    function cancelUndispatched(_message) {
		        return undefined;
		    }
		    function isListening() {
		        return state === ConnectionState.Listening;
		    }
		    function isClosed() {
		        return state === ConnectionState.Closed;
		    }
		    function isDisposed() {
		        return state === ConnectionState.Disposed;
		    }
		    function closeHandler() {
		        if (state === ConnectionState.New || state === ConnectionState.Listening) {
		            state = ConnectionState.Closed;
		            closeEmitter.fire(undefined);
		        }
		        // If the connection is disposed don't sent close events.
		    }
		    function readErrorHandler(error) {
		        errorEmitter.fire([error, undefined, undefined]);
		    }
		    function writeErrorHandler(data) {
		        errorEmitter.fire(data);
		    }
		    messageReader.onClose(closeHandler);
		    messageReader.onError(readErrorHandler);
		    messageWriter.onClose(closeHandler);
		    messageWriter.onError(writeErrorHandler);
		    function triggerMessageQueue() {
		        if (timer || messageQueue.size === 0) {
		            return;
		        }
		        timer = (0, ral_1.default)().timer.setImmediate(() => {
		            timer = undefined;
		            processMessageQueue();
		        });
		    }
		    function handleMessage(message) {
		        if (messages_1.Message.isRequest(message)) {
		            handleRequest(message);
		        }
		        else if (messages_1.Message.isNotification(message)) {
		            handleNotification(message);
		        }
		        else if (messages_1.Message.isResponse(message)) {
		            handleResponse(message);
		        }
		        else {
		            handleInvalidMessage(message);
		        }
		    }
		    function processMessageQueue() {
		        if (messageQueue.size === 0) {
		            return;
		        }
		        const message = messageQueue.shift();
		        try {
		            const messageStrategy = options?.messageStrategy;
		            if (MessageStrategy.is(messageStrategy)) {
		                messageStrategy.handleMessage(message, handleMessage);
		            }
		            else {
		                handleMessage(message);
		            }
		        }
		        finally {
		            triggerMessageQueue();
		        }
		    }
		    const callback = (message) => {
		        try {
		            // We have received a cancellation message. Check if the message is still in the queue
		            // and cancel it if allowed to do so.
		            if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
		                const cancelId = message.params.id;
		                const key = createRequestQueueKey(cancelId);
		                const toCancel = messageQueue.get(key);
		                if (messages_1.Message.isRequest(toCancel)) {
		                    const strategy = options?.connectionStrategy;
		                    const response = (strategy && strategy.cancelUndispatched) ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
		                    if (response && (response.error !== undefined || response.result !== undefined)) {
		                        messageQueue.delete(key);
		                        requestTokens.delete(cancelId);
		                        response.id = toCancel.id;
		                        traceSendingResponse(response, message.method, Date.now());
		                        messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));
		                        return;
		                    }
		                }
		                const cancellationToken = requestTokens.get(cancelId);
		                // The request is already running. Cancel the token
		                if (cancellationToken !== undefined) {
		                    cancellationToken.cancel();
		                    traceReceivedNotification(message);
		                    return;
		                }
		                else {
		                    // Remember the cancel but still queue the message to
		                    // clean up state in process message.
		                    knownCanceledRequests.add(cancelId);
		                }
		            }
		            addMessageToQueue(messageQueue, message);
		        }
		        finally {
		            triggerMessageQueue();
		        }
		    };
		    function handleRequest(requestMessage) {
		        if (isDisposed()) {
		            // we return here silently since we fired an event when the
		            // connection got disposed.
		            return;
		        }
		        function reply(resultOrError, method, startTime) {
		            const message = {
		                jsonrpc: version,
		                id: requestMessage.id
		            };
		            if (resultOrError instanceof messages_1.ResponseError) {
		                message.error = resultOrError.toJson();
		            }
		            else {
		                message.result = resultOrError === undefined ? null : resultOrError;
		            }
		            traceSendingResponse(message, method, startTime);
		            messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
		        }
		        function replyError(error, method, startTime) {
		            const message = {
		                jsonrpc: version,
		                id: requestMessage.id,
		                error: error.toJson()
		            };
		            traceSendingResponse(message, method, startTime);
		            messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
		        }
		        function replySuccess(result, method, startTime) {
		            // The JSON RPC defines that a response must either have a result or an error
		            // So we can't treat undefined as a valid response result.
		            if (result === undefined) {
		                result = null;
		            }
		            const message = {
		                jsonrpc: version,
		                id: requestMessage.id,
		                result: result
		            };
		            traceSendingResponse(message, method, startTime);
		            messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
		        }
		        traceReceivedRequest(requestMessage);
		        const element = requestHandlers.get(requestMessage.method);
		        let type;
		        let requestHandler;
		        if (element) {
		            type = element.type;
		            requestHandler = element.handler;
		        }
		        const startTime = Date.now();
		        if (requestHandler || starRequestHandler) {
		            const tokenKey = requestMessage.id ?? String(Date.now()); //
		            const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver)
		                ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey)
		                : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
		            if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {
		                cancellationSource.cancel();
		            }
		            if (requestMessage.id !== null) {
		                requestTokens.set(tokenKey, cancellationSource);
		            }
		            try {
		                let handlerResult;
		                if (requestHandler) {
		                    if (requestMessage.params === undefined) {
		                        if (type !== undefined && type.numberOfParams !== 0) {
		                            replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
		                            return;
		                        }
		                        handlerResult = requestHandler(cancellationSource.token);
		                    }
		                    else if (Array.isArray(requestMessage.params)) {
		                        if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) {
		                            replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
		                            return;
		                        }
		                        handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
		                    }
		                    else {
		                        if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
		                            replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
		                            return;
		                        }
		                        handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
		                    }
		                }
		                else if (starRequestHandler) {
		                    handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
		                }
		                const promise = handlerResult;
		                if (!handlerResult) {
		                    requestTokens.delete(tokenKey);
		                    replySuccess(handlerResult, requestMessage.method, startTime);
		                }
		                else if (promise.then) {
		                    promise.then((resultOrError) => {
		                        requestTokens.delete(tokenKey);
		                        reply(resultOrError, requestMessage.method, startTime);
		                    }, error => {
		                        requestTokens.delete(tokenKey);
		                        if (error instanceof messages_1.ResponseError) {
		                            replyError(error, requestMessage.method, startTime);
		                        }
		                        else if (error && Is.string(error.message)) {
		                            replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
		                        }
		                        else {
		                            replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
		                        }
		                    });
		                }
		                else {
		                    requestTokens.delete(tokenKey);
		                    reply(handlerResult, requestMessage.method, startTime);
		                }
		            }
		            catch (error) {
		                requestTokens.delete(tokenKey);
		                if (error instanceof messages_1.ResponseError) {
		                    reply(error, requestMessage.method, startTime);
		                }
		                else if (error && Is.string(error.message)) {
		                    replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
		                }
		                else {
		                    replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
		                }
		            }
		        }
		        else {
		            replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
		        }
		    }
		    function handleResponse(responseMessage) {
		        if (isDisposed()) {
		            // See handle request.
		            return;
		        }
		        if (responseMessage.id === null) {
		            if (responseMessage.error) {
		                logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
		            }
		            else {
		                logger.error(`Received response message without id. No further error information provided.`);
		            }
		        }
		        else {
		            const key = responseMessage.id;
		            const responsePromise = responsePromises.get(key);
		            traceReceivedResponse(responseMessage, responsePromise);
		            if (responsePromise !== undefined) {
		                responsePromises.delete(key);
		                try {
		                    if (responseMessage.error) {
		                        const error = responseMessage.error;
		                        responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
		                    }
		                    else if (responseMessage.result !== undefined) {
		                        responsePromise.resolve(responseMessage.result);
		                    }
		                    else {
		                        throw new Error('Should never happen.');
		                    }
		                }
		                catch (error) {
		                    if (error.message) {
		                        logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
		                    }
		                    else {
		                        logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
		                    }
		                }
		            }
		        }
		    }
		    function handleNotification(message) {
		        if (isDisposed()) {
		            // See handle request.
		            return;
		        }
		        let type = undefined;
		        let notificationHandler;
		        if (message.method === CancelNotification.type.method) {
		            const cancelId = message.params.id;
		            knownCanceledRequests.delete(cancelId);
		            traceReceivedNotification(message);
		            return;
		        }
		        else {
		            const element = notificationHandlers.get(message.method);
		            if (element) {
		                notificationHandler = element.handler;
		                type = element.type;
		            }
		        }
		        if (notificationHandler || starNotificationHandler) {
		            try {
		                traceReceivedNotification(message);
		                if (notificationHandler) {
		                    if (message.params === undefined) {
		                        if (type !== undefined) {
		                            if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
		                                logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
		                            }
		                        }
		                        notificationHandler();
		                    }
		                    else if (Array.isArray(message.params)) {
		                        // There are JSON-RPC libraries that send progress message as positional params although
		                        // specified as named. So convert them if this is the case.
		                        const params = message.params;
		                        if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {
		                            notificationHandler({ token: params[0], value: params[1] });
		                        }
		                        else {
		                            if (type !== undefined) {
		                                if (type.parameterStructures === messages_1.ParameterStructures.byName) {
		                                    logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
		                                }
		                                if (type.numberOfParams !== message.params.length) {
		                                    logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
		                                }
		                            }
		                            notificationHandler(...params);
		                        }
		                    }
		                    else {
		                        if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
		                            logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
		                        }
		                        notificationHandler(message.params);
		                    }
		                }
		                else if (starNotificationHandler) {
		                    starNotificationHandler(message.method, message.params);
		                }
		            }
		            catch (error) {
		                if (error.message) {
		                    logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
		                }
		                else {
		                    logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
		                }
		            }
		        }
		        else {
		            unhandledNotificationEmitter.fire(message);
		        }
		    }
		    function handleInvalidMessage(message) {
		        if (!message) {
		            logger.error('Received empty message.');
		            return;
		        }
		        logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
		        // Test whether we find an id to reject the promise
		        const responseMessage = message;
		        if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
		            const key = responseMessage.id;
		            const responseHandler = responsePromises.get(key);
		            if (responseHandler) {
		                responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
		            }
		        }
		    }
		    function stringifyTrace(params) {
		        if (params === undefined || params === null) {
		            return undefined;
		        }
		        switch (trace) {
		            case Trace.Verbose:
		                return JSON.stringify(params, null, 4);
		            case Trace.Compact:
		                return JSON.stringify(params);
		            default:
		                return undefined;
		        }
		    }
		    function traceSendingRequest(message) {
		        if (trace === Trace.Off || !tracer) {
		            return;
		        }
		        if (traceFormat === TraceFormat.Text) {
		            let data = undefined;
		            if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
		                data = `Params: ${stringifyTrace(message.params)}\n\n`;
		            }
		            tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
		        }
		        else {
		            logLSPMessage('send-request', message);
		        }
		    }
		    function traceSendingNotification(message) {
		        if (trace === Trace.Off || !tracer) {
		            return;
		        }
		        if (traceFormat === TraceFormat.Text) {
		            let data = undefined;
		            if (trace === Trace.Verbose || trace === Trace.Compact) {
		                if (message.params) {
		                    data = `Params: ${stringifyTrace(message.params)}\n\n`;
		                }
		                else {
		                    data = 'No parameters provided.\n\n';
		                }
		            }
		            tracer.log(`Sending notification '${message.method}'.`, data);
		        }
		        else {
		            logLSPMessage('send-notification', message);
		        }
		    }
		    function traceSendingResponse(message, method, startTime) {
		        if (trace === Trace.Off || !tracer) {
		            return;
		        }
		        if (traceFormat === TraceFormat.Text) {
		            let data = undefined;
		            if (trace === Trace.Verbose || trace === Trace.Compact) {
		                if (message.error && message.error.data) {
		                    data = `Error data: ${stringifyTrace(message.error.data)}\n\n`;
		                }
		                else {
		                    if (message.result) {
		                        data = `Result: ${stringifyTrace(message.result)}\n\n`;
		                    }
		                    else if (message.error === undefined) {
		                        data = 'No result returned.\n\n';
		                    }
		                }
		            }
		            tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
		        }
		        else {
		            logLSPMessage('send-response', message);
		        }
		    }
		    function traceReceivedRequest(message) {
		        if (trace === Trace.Off || !tracer) {
		            return;
		        }
		        if (traceFormat === TraceFormat.Text) {
		            let data = undefined;
		            if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
		                data = `Params: ${stringifyTrace(message.params)}\n\n`;
		            }
		            tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
		        }
		        else {
		            logLSPMessage('receive-request', message);
		        }
		    }
		    function traceReceivedNotification(message) {
		        if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
		            return;
		        }
		        if (traceFormat === TraceFormat.Text) {
		            let data = undefined;
		            if (trace === Trace.Verbose || trace === Trace.Compact) {
		                if (message.params) {
		                    data = `Params: ${stringifyTrace(message.params)}\n\n`;
		                }
		                else {
		                    data = 'No parameters provided.\n\n';
		                }
		            }
		            tracer.log(`Received notification '${message.method}'.`, data);
		        }
		        else {
		            logLSPMessage('receive-notification', message);
		        }
		    }
		    function traceReceivedResponse(message, responsePromise) {
		        if (trace === Trace.Off || !tracer) {
		            return;
		        }
		        if (traceFormat === TraceFormat.Text) {
		            let data = undefined;
		            if (trace === Trace.Verbose || trace === Trace.Compact) {
		                if (message.error && message.error.data) {
		                    data = `Error data: ${stringifyTrace(message.error.data)}\n\n`;
		                }
		                else {
		                    if (message.result) {
		                        data = `Result: ${stringifyTrace(message.result)}\n\n`;
		                    }
		                    else if (message.error === undefined) {
		                        data = 'No result returned.\n\n';
		                    }
		                }
		            }
		            if (responsePromise) {
		                const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
		                tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
		            }
		            else {
		                tracer.log(`Received response ${message.id} without active response promise.`, data);
		            }
		        }
		        else {
		            logLSPMessage('receive-response', message);
		        }
		    }
		    function logLSPMessage(type, message) {
		        if (!tracer || trace === Trace.Off) {
		            return;
		        }
		        const lspMessage = {
		            isLSPMessage: true,
		            type,
		            message,
		            timestamp: Date.now()
		        };
		        tracer.log(lspMessage);
		    }
		    function throwIfClosedOrDisposed() {
		        if (isClosed()) {
		            throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
		        }
		        if (isDisposed()) {
		            throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
		        }
		    }
		    function throwIfListening() {
		        if (isListening()) {
		            throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
		        }
		    }
		    function throwIfNotListening() {
		        if (!isListening()) {
		            throw new Error('Call listen() first.');
		        }
		    }
		    function undefinedToNull(param) {
		        if (param === undefined) {
		            return null;
		        }
		        else {
		            return param;
		        }
		    }
		    function nullToUndefined(param) {
		        if (param === null) {
		            return undefined;
		        }
		        else {
		            return param;
		        }
		    }
		    function isNamedParam(param) {
		        return param !== undefined && param !== null && !Array.isArray(param) && typeof param === 'object';
		    }
		    function computeSingleParam(parameterStructures, param) {
		        switch (parameterStructures) {
		            case messages_1.ParameterStructures.auto:
		                if (isNamedParam(param)) {
		                    return nullToUndefined(param);
		                }
		                else {
		                    return [undefinedToNull(param)];
		                }
		            case messages_1.ParameterStructures.byName:
		                if (!isNamedParam(param)) {
		                    throw new Error(`Received parameters by name but param is not an object literal.`);
		                }
		                return nullToUndefined(param);
		            case messages_1.ParameterStructures.byPosition:
		                return [undefinedToNull(param)];
		            default:
		                throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
		        }
		    }
		    function computeMessageParams(type, params) {
		        let result;
		        const numberOfParams = type.numberOfParams;
		        switch (numberOfParams) {
		            case 0:
		                result = undefined;
		                break;
		            case 1:
		                result = computeSingleParam(type.parameterStructures, params[0]);
		                break;
		            default:
		                result = [];
		                for (let i = 0; i < params.length && i < numberOfParams; i++) {
		                    result.push(undefinedToNull(params[i]));
		                }
		                if (params.length < numberOfParams) {
		                    for (let i = params.length; i < numberOfParams; i++) {
		                        result.push(null);
		                    }
		                }
		                break;
		        }
		        return result;
		    }
		    const connection = {
		        sendNotification: (type, ...args) => {
		            throwIfClosedOrDisposed();
		            let method;
		            let messageParams;
		            if (Is.string(type)) {
		                method = type;
		                const first = args[0];
		                let paramStart = 0;
		                let parameterStructures = messages_1.ParameterStructures.auto;
		                if (messages_1.ParameterStructures.is(first)) {
		                    paramStart = 1;
		                    parameterStructures = first;
		                }
		                let paramEnd = args.length;
		                const numberOfParams = paramEnd - paramStart;
		                switch (numberOfParams) {
		                    case 0:
		                        messageParams = undefined;
		                        break;
		                    case 1:
		                        messageParams = computeSingleParam(parameterStructures, args[paramStart]);
		                        break;
		                    default:
		                        if (parameterStructures === messages_1.ParameterStructures.byName) {
		                            throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
		                        }
		                        messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value));
		                        break;
		                }
		            }
		            else {
		                const params = args;
		                method = type.method;
		                messageParams = computeMessageParams(type, params);
		            }
		            const notificationMessage = {
		                jsonrpc: version,
		                method: method,
		                params: messageParams
		            };
		            traceSendingNotification(notificationMessage);
		            return messageWriter.write(notificationMessage).catch((error) => {
		                logger.error(`Sending notification failed.`);
		                throw error;
		            });
		        },
		        onNotification: (type, handler) => {
		            throwIfClosedOrDisposed();
		            let method;
		            if (Is.func(type)) {
		                starNotificationHandler = type;
		            }
		            else if (handler) {
		                if (Is.string(type)) {
		                    method = type;
		                    notificationHandlers.set(type, { type: undefined, handler });
		                }
		                else {
		                    method = type.method;
		                    notificationHandlers.set(type.method, { type, handler });
		                }
		            }
		            return {
		                dispose: () => {
		                    if (method !== undefined) {
		                        notificationHandlers.delete(method);
		                    }
		                    else {
		                        starNotificationHandler = undefined;
		                    }
		                }
		            };
		        },
		        onProgress: (_type, token, handler) => {
		            if (progressHandlers.has(token)) {
		                throw new Error(`Progress handler for token ${token} already registered`);
		            }
		            progressHandlers.set(token, handler);
		            return {
		                dispose: () => {
		                    progressHandlers.delete(token);
		                }
		            };
		        },
		        sendProgress: (_type, token, value) => {
		            // This should not await but simple return to ensure that we don't have another
		            // async scheduling. Otherwise one send could overtake another send.
		            return connection.sendNotification(ProgressNotification.type, { token, value });
		        },
		        onUnhandledProgress: unhandledProgressEmitter.event,
		        sendRequest: (type, ...args) => {
		            throwIfClosedOrDisposed();
		            throwIfNotListening();
		            let method;
		            let messageParams;
		            let token = undefined;
		            if (Is.string(type)) {
		                method = type;
		                const first = args[0];
		                const last = args[args.length - 1];
		                let paramStart = 0;
		                let parameterStructures = messages_1.ParameterStructures.auto;
		                if (messages_1.ParameterStructures.is(first)) {
		                    paramStart = 1;
		                    parameterStructures = first;
		                }
		                let paramEnd = args.length;
		                if (cancellation_1.CancellationToken.is(last)) {
		                    paramEnd = paramEnd - 1;
		                    token = last;
		                }
		                const numberOfParams = paramEnd - paramStart;
		                switch (numberOfParams) {
		                    case 0:
		                        messageParams = undefined;
		                        break;
		                    case 1:
		                        messageParams = computeSingleParam(parameterStructures, args[paramStart]);
		                        break;
		                    default:
		                        if (parameterStructures === messages_1.ParameterStructures.byName) {
		                            throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
		                        }
		                        messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value));
		                        break;
		                }
		            }
		            else {
		                const params = args;
		                method = type.method;
		                messageParams = computeMessageParams(type, params);
		                const numberOfParams = type.numberOfParams;
		                token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
		            }
		            const id = sequenceNumber++;
		            let disposable;
		            if (token) {
		                disposable = token.onCancellationRequested(() => {
		                    const p = cancellationStrategy.sender.sendCancellation(connection, id);
		                    if (p === undefined) {
		                        logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`);
		                        return Promise.resolve();
		                    }
		                    else {
		                        return p.catch(() => {
		                            logger.log(`Sending cancellation messages for id ${id} failed`);
		                        });
		                    }
		                });
		            }
		            const requestMessage = {
		                jsonrpc: version,
		                id: id,
		                method: method,
		                params: messageParams
		            };
		            traceSendingRequest(requestMessage);
		            if (typeof cancellationStrategy.sender.enableCancellation === 'function') {
		                cancellationStrategy.sender.enableCancellation(requestMessage);
		            }
		            return new Promise(async (resolve, reject) => {
		                const resolveWithCleanup = (r) => {
		                    resolve(r);
		                    cancellationStrategy.sender.cleanup(id);
		                    disposable?.dispose();
		                };
		                const rejectWithCleanup = (r) => {
		                    reject(r);
		                    cancellationStrategy.sender.cleanup(id);
		                    disposable?.dispose();
		                };
		                const responsePromise = { method: method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
		                try {
		                    await messageWriter.write(requestMessage);
		                    responsePromises.set(id, responsePromise);
		                }
		                catch (error) {
		                    logger.error(`Sending request failed.`);
		                    // Writing the message failed. So we need to reject the promise.
		                    responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : 'Unknown reason'));
		                    throw error;
		                }
		            });
		        },
		        onRequest: (type, handler) => {
		            throwIfClosedOrDisposed();
		            let method = null;
		            if (StarRequestHandler.is(type)) {
		                method = undefined;
		                starRequestHandler = type;
		            }
		            else if (Is.string(type)) {
		                method = null;
		                if (handler !== undefined) {
		                    method = type;
		                    requestHandlers.set(type, { handler: handler, type: undefined });
		                }
		            }
		            else {
		                if (handler !== undefined) {
		                    method = type.method;
		                    requestHandlers.set(type.method, { type, handler });
		                }
		            }
		            return {
		                dispose: () => {
		                    if (method === null) {
		                        return;
		                    }
		                    if (method !== undefined) {
		                        requestHandlers.delete(method);
		                    }
		                    else {
		                        starRequestHandler = undefined;
		                    }
		                }
		            };
		        },
		        hasPendingResponse: () => {
		            return responsePromises.size > 0;
		        },
		        trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {
		            let _sendNotification = false;
		            let _traceFormat = TraceFormat.Text;
		            if (sendNotificationOrTraceOptions !== undefined) {
		                if (Is.boolean(sendNotificationOrTraceOptions)) {
		                    _sendNotification = sendNotificationOrTraceOptions;
		                }
		                else {
		                    _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
		                    _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
		                }
		            }
		            trace = _value;
		            traceFormat = _traceFormat;
		            if (trace === Trace.Off) {
		                tracer = undefined;
		            }
		            else {
		                tracer = _tracer;
		            }
		            if (_sendNotification && !isClosed() && !isDisposed()) {
		                await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
		            }
		        },
		        onError: errorEmitter.event,
		        onClose: closeEmitter.event,
		        onUnhandledNotification: unhandledNotificationEmitter.event,
		        onDispose: disposeEmitter.event,
		        end: () => {
		            messageWriter.end();
		        },
		        dispose: () => {
		            if (isDisposed()) {
		                return;
		            }
		            state = ConnectionState.Disposed;
		            disposeEmitter.fire(undefined);
		            const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, 'Pending response rejected since connection got disposed');
		            for (const promise of responsePromises.values()) {
		                promise.reject(error);
		            }
		            responsePromises = new Map();
		            requestTokens = new Map();
		            knownCanceledRequests = new Set();
		            messageQueue = new linkedMap_1.LinkedMap();
		            // Test for backwards compatibility
		            if (Is.func(messageWriter.dispose)) {
		                messageWriter.dispose();
		            }
		            if (Is.func(messageReader.dispose)) {
		                messageReader.dispose();
		            }
		        },
		        listen: () => {
		            throwIfClosedOrDisposed();
		            throwIfListening();
		            state = ConnectionState.Listening;
		            messageReader.listen(callback);
		        },
		        inspect: () => {
		            // eslint-disable-next-line no-console
		            (0, ral_1.default)().console.log('inspect');
		        }
		    };
		    connection.onNotification(LogTraceNotification.type, (params) => {
		        if (trace === Trace.Off || !tracer) {
		            return;
		        }
		        const verbose = trace === Trace.Verbose || trace === Trace.Compact;
		        tracer.log(params.message, verbose ? params.verbose : undefined);
		    });
		    connection.onNotification(ProgressNotification.type, (params) => {
		        const handler = progressHandlers.get(params.token);
		        if (handler) {
		            handler(params.value);
		        }
		        else {
		            unhandledProgressEmitter.fire(params);
		        }
		    });
		    return connection;
		}
		exports.createMessageConnection = createMessageConnection; 
	} (connection$1));
	return connection$1;
}

var hasRequiredApi;

function requireApi () {
	if (hasRequiredApi) return api$1;
	hasRequiredApi = 1;
	(function (exports) {
		/* --------------------------------------------------------------------------------------------
		 * Copyright (c) Microsoft Corporation. All rights reserved.
		 * Licensed under the MIT License. See License.txt in the project root for license information.
		 * ------------------------------------------------------------------------------------------ */
		/// <reference path="../../typings/thenable.d.ts" />
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = void 0;
		exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = void 0;
		const messages_1 = requireMessages();
		Object.defineProperty(exports, "Message", { enumerable: true, get: function () { return messages_1.Message; } });
		Object.defineProperty(exports, "RequestType", { enumerable: true, get: function () { return messages_1.RequestType; } });
		Object.defineProperty(exports, "RequestType0", { enumerable: true, get: function () { return messages_1.RequestType0; } });
		Object.defineProperty(exports, "RequestType1", { enumerable: true, get: function () { return messages_1.RequestType1; } });
		Object.defineProperty(exports, "RequestType2", { enumerable: true, get: function () { return messages_1.RequestType2; } });
		Object.defineProperty(exports, "RequestType3", { enumerable: true, get: function () { return messages_1.RequestType3; } });
		Object.defineProperty(exports, "RequestType4", { enumerable: true, get: function () { return messages_1.RequestType4; } });
		Object.defineProperty(exports, "RequestType5", { enumerable: true, get: function () { return messages_1.RequestType5; } });
		Object.defineProperty(exports, "RequestType6", { enumerable: true, get: function () { return messages_1.RequestType6; } });
		Object.defineProperty(exports, "RequestType7", { enumerable: true, get: function () { return messages_1.RequestType7; } });
		Object.defineProperty(exports, "RequestType8", { enumerable: true, get: function () { return messages_1.RequestType8; } });
		Object.defineProperty(exports, "RequestType9", { enumerable: true, get: function () { return messages_1.RequestType9; } });
		Object.defineProperty(exports, "ResponseError", { enumerable: true, get: function () { return messages_1.ResponseError; } });
		Object.defineProperty(exports, "ErrorCodes", { enumerable: true, get: function () { return messages_1.ErrorCodes; } });
		Object.defineProperty(exports, "NotificationType", { enumerable: true, get: function () { return messages_1.NotificationType; } });
		Object.defineProperty(exports, "NotificationType0", { enumerable: true, get: function () { return messages_1.NotificationType0; } });
		Object.defineProperty(exports, "NotificationType1", { enumerable: true, get: function () { return messages_1.NotificationType1; } });
		Object.defineProperty(exports, "NotificationType2", { enumerable: true, get: function () { return messages_1.NotificationType2; } });
		Object.defineProperty(exports, "NotificationType3", { enumerable: true, get: function () { return messages_1.NotificationType3; } });
		Object.defineProperty(exports, "NotificationType4", { enumerable: true, get: function () { return messages_1.NotificationType4; } });
		Object.defineProperty(exports, "NotificationType5", { enumerable: true, get: function () { return messages_1.NotificationType5; } });
		Object.defineProperty(exports, "NotificationType6", { enumerable: true, get: function () { return messages_1.NotificationType6; } });
		Object.defineProperty(exports, "NotificationType7", { enumerable: true, get: function () { return messages_1.NotificationType7; } });
		Object.defineProperty(exports, "NotificationType8", { enumerable: true, get: function () { return messages_1.NotificationType8; } });
		Object.defineProperty(exports, "NotificationType9", { enumerable: true, get: function () { return messages_1.NotificationType9; } });
		Object.defineProperty(exports, "ParameterStructures", { enumerable: true, get: function () { return messages_1.ParameterStructures; } });
		const linkedMap_1 = requireLinkedMap();
		Object.defineProperty(exports, "LinkedMap", { enumerable: true, get: function () { return linkedMap_1.LinkedMap; } });
		Object.defineProperty(exports, "LRUCache", { enumerable: true, get: function () { return linkedMap_1.LRUCache; } });
		Object.defineProperty(exports, "Touch", { enumerable: true, get: function () { return linkedMap_1.Touch; } });
		const disposable_1 = requireDisposable();
		Object.defineProperty(exports, "Disposable", { enumerable: true, get: function () { return disposable_1.Disposable; } });
		const events_1 = requireEvents();
		Object.defineProperty(exports, "Event", { enumerable: true, get: function () { return events_1.Event; } });
		Object.defineProperty(exports, "Emitter", { enumerable: true, get: function () { return events_1.Emitter; } });
		const cancellation_1 = requireCancellation();
		Object.defineProperty(exports, "CancellationTokenSource", { enumerable: true, get: function () { return cancellation_1.CancellationTokenSource; } });
		Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function () { return cancellation_1.CancellationToken; } });
		const sharedArrayCancellation_1 = requireSharedArrayCancellation();
		Object.defineProperty(exports, "SharedArraySenderStrategy", { enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArraySenderStrategy; } });
		Object.defineProperty(exports, "SharedArrayReceiverStrategy", { enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArrayReceiverStrategy; } });
		const messageReader_1 = requireMessageReader();
		Object.defineProperty(exports, "MessageReader", { enumerable: true, get: function () { return messageReader_1.MessageReader; } });
		Object.defineProperty(exports, "AbstractMessageReader", { enumerable: true, get: function () { return messageReader_1.AbstractMessageReader; } });
		Object.defineProperty(exports, "ReadableStreamMessageReader", { enumerable: true, get: function () { return messageReader_1.ReadableStreamMessageReader; } });
		const messageWriter_1 = requireMessageWriter();
		Object.defineProperty(exports, "MessageWriter", { enumerable: true, get: function () { return messageWriter_1.MessageWriter; } });
		Object.defineProperty(exports, "AbstractMessageWriter", { enumerable: true, get: function () { return messageWriter_1.AbstractMessageWriter; } });
		Object.defineProperty(exports, "WriteableStreamMessageWriter", { enumerable: true, get: function () { return messageWriter_1.WriteableStreamMessageWriter; } });
		const messageBuffer_1 = requireMessageBuffer();
		Object.defineProperty(exports, "AbstractMessageBuffer", { enumerable: true, get: function () { return messageBuffer_1.AbstractMessageBuffer; } });
		const connection_1 = requireConnection();
		Object.defineProperty(exports, "ConnectionStrategy", { enumerable: true, get: function () { return connection_1.ConnectionStrategy; } });
		Object.defineProperty(exports, "ConnectionOptions", { enumerable: true, get: function () { return connection_1.ConnectionOptions; } });
		Object.defineProperty(exports, "NullLogger", { enumerable: true, get: function () { return connection_1.NullLogger; } });
		Object.defineProperty(exports, "createMessageConnection", { enumerable: true, get: function () { return connection_1.createMessageConnection; } });
		Object.defineProperty(exports, "ProgressToken", { enumerable: true, get: function () { return connection_1.ProgressToken; } });
		Object.defineProperty(exports, "ProgressType", { enumerable: true, get: function () { return connection_1.ProgressType; } });
		Object.defineProperty(exports, "Trace", { enumerable: true, get: function () { return connection_1.Trace; } });
		Object.defineProperty(exports, "TraceValues", { enumerable: true, get: function () { return connection_1.TraceValues; } });
		Object.defineProperty(exports, "TraceFormat", { enumerable: true, get: function () { return connection_1.TraceFormat; } });
		Object.defineProperty(exports, "SetTraceNotification", { enumerable: true, get: function () { return connection_1.SetTraceNotification; } });
		Object.defineProperty(exports, "LogTraceNotification", { enumerable: true, get: function () { return connection_1.LogTraceNotification; } });
		Object.defineProperty(exports, "ConnectionErrors", { enumerable: true, get: function () { return connection_1.ConnectionErrors; } });
		Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return connection_1.ConnectionError; } });
		Object.defineProperty(exports, "CancellationReceiverStrategy", { enumerable: true, get: function () { return connection_1.CancellationReceiverStrategy; } });
		Object.defineProperty(exports, "CancellationSenderStrategy", { enumerable: true, get: function () { return connection_1.CancellationSenderStrategy; } });
		Object.defineProperty(exports, "CancellationStrategy", { enumerable: true, get: function () { return connection_1.CancellationStrategy; } });
		Object.defineProperty(exports, "MessageStrategy", { enumerable: true, get: function () { return connection_1.MessageStrategy; } });
		const ral_1 = requireRal();
		exports.RAL = ral_1.default; 
	} (api$1));
	return api$1;
}

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(ril, "__esModule", { value: true });
const api_1 = requireApi();
class MessageBuffer extends api_1.AbstractMessageBuffer {
    constructor(encoding = 'utf-8') {
        super(encoding);
        this.asciiDecoder = new TextDecoder('ascii');
    }
    emptyBuffer() {
        return MessageBuffer.emptyBuffer;
    }
    fromString(value, _encoding) {
        return (new TextEncoder()).encode(value);
    }
    toString(value, encoding) {
        if (encoding === 'ascii') {
            return this.asciiDecoder.decode(value);
        }
        else {
            return (new TextDecoder(encoding)).decode(value);
        }
    }
    asNative(buffer, length) {
        if (length === undefined) {
            return buffer;
        }
        else {
            return buffer.slice(0, length);
        }
    }
    allocNative(length) {
        return new Uint8Array(length);
    }
}
MessageBuffer.emptyBuffer = new Uint8Array(0);
class ReadableStreamWrapper {
    constructor(socket) {
        this.socket = socket;
        this._onData = new api_1.Emitter();
        this._messageListener = (event) => {
            const blob = event.data;
            blob.arrayBuffer().then((buffer) => {
                this._onData.fire(new Uint8Array(buffer));
            }, () => {
                (0, api_1.RAL)().console.error(`Converting blob to array buffer failed.`);
            });
        };
        this.socket.addEventListener('message', this._messageListener);
    }
    onClose(listener) {
        this.socket.addEventListener('close', listener);
        return api_1.Disposable.create(() => this.socket.removeEventListener('close', listener));
    }
    onError(listener) {
        this.socket.addEventListener('error', listener);
        return api_1.Disposable.create(() => this.socket.removeEventListener('error', listener));
    }
    onEnd(listener) {
        this.socket.addEventListener('end', listener);
        return api_1.Disposable.create(() => this.socket.removeEventListener('end', listener));
    }
    onData(listener) {
        return this._onData.event(listener);
    }
}
class WritableStreamWrapper {
    constructor(socket) {
        this.socket = socket;
    }
    onClose(listener) {
        this.socket.addEventListener('close', listener);
        return api_1.Disposable.create(() => this.socket.removeEventListener('close', listener));
    }
    onError(listener) {
        this.socket.addEventListener('error', listener);
        return api_1.Disposable.create(() => this.socket.removeEventListener('error', listener));
    }
    onEnd(listener) {
        this.socket.addEventListener('end', listener);
        return api_1.Disposable.create(() => this.socket.removeEventListener('end', listener));
    }
    write(data, encoding) {
        if (typeof data === 'string') {
            if (encoding !== undefined && encoding !== 'utf-8') {
                throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${encoding}`);
            }
            this.socket.send(data);
        }
        else {
            this.socket.send(data);
        }
        return Promise.resolve();
    }
    end() {
        this.socket.close();
    }
}
const _textEncoder = new TextEncoder();
const _ril = Object.freeze({
    messageBuffer: Object.freeze({
        create: (encoding) => new MessageBuffer(encoding)
    }),
    applicationJson: Object.freeze({
        encoder: Object.freeze({
            name: 'application/json',
            encode: (msg, options) => {
                if (options.charset !== 'utf-8') {
                    throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${options.charset}`);
                }
                return Promise.resolve(_textEncoder.encode(JSON.stringify(msg, undefined, 0)));
            }
        }),
        decoder: Object.freeze({
            name: 'application/json',
            decode: (buffer, options) => {
                if (!(buffer instanceof Uint8Array)) {
                    throw new Error(`In a Browser environments only Uint8Arrays are supported.`);
                }
                return Promise.resolve(JSON.parse(new TextDecoder(options.charset).decode(buffer)));
            }
        })
    }),
    stream: Object.freeze({
        asReadableStream: (socket) => new ReadableStreamWrapper(socket),
        asWritableStream: (socket) => new WritableStreamWrapper(socket)
    }),
    console: console,
    timer: Object.freeze({
        setTimeout(callback, ms, ...args) {
            const handle = setTimeout(callback, ms, ...args);
            return { dispose: () => clearTimeout(handle) };
        },
        setImmediate(callback, ...args) {
            const handle = setTimeout(callback, 0, ...args);
            return { dispose: () => clearTimeout(handle) };
        },
        setInterval(callback, ms, ...args) {
            const handle = setInterval(callback, ms, ...args);
            return { dispose: () => clearInterval(handle) };
        },
    })
});
function RIL() {
    return _ril;
}
(function (RIL) {
    function install() {
        api_1.RAL.install(_ril);
    }
    RIL.install = install;
})(RIL || (RIL = {}));
ril.default = RIL;

(function (exports) {
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	var __createBinding = (commonjsGlobal && commonjsGlobal.__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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
	    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.createMessageConnection = exports.BrowserMessageWriter = exports.BrowserMessageReader = void 0;
	const ril_1 = ril;
	// Install the browser runtime abstract.
	ril_1.default.install();
	const api_1 = requireApi();
	__exportStar(requireApi(), exports);
	class BrowserMessageReader extends api_1.AbstractMessageReader {
	    constructor(port) {
	        super();
	        this._onData = new api_1.Emitter();
	        this._messageListener = (event) => {
	            this._onData.fire(event.data);
	        };
	        port.addEventListener('error', (event) => this.fireError(event));
	        port.onmessage = this._messageListener;
	    }
	    listen(callback) {
	        return this._onData.event(callback);
	    }
	}
	exports.BrowserMessageReader = BrowserMessageReader;
	class BrowserMessageWriter extends api_1.AbstractMessageWriter {
	    constructor(port) {
	        super();
	        this.port = port;
	        this.errorCount = 0;
	        port.addEventListener('error', (event) => this.fireError(event));
	    }
	    write(msg) {
	        try {
	            this.port.postMessage(msg);
	            return Promise.resolve();
	        }
	        catch (error) {
	            this.handleError(error, msg);
	            return Promise.reject(error);
	        }
	    }
	    handleError(error, msg) {
	        this.errorCount++;
	        this.fireError(error, msg, this.errorCount);
	    }
	    end() {
	    }
	}
	exports.BrowserMessageWriter = BrowserMessageWriter;
	function createMessageConnection(reader, writer, logger, options) {
	    if (logger === undefined) {
	        logger = api_1.NullLogger;
	    }
	    if (api_1.ConnectionStrategy.is(options)) {
	        options = { connectionStrategy: options };
	    }
	    return (0, api_1.createMessageConnection)(reader, writer, logger, options);
	}
	exports.createMessageConnection = createMessageConnection; 
} (main$1));

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

var browser$1 = main$1;

var api = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
var DocumentUri;
(function (DocumentUri) {
    function is(value) {
        return typeof value === 'string';
    }
    DocumentUri.is = is;
})(DocumentUri || (DocumentUri = {}));
var URI;
(function (URI) {
    function is(value) {
        return typeof value === 'string';
    }
    URI.is = is;
})(URI || (URI = {}));
var integer;
(function (integer) {
    integer.MIN_VALUE = -2147483648;
    integer.MAX_VALUE = 2147483647;
    function is(value) {
        return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE;
    }
    integer.is = is;
})(integer || (integer = {}));
var uinteger;
(function (uinteger) {
    uinteger.MIN_VALUE = 0;
    uinteger.MAX_VALUE = 2147483647;
    function is(value) {
        return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE;
    }
    uinteger.is = is;
})(uinteger || (uinteger = {}));
/**
 * The Position namespace provides helper functions to work with
 * {@link Position} literals.
 */
var Position;
(function (Position) {
    /**
     * Creates a new Position literal from the given line and character.
     * @param line The position's line.
     * @param character The position's character.
     */
    function create(line, character) {
        if (line === Number.MAX_VALUE) {
            line = uinteger.MAX_VALUE;
        }
        if (character === Number.MAX_VALUE) {
            character = uinteger.MAX_VALUE;
        }
        return { line, character };
    }
    Position.create = create;
    /**
     * Checks whether the given literal conforms to the {@link Position} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.objectLiteral(candidate) && Is$4.uinteger(candidate.line) && Is$4.uinteger(candidate.character);
    }
    Position.is = is;
})(Position || (Position = {}));
/**
 * The Range namespace provides helper functions to work with
 * {@link Range} literals.
 */
var Range;
(function (Range) {
    function create(one, two, three, four) {
        if (Is$4.uinteger(one) && Is$4.uinteger(two) && Is$4.uinteger(three) && Is$4.uinteger(four)) {
            return { start: Position.create(one, two), end: Position.create(three, four) };
        }
        else if (Position.is(one) && Position.is(two)) {
            return { start: one, end: two };
        }
        else {
            throw new Error(`Range#create called with invalid arguments[${one}, ${two}, ${three}, ${four}]`);
        }
    }
    Range.create = create;
    /**
     * Checks whether the given literal conforms to the {@link Range} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
    }
    Range.is = is;
})(Range || (Range = {}));
/**
 * The Location namespace provides helper functions to work with
 * {@link Location} literals.
 */
var Location;
(function (Location) {
    /**
     * Creates a Location literal.
     * @param uri The location's uri.
     * @param range The location's range.
     */
    function create(uri, range) {
        return { uri, range };
    }
    Location.create = create;
    /**
     * Checks whether the given literal conforms to the {@link Location} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.objectLiteral(candidate) && Range.is(candidate.range) && (Is$4.string(candidate.uri) || Is$4.undefined(candidate.uri));
    }
    Location.is = is;
})(Location || (Location = {}));
/**
 * The LocationLink namespace provides helper functions to work with
 * {@link LocationLink} literals.
 */
var LocationLink;
(function (LocationLink) {
    /**
     * Creates a LocationLink literal.
     * @param targetUri The definition's uri.
     * @param targetRange The full range of the definition.
     * @param targetSelectionRange The span of the symbol definition at the target.
     * @param originSelectionRange The span of the symbol being defined in the originating source file.
     */
    function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
        return { targetUri, targetRange, targetSelectionRange, originSelectionRange };
    }
    LocationLink.create = create;
    /**
     * Checks whether the given literal conforms to the {@link LocationLink} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is$4.string(candidate.targetUri)
            && Range.is(candidate.targetSelectionRange)
            && (Range.is(candidate.originSelectionRange) || Is$4.undefined(candidate.originSelectionRange));
    }
    LocationLink.is = is;
})(LocationLink || (LocationLink = {}));
/**
 * The Color namespace provides helper functions to work with
 * {@link Color} literals.
 */
var Color;
(function (Color) {
    /**
     * Creates a new Color literal.
     */
    function create(red, green, blue, alpha) {
        return {
            red,
            green,
            blue,
            alpha,
        };
    }
    Color.create = create;
    /**
     * Checks whether the given literal conforms to the {@link Color} interface.
     */
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && Is$4.numberRange(candidate.red, 0, 1)
            && Is$4.numberRange(candidate.green, 0, 1)
            && Is$4.numberRange(candidate.blue, 0, 1)
            && Is$4.numberRange(candidate.alpha, 0, 1);
    }
    Color.is = is;
})(Color || (Color = {}));
/**
 * The ColorInformation namespace provides helper functions to work with
 * {@link ColorInformation} literals.
 */
var ColorInformation;
(function (ColorInformation) {
    /**
     * Creates a new ColorInformation literal.
     */
    function create(range, color) {
        return {
            range,
            color,
        };
    }
    ColorInformation.create = create;
    /**
     * Checks whether the given literal conforms to the {@link ColorInformation} interface.
     */
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);
    }
    ColorInformation.is = is;
})(ColorInformation || (ColorInformation = {}));
/**
 * The Color namespace provides helper functions to work with
 * {@link ColorPresentation} literals.
 */
var ColorPresentation;
(function (ColorPresentation) {
    /**
     * Creates a new ColorInformation literal.
     */
    function create(label, textEdit, additionalTextEdits) {
        return {
            label,
            textEdit,
            additionalTextEdits,
        };
    }
    ColorPresentation.create = create;
    /**
     * Checks whether the given literal conforms to the {@link ColorInformation} interface.
     */
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && Is$4.string(candidate.label)
            && (Is$4.undefined(candidate.textEdit) || TextEdit.is(candidate))
            && (Is$4.undefined(candidate.additionalTextEdits) || Is$4.typedArray(candidate.additionalTextEdits, TextEdit.is));
    }
    ColorPresentation.is = is;
})(ColorPresentation || (ColorPresentation = {}));
/**
 * A set of predefined range kinds.
 */
var FoldingRangeKind;
(function (FoldingRangeKind) {
    /**
     * Folding range for a comment
     */
    FoldingRangeKind.Comment = 'comment';
    /**
     * Folding range for an import or include
     */
    FoldingRangeKind.Imports = 'imports';
    /**
     * Folding range for a region (e.g. `#region`)
     */
    FoldingRangeKind.Region = 'region';
})(FoldingRangeKind || (FoldingRangeKind = {}));
/**
 * The folding range namespace provides helper functions to work with
 * {@link FoldingRange} literals.
 */
var FoldingRange;
(function (FoldingRange) {
    /**
     * Creates a new FoldingRange literal.
     */
    function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {
        const result = {
            startLine,
            endLine
        };
        if (Is$4.defined(startCharacter)) {
            result.startCharacter = startCharacter;
        }
        if (Is$4.defined(endCharacter)) {
            result.endCharacter = endCharacter;
        }
        if (Is$4.defined(kind)) {
            result.kind = kind;
        }
        if (Is$4.defined(collapsedText)) {
            result.collapsedText = collapsedText;
        }
        return result;
    }
    FoldingRange.create = create;
    /**
     * Checks whether the given literal conforms to the {@link FoldingRange} interface.
     */
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && Is$4.uinteger(candidate.startLine) && Is$4.uinteger(candidate.startLine)
            && (Is$4.undefined(candidate.startCharacter) || Is$4.uinteger(candidate.startCharacter))
            && (Is$4.undefined(candidate.endCharacter) || Is$4.uinteger(candidate.endCharacter))
            && (Is$4.undefined(candidate.kind) || Is$4.string(candidate.kind));
    }
    FoldingRange.is = is;
})(FoldingRange || (FoldingRange = {}));
/**
 * The DiagnosticRelatedInformation namespace provides helper functions to work with
 * {@link DiagnosticRelatedInformation} literals.
 */
var DiagnosticRelatedInformation;
(function (DiagnosticRelatedInformation) {
    /**
     * Creates a new DiagnosticRelatedInformation literal.
     */
    function create(location, message) {
        return {
            location,
            message
        };
    }
    DiagnosticRelatedInformation.create = create;
    /**
     * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Location.is(candidate.location) && Is$4.string(candidate.message);
    }
    DiagnosticRelatedInformation.is = is;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
/**
 * The diagnostic's severity.
 */
var DiagnosticSeverity;
(function (DiagnosticSeverity) {
    /**
     * Reports an error.
     */
    DiagnosticSeverity.Error = 1;
    /**
     * Reports a warning.
     */
    DiagnosticSeverity.Warning = 2;
    /**
     * Reports an information.
     */
    DiagnosticSeverity.Information = 3;
    /**
     * Reports a hint.
     */
    DiagnosticSeverity.Hint = 4;
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
/**
 * The diagnostic tags.
 *
 * @since 3.15.0
 */
var DiagnosticTag;
(function (DiagnosticTag) {
    /**
     * Unused or unnecessary code.
     *
     * Clients are allowed to render diagnostics with this tag faded out instead of having
     * an error squiggle.
     */
    DiagnosticTag.Unnecessary = 1;
    /**
     * Deprecated or obsolete code.
     *
     * Clients are allowed to rendered diagnostics with this tag strike through.
     */
    DiagnosticTag.Deprecated = 2;
})(DiagnosticTag || (DiagnosticTag = {}));
/**
 * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes.
 *
 * @since 3.16.0
 */
var CodeDescription;
(function (CodeDescription) {
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && Is$4.string(candidate.href);
    }
    CodeDescription.is = is;
})(CodeDescription || (CodeDescription = {}));
/**
 * The Diagnostic namespace provides helper functions to work with
 * {@link Diagnostic} literals.
 */
var Diagnostic;
(function (Diagnostic) {
    /**
     * Creates a new Diagnostic literal.
     */
    function create(range, message, severity, code, source, relatedInformation) {
        let result = { range, message };
        if (Is$4.defined(severity)) {
            result.severity = severity;
        }
        if (Is$4.defined(code)) {
            result.code = code;
        }
        if (Is$4.defined(source)) {
            result.source = source;
        }
        if (Is$4.defined(relatedInformation)) {
            result.relatedInformation = relatedInformation;
        }
        return result;
    }
    Diagnostic.create = create;
    /**
     * Checks whether the given literal conforms to the {@link Diagnostic} interface.
     */
    function is(value) {
        var _a;
        let candidate = value;
        return Is$4.defined(candidate)
            && Range.is(candidate.range)
            && Is$4.string(candidate.message)
            && (Is$4.number(candidate.severity) || Is$4.undefined(candidate.severity))
            && (Is$4.integer(candidate.code) || Is$4.string(candidate.code) || Is$4.undefined(candidate.code))
            && (Is$4.undefined(candidate.codeDescription) || (Is$4.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)))
            && (Is$4.string(candidate.source) || Is$4.undefined(candidate.source))
            && (Is$4.undefined(candidate.relatedInformation) || Is$4.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
    }
    Diagnostic.is = is;
})(Diagnostic || (Diagnostic = {}));
/**
 * The Command namespace provides helper functions to work with
 * {@link Command} literals.
 */
var Command;
(function (Command) {
    /**
     * Creates a new Command literal.
     */
    function create(title, command, ...args) {
        let result = { title, command };
        if (Is$4.defined(args) && args.length > 0) {
            result.arguments = args;
        }
        return result;
    }
    Command.create = create;
    /**
     * Checks whether the given literal conforms to the {@link Command} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Is$4.string(candidate.title) && Is$4.string(candidate.command);
    }
    Command.is = is;
})(Command || (Command = {}));
/**
 * The TextEdit namespace provides helper function to create replace,
 * insert and delete edits more easily.
 */
var TextEdit;
(function (TextEdit) {
    /**
     * Creates a replace text edit.
     * @param range The range of text to be replaced.
     * @param newText The new text.
     */
    function replace(range, newText) {
        return { range, newText };
    }
    TextEdit.replace = replace;
    /**
     * Creates an insert text edit.
     * @param position The position to insert the text at.
     * @param newText The text to be inserted.
     */
    function insert(position, newText) {
        return { range: { start: position, end: position }, newText };
    }
    TextEdit.insert = insert;
    /**
     * Creates a delete text edit.
     * @param range The range of text to be deleted.
     */
    function del(range) {
        return { range, newText: '' };
    }
    TextEdit.del = del;
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate)
            && Is$4.string(candidate.newText)
            && Range.is(candidate.range);
    }
    TextEdit.is = is;
})(TextEdit || (TextEdit = {}));
var ChangeAnnotation;
(function (ChangeAnnotation) {
    function create(label, needsConfirmation, description) {
        const result = { label };
        if (needsConfirmation !== undefined) {
            result.needsConfirmation = needsConfirmation;
        }
        if (description !== undefined) {
            result.description = description;
        }
        return result;
    }
    ChangeAnnotation.create = create;
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && Is$4.string(candidate.label) &&
            (Is$4.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) &&
            (Is$4.string(candidate.description) || candidate.description === undefined);
    }
    ChangeAnnotation.is = is;
})(ChangeAnnotation || (ChangeAnnotation = {}));
var ChangeAnnotationIdentifier;
(function (ChangeAnnotationIdentifier) {
    function is(value) {
        const candidate = value;
        return Is$4.string(candidate);
    }
    ChangeAnnotationIdentifier.is = is;
})(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {}));
var AnnotatedTextEdit;
(function (AnnotatedTextEdit) {
    /**
     * Creates an annotated replace text edit.
     *
     * @param range The range of text to be replaced.
     * @param newText The new text.
     * @param annotation The annotation.
     */
    function replace(range, newText, annotation) {
        return { range, newText, annotationId: annotation };
    }
    AnnotatedTextEdit.replace = replace;
    /**
     * Creates an annotated insert text edit.
     *
     * @param position The position to insert the text at.
     * @param newText The text to be inserted.
     * @param annotation The annotation.
     */
    function insert(position, newText, annotation) {
        return { range: { start: position, end: position }, newText, annotationId: annotation };
    }
    AnnotatedTextEdit.insert = insert;
    /**
     * Creates an annotated delete text edit.
     *
     * @param range The range of text to be deleted.
     * @param annotation The annotation.
     */
    function del(range, annotation) {
        return { range, newText: '', annotationId: annotation };
    }
    AnnotatedTextEdit.del = del;
    function is(value) {
        const candidate = value;
        return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
    }
    AnnotatedTextEdit.is = is;
})(AnnotatedTextEdit || (AnnotatedTextEdit = {}));
/**
 * The TextDocumentEdit namespace provides helper function to create
 * an edit that manipulates a text document.
 */
var TextDocumentEdit;
(function (TextDocumentEdit) {
    /**
     * Creates a new `TextDocumentEdit`
     */
    function create(textDocument, edits) {
        return { textDocument, edits };
    }
    TextDocumentEdit.create = create;
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate)
            && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument)
            && Array.isArray(candidate.edits);
    }
    TextDocumentEdit.is = is;
})(TextDocumentEdit || (TextDocumentEdit = {}));
var CreateFile;
(function (CreateFile) {
    function create(uri, options, annotation) {
        let result = {
            kind: 'create',
            uri
        };
        if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
            result.options = options;
        }
        if (annotation !== undefined) {
            result.annotationId = annotation;
        }
        return result;
    }
    CreateFile.create = create;
    function is(value) {
        let candidate = value;
        return candidate && candidate.kind === 'create' && Is$4.string(candidate.uri) && (candidate.options === undefined ||
            ((candidate.options.overwrite === undefined || Is$4.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is$4.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
    }
    CreateFile.is = is;
})(CreateFile || (CreateFile = {}));
var RenameFile;
(function (RenameFile) {
    function create(oldUri, newUri, options, annotation) {
        let result = {
            kind: 'rename',
            oldUri,
            newUri
        };
        if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
            result.options = options;
        }
        if (annotation !== undefined) {
            result.annotationId = annotation;
        }
        return result;
    }
    RenameFile.create = create;
    function is(value) {
        let candidate = value;
        return candidate && candidate.kind === 'rename' && Is$4.string(candidate.oldUri) && Is$4.string(candidate.newUri) && (candidate.options === undefined ||
            ((candidate.options.overwrite === undefined || Is$4.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is$4.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
    }
    RenameFile.is = is;
})(RenameFile || (RenameFile = {}));
var DeleteFile;
(function (DeleteFile) {
    function create(uri, options, annotation) {
        let result = {
            kind: 'delete',
            uri
        };
        if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) {
            result.options = options;
        }
        if (annotation !== undefined) {
            result.annotationId = annotation;
        }
        return result;
    }
    DeleteFile.create = create;
    function is(value) {
        let candidate = value;
        return candidate && candidate.kind === 'delete' && Is$4.string(candidate.uri) && (candidate.options === undefined ||
            ((candidate.options.recursive === undefined || Is$4.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is$4.boolean(candidate.options.ignoreIfNotExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
    }
    DeleteFile.is = is;
})(DeleteFile || (DeleteFile = {}));
var WorkspaceEdit;
(function (WorkspaceEdit) {
    function is(value) {
        let candidate = value;
        return candidate &&
            (candidate.changes !== undefined || candidate.documentChanges !== undefined) &&
            (candidate.documentChanges === undefined || candidate.documentChanges.every((change) => {
                if (Is$4.string(change.kind)) {
                    return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
                }
                else {
                    return TextDocumentEdit.is(change);
                }
            }));
    }
    WorkspaceEdit.is = is;
})(WorkspaceEdit || (WorkspaceEdit = {}));
class TextEditChangeImpl {
    constructor(edits, changeAnnotations) {
        this.edits = edits;
        this.changeAnnotations = changeAnnotations;
    }
    insert(position, newText, annotation) {
        let edit;
        let id;
        if (annotation === undefined) {
            edit = TextEdit.insert(position, newText);
        }
        else if (ChangeAnnotationIdentifier.is(annotation)) {
            id = annotation;
            edit = AnnotatedTextEdit.insert(position, newText, annotation);
        }
        else {
            this.assertChangeAnnotations(this.changeAnnotations);
            id = this.changeAnnotations.manage(annotation);
            edit = AnnotatedTextEdit.insert(position, newText, id);
        }
        this.edits.push(edit);
        if (id !== undefined) {
            return id;
        }
    }
    replace(range, newText, annotation) {
        let edit;
        let id;
        if (annotation === undefined) {
            edit = TextEdit.replace(range, newText);
        }
        else if (ChangeAnnotationIdentifier.is(annotation)) {
            id = annotation;
            edit = AnnotatedTextEdit.replace(range, newText, annotation);
        }
        else {
            this.assertChangeAnnotations(this.changeAnnotations);
            id = this.changeAnnotations.manage(annotation);
            edit = AnnotatedTextEdit.replace(range, newText, id);
        }
        this.edits.push(edit);
        if (id !== undefined) {
            return id;
        }
    }
    delete(range, annotation) {
        let edit;
        let id;
        if (annotation === undefined) {
            edit = TextEdit.del(range);
        }
        else if (ChangeAnnotationIdentifier.is(annotation)) {
            id = annotation;
            edit = AnnotatedTextEdit.del(range, annotation);
        }
        else {
            this.assertChangeAnnotations(this.changeAnnotations);
            id = this.changeAnnotations.manage(annotation);
            edit = AnnotatedTextEdit.del(range, id);
        }
        this.edits.push(edit);
        if (id !== undefined) {
            return id;
        }
    }
    add(edit) {
        this.edits.push(edit);
    }
    all() {
        return this.edits;
    }
    clear() {
        this.edits.splice(0, this.edits.length);
    }
    assertChangeAnnotations(value) {
        if (value === undefined) {
            throw new Error(`Text edit change is not configured to manage change annotations.`);
        }
    }
}
/**
 * A helper class
 */
class ChangeAnnotations {
    constructor(annotations) {
        this._annotations = annotations === undefined ? Object.create(null) : annotations;
        this._counter = 0;
        this._size = 0;
    }
    all() {
        return this._annotations;
    }
    get size() {
        return this._size;
    }
    manage(idOrAnnotation, annotation) {
        let id;
        if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {
            id = idOrAnnotation;
        }
        else {
            id = this.nextId();
            annotation = idOrAnnotation;
        }
        if (this._annotations[id] !== undefined) {
            throw new Error(`Id ${id} is already in use.`);
        }
        if (annotation === undefined) {
            throw new Error(`No annotation provided for id ${id}`);
        }
        this._annotations[id] = annotation;
        this._size++;
        return id;
    }
    nextId() {
        this._counter++;
        return this._counter.toString();
    }
}
/**
 * A workspace change helps constructing changes to a workspace.
 */
class WorkspaceChange {
    constructor(workspaceEdit) {
        this._textEditChanges = Object.create(null);
        if (workspaceEdit !== undefined) {
            this._workspaceEdit = workspaceEdit;
            if (workspaceEdit.documentChanges) {
                this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
                workspaceEdit.changeAnnotations = this._changeAnnotations.all();
                workspaceEdit.documentChanges.forEach((change) => {
                    if (TextDocumentEdit.is(change)) {
                        const textEditChange = new TextEditChangeImpl(change.edits, this._changeAnnotations);
                        this._textEditChanges[change.textDocument.uri] = textEditChange;
                    }
                });
            }
            else if (workspaceEdit.changes) {
                Object.keys(workspaceEdit.changes).forEach((key) => {
                    const textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
                    this._textEditChanges[key] = textEditChange;
                });
            }
        }
        else {
            this._workspaceEdit = {};
        }
    }
    /**
     * Returns the underlying {@link WorkspaceEdit} literal
     * use to be returned from a workspace edit operation like rename.
     */
    get edit() {
        this.initDocumentChanges();
        if (this._changeAnnotations !== undefined) {
            if (this._changeAnnotations.size === 0) {
                this._workspaceEdit.changeAnnotations = undefined;
            }
            else {
                this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
            }
        }
        return this._workspaceEdit;
    }
    getTextEditChange(key) {
        if (OptionalVersionedTextDocumentIdentifier.is(key)) {
            this.initDocumentChanges();
            if (this._workspaceEdit.documentChanges === undefined) {
                throw new Error('Workspace edit is not configured for document changes.');
            }
            const textDocument = { uri: key.uri, version: key.version };
            let result = this._textEditChanges[textDocument.uri];
            if (!result) {
                const edits = [];
                const textDocumentEdit = {
                    textDocument,
                    edits
                };
                this._workspaceEdit.documentChanges.push(textDocumentEdit);
                result = new TextEditChangeImpl(edits, this._changeAnnotations);
                this._textEditChanges[textDocument.uri] = result;
            }
            return result;
        }
        else {
            this.initChanges();
            if (this._workspaceEdit.changes === undefined) {
                throw new Error('Workspace edit is not configured for normal text edit changes.');
            }
            let result = this._textEditChanges[key];
            if (!result) {
                let edits = [];
                this._workspaceEdit.changes[key] = edits;
                result = new TextEditChangeImpl(edits);
                this._textEditChanges[key] = result;
            }
            return result;
        }
    }
    initDocumentChanges() {
        if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
            this._changeAnnotations = new ChangeAnnotations();
            this._workspaceEdit.documentChanges = [];
            this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
        }
    }
    initChanges() {
        if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
            this._workspaceEdit.changes = Object.create(null);
        }
    }
    createFile(uri, optionsOrAnnotation, options) {
        this.initDocumentChanges();
        if (this._workspaceEdit.documentChanges === undefined) {
            throw new Error('Workspace edit is not configured for document changes.');
        }
        let annotation;
        if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
            annotation = optionsOrAnnotation;
        }
        else {
            options = optionsOrAnnotation;
        }
        let operation;
        let id;
        if (annotation === undefined) {
            operation = CreateFile.create(uri, options);
        }
        else {
            id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
            operation = CreateFile.create(uri, options, id);
        }
        this._workspaceEdit.documentChanges.push(operation);
        if (id !== undefined) {
            return id;
        }
    }
    renameFile(oldUri, newUri, optionsOrAnnotation, options) {
        this.initDocumentChanges();
        if (this._workspaceEdit.documentChanges === undefined) {
            throw new Error('Workspace edit is not configured for document changes.');
        }
        let annotation;
        if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
            annotation = optionsOrAnnotation;
        }
        else {
            options = optionsOrAnnotation;
        }
        let operation;
        let id;
        if (annotation === undefined) {
            operation = RenameFile.create(oldUri, newUri, options);
        }
        else {
            id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
            operation = RenameFile.create(oldUri, newUri, options, id);
        }
        this._workspaceEdit.documentChanges.push(operation);
        if (id !== undefined) {
            return id;
        }
    }
    deleteFile(uri, optionsOrAnnotation, options) {
        this.initDocumentChanges();
        if (this._workspaceEdit.documentChanges === undefined) {
            throw new Error('Workspace edit is not configured for document changes.');
        }
        let annotation;
        if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
            annotation = optionsOrAnnotation;
        }
        else {
            options = optionsOrAnnotation;
        }
        let operation;
        let id;
        if (annotation === undefined) {
            operation = DeleteFile.create(uri, options);
        }
        else {
            id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
            operation = DeleteFile.create(uri, options, id);
        }
        this._workspaceEdit.documentChanges.push(operation);
        if (id !== undefined) {
            return id;
        }
    }
}
/**
 * The TextDocumentIdentifier namespace provides helper functions to work with
 * {@link TextDocumentIdentifier} literals.
 */
var TextDocumentIdentifier;
(function (TextDocumentIdentifier) {
    /**
     * Creates a new TextDocumentIdentifier literal.
     * @param uri The document's uri.
     */
    function create(uri) {
        return { uri };
    }
    TextDocumentIdentifier.create = create;
    /**
     * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Is$4.string(candidate.uri);
    }
    TextDocumentIdentifier.is = is;
})(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
/**
 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
 * {@link VersionedTextDocumentIdentifier} literals.
 */
var VersionedTextDocumentIdentifier;
(function (VersionedTextDocumentIdentifier) {
    /**
     * Creates a new VersionedTextDocumentIdentifier literal.
     * @param uri The document's uri.
     * @param version The document's version.
     */
    function create(uri, version) {
        return { uri, version };
    }
    VersionedTextDocumentIdentifier.create = create;
    /**
     * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Is$4.string(candidate.uri) && Is$4.integer(candidate.version);
    }
    VersionedTextDocumentIdentifier.is = is;
})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
/**
 * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with
 * {@link OptionalVersionedTextDocumentIdentifier} literals.
 */
var OptionalVersionedTextDocumentIdentifier;
(function (OptionalVersionedTextDocumentIdentifier) {
    /**
     * Creates a new OptionalVersionedTextDocumentIdentifier literal.
     * @param uri The document's uri.
     * @param version The document's version.
     */
    function create(uri, version) {
        return { uri, version };
    }
    OptionalVersionedTextDocumentIdentifier.create = create;
    /**
     * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Is$4.string(candidate.uri) && (candidate.version === null || Is$4.integer(candidate.version));
    }
    OptionalVersionedTextDocumentIdentifier.is = is;
})(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {}));
/**
 * The TextDocumentItem namespace provides helper functions to work with
 * {@link TextDocumentItem} literals.
 */
var TextDocumentItem;
(function (TextDocumentItem) {
    /**
     * Creates a new TextDocumentItem literal.
     * @param uri The document's uri.
     * @param languageId The document's language identifier.
     * @param version The document's version number.
     * @param text The document's text.
     */
    function create(uri, languageId, version, text) {
        return { uri, languageId, version, text };
    }
    TextDocumentItem.create = create;
    /**
     * Checks whether the given literal conforms to the {@link TextDocumentItem} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Is$4.string(candidate.uri) && Is$4.string(candidate.languageId) && Is$4.integer(candidate.version) && Is$4.string(candidate.text);
    }
    TextDocumentItem.is = is;
})(TextDocumentItem || (TextDocumentItem = {}));
/**
 * Describes the content type that a client supports in various
 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
 *
 * Please note that `MarkupKinds` must not start with a `$`. This kinds
 * are reserved for internal usage.
 */
var MarkupKind;
(function (MarkupKind) {
    /**
     * Plain text is supported as a content format
     */
    MarkupKind.PlainText = 'plaintext';
    /**
     * Markdown is supported as a content format
     */
    MarkupKind.Markdown = 'markdown';
    /**
     * Checks whether the given value is a value of the {@link MarkupKind} type.
     */
    function is(value) {
        const candidate = value;
        return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
    }
    MarkupKind.is = is;
})(MarkupKind || (MarkupKind = {}));
var MarkupContent;
(function (MarkupContent) {
    /**
     * Checks whether the given value conforms to the {@link MarkupContent} interface.
     */
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is$4.string(candidate.value);
    }
    MarkupContent.is = is;
})(MarkupContent || (MarkupContent = {}));
/**
 * The kind of a completion entry.
 */
var CompletionItemKind;
(function (CompletionItemKind) {
    CompletionItemKind.Text = 1;
    CompletionItemKind.Method = 2;
    CompletionItemKind.Function = 3;
    CompletionItemKind.Constructor = 4;
    CompletionItemKind.Field = 5;
    CompletionItemKind.Variable = 6;
    CompletionItemKind.Class = 7;
    CompletionItemKind.Interface = 8;
    CompletionItemKind.Module = 9;
    CompletionItemKind.Property = 10;
    CompletionItemKind.Unit = 11;
    CompletionItemKind.Value = 12;
    CompletionItemKind.Enum = 13;
    CompletionItemKind.Keyword = 14;
    CompletionItemKind.Snippet = 15;
    CompletionItemKind.Color = 16;
    CompletionItemKind.File = 17;
    CompletionItemKind.Reference = 18;
    CompletionItemKind.Folder = 19;
    CompletionItemKind.EnumMember = 20;
    CompletionItemKind.Constant = 21;
    CompletionItemKind.Struct = 22;
    CompletionItemKind.Event = 23;
    CompletionItemKind.Operator = 24;
    CompletionItemKind.TypeParameter = 25;
})(CompletionItemKind || (CompletionItemKind = {}));
/**
 * Defines whether the insert text in a completion item should be interpreted as
 * plain text or a snippet.
 */
var InsertTextFormat;
(function (InsertTextFormat) {
    /**
     * The primary text to be inserted is treated as a plain string.
     */
    InsertTextFormat.PlainText = 1;
    /**
     * The primary text to be inserted is treated as a snippet.
     *
     * A snippet can define tab stops and placeholders with `$1`, `$2`
     * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
     * the end of the snippet. Placeholders with equal identifiers are linked,
     * that is typing in one will update others too.
     *
     * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax
     */
    InsertTextFormat.Snippet = 2;
})(InsertTextFormat || (InsertTextFormat = {}));
/**
 * Completion item tags are extra annotations that tweak the rendering of a completion
 * item.
 *
 * @since 3.15.0
 */
var CompletionItemTag;
(function (CompletionItemTag) {
    /**
     * Render a completion as obsolete, usually using a strike-out.
     */
    CompletionItemTag.Deprecated = 1;
})(CompletionItemTag || (CompletionItemTag = {}));
/**
 * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits.
 *
 * @since 3.16.0
 */
var InsertReplaceEdit;
(function (InsertReplaceEdit) {
    /**
     * Creates a new insert / replace edit
     */
    function create(newText, insert, replace) {
        return { newText, insert, replace };
    }
    InsertReplaceEdit.create = create;
    /**
     * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface.
     */
    function is(value) {
        const candidate = value;
        return candidate && Is$4.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
    }
    InsertReplaceEdit.is = is;
})(InsertReplaceEdit || (InsertReplaceEdit = {}));
/**
 * How whitespace and indentation is handled during completion
 * item insertion.
 *
 * @since 3.16.0
 */
var InsertTextMode;
(function (InsertTextMode) {
    /**
     * The insertion or replace strings is taken as it is. If the
     * value is multi line the lines below the cursor will be
     * inserted using the indentation defined in the string value.
     * The client will not apply any kind of adjustments to the
     * string.
     */
    InsertTextMode.asIs = 1;
    /**
     * The editor adjusts leading whitespace of new lines so that
     * they match the indentation up to the cursor of the line for
     * which the item is accepted.
     *
     * Consider a line like this: <2tabs><cursor><3tabs>foo. Accepting a
     * multi line completion item is indented using 2 tabs and all
     * following lines inserted will be indented using 2 tabs as well.
     */
    InsertTextMode.adjustIndentation = 2;
})(InsertTextMode || (InsertTextMode = {}));
var CompletionItemLabelDetails;
(function (CompletionItemLabelDetails) {
    function is(value) {
        const candidate = value;
        return candidate && (Is$4.string(candidate.detail) || candidate.detail === undefined) &&
            (Is$4.string(candidate.description) || candidate.description === undefined);
    }
    CompletionItemLabelDetails.is = is;
})(CompletionItemLabelDetails || (CompletionItemLabelDetails = {}));
/**
 * The CompletionItem namespace provides functions to deal with
 * completion items.
 */
var CompletionItem;
(function (CompletionItem) {
    /**
     * Create a completion item and seed it with a label.
     * @param label The completion item's label
     */
    function create(label) {
        return { label };
    }
    CompletionItem.create = create;
})(CompletionItem || (CompletionItem = {}));
/**
 * The CompletionList namespace provides functions to deal with
 * completion lists.
 */
var CompletionList;
(function (CompletionList) {
    /**
     * Creates a new completion list.
     *
     * @param items The completion items.
     * @param isIncomplete The list is not complete.
     */
    function create(items, isIncomplete) {
        return { items: items ? items : [], isIncomplete: !!isIncomplete };
    }
    CompletionList.create = create;
})(CompletionList || (CompletionList = {}));
var MarkedString;
(function (MarkedString) {
    /**
     * Creates a marked string from plain text.
     *
     * @param plainText The plain text.
     */
    function fromPlainText(plainText) {
        return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
    }
    MarkedString.fromPlainText = fromPlainText;
    /**
     * Checks whether the given value conforms to the {@link MarkedString} type.
     */
    function is(value) {
        const candidate = value;
        return Is$4.string(candidate) || (Is$4.objectLiteral(candidate) && Is$4.string(candidate.language) && Is$4.string(candidate.value));
    }
    MarkedString.is = is;
})(MarkedString || (MarkedString = {}));
var Hover;
(function (Hover) {
    /**
     * Checks whether the given value conforms to the {@link Hover} interface.
     */
    function is(value) {
        let candidate = value;
        return !!candidate && Is$4.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
            MarkedString.is(candidate.contents) ||
            Is$4.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range));
    }
    Hover.is = is;
})(Hover || (Hover = {}));
/**
 * The ParameterInformation namespace provides helper functions to work with
 * {@link ParameterInformation} literals.
 */
var ParameterInformation;
(function (ParameterInformation) {
    /**
     * Creates a new parameter information literal.
     *
     * @param label A label string.
     * @param documentation A doc string.
     */
    function create(label, documentation) {
        return documentation ? { label, documentation } : { label };
    }
    ParameterInformation.create = create;
})(ParameterInformation || (ParameterInformation = {}));
/**
 * The SignatureInformation namespace provides helper functions to work with
 * {@link SignatureInformation} literals.
 */
var SignatureInformation;
(function (SignatureInformation) {
    function create(label, documentation, ...parameters) {
        let result = { label };
        if (Is$4.defined(documentation)) {
            result.documentation = documentation;
        }
        if (Is$4.defined(parameters)) {
            result.parameters = parameters;
        }
        else {
            result.parameters = [];
        }
        return result;
    }
    SignatureInformation.create = create;
})(SignatureInformation || (SignatureInformation = {}));
/**
 * A document highlight kind.
 */
var DocumentHighlightKind;
(function (DocumentHighlightKind) {
    /**
     * A textual occurrence.
     */
    DocumentHighlightKind.Text = 1;
    /**
     * Read-access of a symbol, like reading a variable.
     */
    DocumentHighlightKind.Read = 2;
    /**
     * Write-access of a symbol, like writing to a variable.
     */
    DocumentHighlightKind.Write = 3;
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
/**
 * DocumentHighlight namespace to provide helper functions to work with
 * {@link DocumentHighlight} literals.
 */
var DocumentHighlight;
(function (DocumentHighlight) {
    /**
     * Create a DocumentHighlight object.
     * @param range The range the highlight applies to.
     * @param kind The highlight kind
     */
    function create(range, kind) {
        let result = { range };
        if (Is$4.number(kind)) {
            result.kind = kind;
        }
        return result;
    }
    DocumentHighlight.create = create;
})(DocumentHighlight || (DocumentHighlight = {}));
/**
 * A symbol kind.
 */
var SymbolKind;
(function (SymbolKind) {
    SymbolKind.File = 1;
    SymbolKind.Module = 2;
    SymbolKind.Namespace = 3;
    SymbolKind.Package = 4;
    SymbolKind.Class = 5;
    SymbolKind.Method = 6;
    SymbolKind.Property = 7;
    SymbolKind.Field = 8;
    SymbolKind.Constructor = 9;
    SymbolKind.Enum = 10;
    SymbolKind.Interface = 11;
    SymbolKind.Function = 12;
    SymbolKind.Variable = 13;
    SymbolKind.Constant = 14;
    SymbolKind.String = 15;
    SymbolKind.Number = 16;
    SymbolKind.Boolean = 17;
    SymbolKind.Array = 18;
    SymbolKind.Object = 19;
    SymbolKind.Key = 20;
    SymbolKind.Null = 21;
    SymbolKind.EnumMember = 22;
    SymbolKind.Struct = 23;
    SymbolKind.Event = 24;
    SymbolKind.Operator = 25;
    SymbolKind.TypeParameter = 26;
})(SymbolKind || (SymbolKind = {}));
/**
 * Symbol tags are extra annotations that tweak the rendering of a symbol.
 *
 * @since 3.16
 */
var SymbolTag;
(function (SymbolTag) {
    /**
     * Render a symbol as obsolete, usually using a strike-out.
     */
    SymbolTag.Deprecated = 1;
})(SymbolTag || (SymbolTag = {}));
var SymbolInformation;
(function (SymbolInformation) {
    /**
     * Creates a new symbol information literal.
     *
     * @param name The name of the symbol.
     * @param kind The kind of the symbol.
     * @param range The range of the location of the symbol.
     * @param uri The resource of the location of symbol.
     * @param containerName The name of the symbol containing the symbol.
     */
    function create(name, kind, range, uri, containerName) {
        let result = {
            name,
            kind,
            location: { uri, range }
        };
        if (containerName) {
            result.containerName = containerName;
        }
        return result;
    }
    SymbolInformation.create = create;
})(SymbolInformation || (SymbolInformation = {}));
var WorkspaceSymbol;
(function (WorkspaceSymbol) {
    /**
     * Create a new workspace symbol.
     *
     * @param name The name of the symbol.
     * @param kind The kind of the symbol.
     * @param uri The resource of the location of the symbol.
     * @param range An options range of the location.
     * @returns A WorkspaceSymbol.
     */
    function create(name, kind, uri, range) {
        return range !== undefined
            ? { name, kind, location: { uri, range } }
            : { name, kind, location: { uri } };
    }
    WorkspaceSymbol.create = create;
})(WorkspaceSymbol || (WorkspaceSymbol = {}));
var DocumentSymbol;
(function (DocumentSymbol) {
    /**
     * Creates a new symbol information literal.
     *
     * @param name The name of the symbol.
     * @param detail The detail of the symbol.
     * @param kind The kind of the symbol.
     * @param range The range of the symbol.
     * @param selectionRange The selectionRange of the symbol.
     * @param children Children of the symbol.
     */
    function create(name, detail, kind, range, selectionRange, children) {
        let result = {
            name,
            detail,
            kind,
            range,
            selectionRange
        };
        if (children !== undefined) {
            result.children = children;
        }
        return result;
    }
    DocumentSymbol.create = create;
    /**
     * Checks whether the given literal conforms to the {@link DocumentSymbol} interface.
     */
    function is(value) {
        let candidate = value;
        return candidate &&
            Is$4.string(candidate.name) && Is$4.number(candidate.kind) &&
            Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
            (candidate.detail === undefined || Is$4.string(candidate.detail)) &&
            (candidate.deprecated === undefined || Is$4.boolean(candidate.deprecated)) &&
            (candidate.children === undefined || Array.isArray(candidate.children)) &&
            (candidate.tags === undefined || Array.isArray(candidate.tags));
    }
    DocumentSymbol.is = is;
})(DocumentSymbol || (DocumentSymbol = {}));
/**
 * A set of predefined code action kinds
 */
var CodeActionKind;
(function (CodeActionKind) {
    /**
     * Empty kind.
     */
    CodeActionKind.Empty = '';
    /**
     * Base kind for quickfix actions: 'quickfix'
     */
    CodeActionKind.QuickFix = 'quickfix';
    /**
     * Base kind for refactoring actions: 'refactor'
     */
    CodeActionKind.Refactor = 'refactor';
    /**
     * Base kind for refactoring extraction actions: 'refactor.extract'
     *
     * Example extract actions:
     *
     * - Extract method
     * - Extract function
     * - Extract variable
     * - Extract interface from class
     * - ...
     */
    CodeActionKind.RefactorExtract = 'refactor.extract';
    /**
     * Base kind for refactoring inline actions: 'refactor.inline'
     *
     * Example inline actions:
     *
     * - Inline function
     * - Inline variable
     * - Inline constant
     * - ...
     */
    CodeActionKind.RefactorInline = 'refactor.inline';
    /**
     * Base kind for refactoring rewrite actions: 'refactor.rewrite'
     *
     * Example rewrite actions:
     *
     * - Convert JavaScript function to class
     * - Add or remove parameter
     * - Encapsulate field
     * - Make method static
     * - Move method to base class
     * - ...
     */
    CodeActionKind.RefactorRewrite = 'refactor.rewrite';
    /**
     * Base kind for source actions: `source`
     *
     * Source code actions apply to the entire file.
     */
    CodeActionKind.Source = 'source';
    /**
     * Base kind for an organize imports source action: `source.organizeImports`
     */
    CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
    /**
     * Base kind for auto-fix source actions: `source.fixAll`.
     *
     * Fix all actions automatically fix errors that have a clear fix that do not require user input.
     * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
     *
     * @since 3.15.0
     */
    CodeActionKind.SourceFixAll = 'source.fixAll';
})(CodeActionKind || (CodeActionKind = {}));
/**
 * The reason why code actions were requested.
 *
 * @since 3.17.0
 */
var CodeActionTriggerKind;
(function (CodeActionTriggerKind) {
    /**
     * Code actions were explicitly requested by the user or by an extension.
     */
    CodeActionTriggerKind.Invoked = 1;
    /**
     * Code actions were requested automatically.
     *
     * This typically happens when current selection in a file changes, but can
     * also be triggered when file content changes.
     */
    CodeActionTriggerKind.Automatic = 2;
})(CodeActionTriggerKind || (CodeActionTriggerKind = {}));
/**
 * The CodeActionContext namespace provides helper functions to work with
 * {@link CodeActionContext} literals.
 */
var CodeActionContext;
(function (CodeActionContext) {
    /**
     * Creates a new CodeActionContext literal.
     */
    function create(diagnostics, only, triggerKind) {
        let result = { diagnostics };
        if (only !== undefined && only !== null) {
            result.only = only;
        }
        if (triggerKind !== undefined && triggerKind !== null) {
            result.triggerKind = triggerKind;
        }
        return result;
    }
    CodeActionContext.create = create;
    /**
     * Checks whether the given literal conforms to the {@link CodeActionContext} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Is$4.typedArray(candidate.diagnostics, Diagnostic.is)
            && (candidate.only === undefined || Is$4.typedArray(candidate.only, Is$4.string))
            && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic);
    }
    CodeActionContext.is = is;
})(CodeActionContext || (CodeActionContext = {}));
var CodeAction;
(function (CodeAction) {
    function create(title, kindOrCommandOrEdit, kind) {
        let result = { title };
        let checkKind = true;
        if (typeof kindOrCommandOrEdit === 'string') {
            checkKind = false;
            result.kind = kindOrCommandOrEdit;
        }
        else if (Command.is(kindOrCommandOrEdit)) {
            result.command = kindOrCommandOrEdit;
        }
        else {
            result.edit = kindOrCommandOrEdit;
        }
        if (checkKind && kind !== undefined) {
            result.kind = kind;
        }
        return result;
    }
    CodeAction.create = create;
    function is(value) {
        let candidate = value;
        return candidate && Is$4.string(candidate.title) &&
            (candidate.diagnostics === undefined || Is$4.typedArray(candidate.diagnostics, Diagnostic.is)) &&
            (candidate.kind === undefined || Is$4.string(candidate.kind)) &&
            (candidate.edit !== undefined || candidate.command !== undefined) &&
            (candidate.command === undefined || Command.is(candidate.command)) &&
            (candidate.isPreferred === undefined || Is$4.boolean(candidate.isPreferred)) &&
            (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit));
    }
    CodeAction.is = is;
})(CodeAction || (CodeAction = {}));
/**
 * The CodeLens namespace provides helper functions to work with
 * {@link CodeLens} literals.
 */
var CodeLens;
(function (CodeLens) {
    /**
     * Creates a new CodeLens literal.
     */
    function create(range, data) {
        let result = { range };
        if (Is$4.defined(data)) {
            result.data = data;
        }
        return result;
    }
    CodeLens.create = create;
    /**
     * Checks whether the given literal conforms to the {@link CodeLens} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Range.is(candidate.range) && (Is$4.undefined(candidate.command) || Command.is(candidate.command));
    }
    CodeLens.is = is;
})(CodeLens || (CodeLens = {}));
/**
 * The FormattingOptions namespace provides helper functions to work with
 * {@link FormattingOptions} literals.
 */
var FormattingOptions;
(function (FormattingOptions) {
    /**
     * Creates a new FormattingOptions literal.
     */
    function create(tabSize, insertSpaces) {
        return { tabSize, insertSpaces };
    }
    FormattingOptions.create = create;
    /**
     * Checks whether the given literal conforms to the {@link FormattingOptions} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Is$4.uinteger(candidate.tabSize) && Is$4.boolean(candidate.insertSpaces);
    }
    FormattingOptions.is = is;
})(FormattingOptions || (FormattingOptions = {}));
/**
 * The DocumentLink namespace provides helper functions to work with
 * {@link DocumentLink} literals.
 */
var DocumentLink;
(function (DocumentLink) {
    /**
     * Creates a new DocumentLink literal.
     */
    function create(range, target, data) {
        return { range, target, data };
    }
    DocumentLink.create = create;
    /**
     * Checks whether the given literal conforms to the {@link DocumentLink} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Range.is(candidate.range) && (Is$4.undefined(candidate.target) || Is$4.string(candidate.target));
    }
    DocumentLink.is = is;
})(DocumentLink || (DocumentLink = {}));
/**
 * The SelectionRange namespace provides helper function to work with
 * SelectionRange literals.
 */
var SelectionRange;
(function (SelectionRange) {
    /**
     * Creates a new SelectionRange
     * @param range the range.
     * @param parent an optional parent.
     */
    function create(range, parent) {
        return { range, parent };
    }
    SelectionRange.create = create;
    function is(value) {
        let candidate = value;
        return Is$4.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
    }
    SelectionRange.is = is;
})(SelectionRange || (SelectionRange = {}));
/**
 * A set of predefined token types. This set is not fixed
 * an clients can specify additional token types via the
 * corresponding client capabilities.
 *
 * @since 3.16.0
 */
var SemanticTokenTypes;
(function (SemanticTokenTypes) {
    SemanticTokenTypes["namespace"] = "namespace";
    /**
     * Represents a generic type. Acts as a fallback for types which can't be mapped to
     * a specific type like class or enum.
     */
    SemanticTokenTypes["type"] = "type";
    SemanticTokenTypes["class"] = "class";
    SemanticTokenTypes["enum"] = "enum";
    SemanticTokenTypes["interface"] = "interface";
    SemanticTokenTypes["struct"] = "struct";
    SemanticTokenTypes["typeParameter"] = "typeParameter";
    SemanticTokenTypes["parameter"] = "parameter";
    SemanticTokenTypes["variable"] = "variable";
    SemanticTokenTypes["property"] = "property";
    SemanticTokenTypes["enumMember"] = "enumMember";
    SemanticTokenTypes["event"] = "event";
    SemanticTokenTypes["function"] = "function";
    SemanticTokenTypes["method"] = "method";
    SemanticTokenTypes["macro"] = "macro";
    SemanticTokenTypes["keyword"] = "keyword";
    SemanticTokenTypes["modifier"] = "modifier";
    SemanticTokenTypes["comment"] = "comment";
    SemanticTokenTypes["string"] = "string";
    SemanticTokenTypes["number"] = "number";
    SemanticTokenTypes["regexp"] = "regexp";
    SemanticTokenTypes["operator"] = "operator";
    /**
     * @since 3.17.0
     */
    SemanticTokenTypes["decorator"] = "decorator";
})(SemanticTokenTypes || (SemanticTokenTypes = {}));
/**
 * A set of predefined token modifiers. This set is not fixed
 * an clients can specify additional token types via the
 * corresponding client capabilities.
 *
 * @since 3.16.0
 */
var SemanticTokenModifiers;
(function (SemanticTokenModifiers) {
    SemanticTokenModifiers["declaration"] = "declaration";
    SemanticTokenModifiers["definition"] = "definition";
    SemanticTokenModifiers["readonly"] = "readonly";
    SemanticTokenModifiers["static"] = "static";
    SemanticTokenModifiers["deprecated"] = "deprecated";
    SemanticTokenModifiers["abstract"] = "abstract";
    SemanticTokenModifiers["async"] = "async";
    SemanticTokenModifiers["modification"] = "modification";
    SemanticTokenModifiers["documentation"] = "documentation";
    SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary";
})(SemanticTokenModifiers || (SemanticTokenModifiers = {}));
/**
 * @since 3.16.0
 */
var SemanticTokens;
(function (SemanticTokens) {
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
            Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
    }
    SemanticTokens.is = is;
})(SemanticTokens || (SemanticTokens = {}));
/**
 * The InlineValueText namespace provides functions to deal with InlineValueTexts.
 *
 * @since 3.17.0
 */
var InlineValueText;
(function (InlineValueText) {
    /**
     * Creates a new InlineValueText literal.
     */
    function create(range, text) {
        return { range, text };
    }
    InlineValueText.create = create;
    function is(value) {
        const candidate = value;
        return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is$4.string(candidate.text);
    }
    InlineValueText.is = is;
})(InlineValueText || (InlineValueText = {}));
/**
 * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups.
 *
 * @since 3.17.0
 */
var InlineValueVariableLookup;
(function (InlineValueVariableLookup) {
    /**
     * Creates a new InlineValueText literal.
     */
    function create(range, variableName, caseSensitiveLookup) {
        return { range, variableName, caseSensitiveLookup };
    }
    InlineValueVariableLookup.create = create;
    function is(value) {
        const candidate = value;
        return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is$4.boolean(candidate.caseSensitiveLookup)
            && (Is$4.string(candidate.variableName) || candidate.variableName === undefined);
    }
    InlineValueVariableLookup.is = is;
})(InlineValueVariableLookup || (InlineValueVariableLookup = {}));
/**
 * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression.
 *
 * @since 3.17.0
 */
var InlineValueEvaluatableExpression;
(function (InlineValueEvaluatableExpression) {
    /**
     * Creates a new InlineValueEvaluatableExpression literal.
     */
    function create(range, expression) {
        return { range, expression };
    }
    InlineValueEvaluatableExpression.create = create;
    function is(value) {
        const candidate = value;
        return candidate !== undefined && candidate !== null && Range.is(candidate.range)
            && (Is$4.string(candidate.expression) || candidate.expression === undefined);
    }
    InlineValueEvaluatableExpression.is = is;
})(InlineValueEvaluatableExpression || (InlineValueEvaluatableExpression = {}));
/**
 * The InlineValueContext namespace provides helper functions to work with
 * {@link InlineValueContext} literals.
 *
 * @since 3.17.0
 */
var InlineValueContext;
(function (InlineValueContext) {
    /**
     * Creates a new InlineValueContext literal.
     */
    function create(frameId, stoppedLocation) {
        return { frameId, stoppedLocation };
    }
    InlineValueContext.create = create;
    /**
     * Checks whether the given literal conforms to the {@link InlineValueContext} interface.
     */
    function is(value) {
        const candidate = value;
        return Is$4.defined(candidate) && Range.is(value.stoppedLocation);
    }
    InlineValueContext.is = is;
})(InlineValueContext || (InlineValueContext = {}));
/**
 * Inlay hint kinds.
 *
 * @since 3.17.0
 */
var InlayHintKind;
(function (InlayHintKind) {
    /**
     * An inlay hint that for a type annotation.
     */
    InlayHintKind.Type = 1;
    /**
     * An inlay hint that is for a parameter.
     */
    InlayHintKind.Parameter = 2;
    function is(value) {
        return value === 1 || value === 2;
    }
    InlayHintKind.is = is;
})(InlayHintKind || (InlayHintKind = {}));
var InlayHintLabelPart;
(function (InlayHintLabelPart) {
    function create(value) {
        return { value };
    }
    InlayHintLabelPart.create = create;
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate)
            && (candidate.tooltip === undefined || Is$4.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip))
            && (candidate.location === undefined || Location.is(candidate.location))
            && (candidate.command === undefined || Command.is(candidate.command));
    }
    InlayHintLabelPart.is = is;
})(InlayHintLabelPart || (InlayHintLabelPart = {}));
var InlayHint;
(function (InlayHint) {
    function create(position, label, kind) {
        const result = { position, label };
        if (kind !== undefined) {
            result.kind = kind;
        }
        return result;
    }
    InlayHint.create = create;
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && Position.is(candidate.position)
            && (Is$4.string(candidate.label) || Is$4.typedArray(candidate.label, InlayHintLabelPart.is))
            && (candidate.kind === undefined || InlayHintKind.is(candidate.kind))
            && (candidate.textEdits === undefined) || Is$4.typedArray(candidate.textEdits, TextEdit.is)
            && (candidate.tooltip === undefined || Is$4.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip))
            && (candidate.paddingLeft === undefined || Is$4.boolean(candidate.paddingLeft))
            && (candidate.paddingRight === undefined || Is$4.boolean(candidate.paddingRight));
    }
    InlayHint.is = is;
})(InlayHint || (InlayHint = {}));
var StringValue;
(function (StringValue) {
    function createSnippet(value) {
        return { kind: 'snippet', value };
    }
    StringValue.createSnippet = createSnippet;
})(StringValue || (StringValue = {}));
var InlineCompletionItem;
(function (InlineCompletionItem) {
    function create(insertText, filterText, range, command) {
        return { insertText, filterText, range, command };
    }
    InlineCompletionItem.create = create;
})(InlineCompletionItem || (InlineCompletionItem = {}));
var InlineCompletionList;
(function (InlineCompletionList) {
    function create(items) {
        return { items };
    }
    InlineCompletionList.create = create;
})(InlineCompletionList || (InlineCompletionList = {}));
/**
 * Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.
 *
 * @since 3.18.0
 * @proposed
 */
var InlineCompletionTriggerKind;
(function (InlineCompletionTriggerKind) {
    /**
     * Completion was triggered explicitly by a user gesture.
     */
    InlineCompletionTriggerKind.Invoked = 0;
    /**
     * Completion was triggered automatically while editing.
     */
    InlineCompletionTriggerKind.Automatic = 1;
})(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
var SelectedCompletionInfo;
(function (SelectedCompletionInfo) {
    function create(range, text) {
        return { range, text };
    }
    SelectedCompletionInfo.create = create;
})(SelectedCompletionInfo || (SelectedCompletionInfo = {}));
var InlineCompletionContext;
(function (InlineCompletionContext) {
    function create(triggerKind, selectedCompletionInfo) {
        return { triggerKind, selectedCompletionInfo };
    }
    InlineCompletionContext.create = create;
})(InlineCompletionContext || (InlineCompletionContext = {}));
var WorkspaceFolder;
(function (WorkspaceFolder) {
    function is(value) {
        const candidate = value;
        return Is$4.objectLiteral(candidate) && URI.is(candidate.uri) && Is$4.string(candidate.name);
    }
    WorkspaceFolder.is = is;
})(WorkspaceFolder || (WorkspaceFolder = {}));
const EOL = ['\n', '\r\n', '\r'];
/**
 * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
 */
var TextDocument;
(function (TextDocument) {
    /**
     * Creates a new ITextDocument literal from the given uri and content.
     * @param uri The document's uri.
     * @param languageId The document's language Id.
     * @param version The document's version.
     * @param content The document's content.
     */
    function create(uri, languageId, version, content) {
        return new FullTextDocument(uri, languageId, version, content);
    }
    TextDocument.create = create;
    /**
     * Checks whether the given literal conforms to the {@link ITextDocument} interface.
     */
    function is(value) {
        let candidate = value;
        return Is$4.defined(candidate) && Is$4.string(candidate.uri) && (Is$4.undefined(candidate.languageId) || Is$4.string(candidate.languageId)) && Is$4.uinteger(candidate.lineCount)
            && Is$4.func(candidate.getText) && Is$4.func(candidate.positionAt) && Is$4.func(candidate.offsetAt) ? true : false;
    }
    TextDocument.is = is;
    function applyEdits(document, edits) {
        let text = document.getText();
        let sortedEdits = mergeSort(edits, (a, b) => {
            let diff = a.range.start.line - b.range.start.line;
            if (diff === 0) {
                return a.range.start.character - b.range.start.character;
            }
            return diff;
        });
        let lastModifiedOffset = text.length;
        for (let i = sortedEdits.length - 1; i >= 0; i--) {
            let e = sortedEdits[i];
            let startOffset = document.offsetAt(e.range.start);
            let endOffset = document.offsetAt(e.range.end);
            if (endOffset <= lastModifiedOffset) {
                text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
            }
            else {
                throw new Error('Overlapping edit');
            }
            lastModifiedOffset = startOffset;
        }
        return text;
    }
    TextDocument.applyEdits = applyEdits;
    function mergeSort(data, compare) {
        if (data.length <= 1) {
            // sorted
            return data;
        }
        const p = (data.length / 2) | 0;
        const left = data.slice(0, p);
        const right = data.slice(p);
        mergeSort(left, compare);
        mergeSort(right, compare);
        let leftIdx = 0;
        let rightIdx = 0;
        let i = 0;
        while (leftIdx < left.length && rightIdx < right.length) {
            let ret = compare(left[leftIdx], right[rightIdx]);
            if (ret <= 0) {
                // smaller_equal -> take left to preserve order
                data[i++] = left[leftIdx++];
            }
            else {
                // greater -> take right
                data[i++] = right[rightIdx++];
            }
        }
        while (leftIdx < left.length) {
            data[i++] = left[leftIdx++];
        }
        while (rightIdx < right.length) {
            data[i++] = right[rightIdx++];
        }
        return data;
    }
})(TextDocument || (TextDocument = {}));
/**
 * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
 */
class FullTextDocument {
    constructor(uri, languageId, version, content) {
        this._uri = uri;
        this._languageId = languageId;
        this._version = version;
        this._content = content;
        this._lineOffsets = undefined;
    }
    get uri() {
        return this._uri;
    }
    get languageId() {
        return this._languageId;
    }
    get version() {
        return this._version;
    }
    getText(range) {
        if (range) {
            let start = this.offsetAt(range.start);
            let end = this.offsetAt(range.end);
            return this._content.substring(start, end);
        }
        return this._content;
    }
    update(event, version) {
        this._content = event.text;
        this._version = version;
        this._lineOffsets = undefined;
    }
    getLineOffsets() {
        if (this._lineOffsets === undefined) {
            let lineOffsets = [];
            let text = this._content;
            let isLineStart = true;
            for (let i = 0; i < text.length; i++) {
                if (isLineStart) {
                    lineOffsets.push(i);
                    isLineStart = false;
                }
                let ch = text.charAt(i);
                isLineStart = (ch === '\r' || ch === '\n');
                if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
                    i++;
                }
            }
            if (isLineStart && text.length > 0) {
                lineOffsets.push(text.length);
            }
            this._lineOffsets = lineOffsets;
        }
        return this._lineOffsets;
    }
    positionAt(offset) {
        offset = Math.max(Math.min(offset, this._content.length), 0);
        let lineOffsets = this.getLineOffsets();
        let low = 0, high = lineOffsets.length;
        if (high === 0) {
            return Position.create(0, offset);
        }
        while (low < high) {
            let mid = Math.floor((low + high) / 2);
            if (lineOffsets[mid] > offset) {
                high = mid;
            }
            else {
                low = mid + 1;
            }
        }
        // low is the least x for which the line offset is larger than the current offset
        // or array.length if no line offset is larger than the current offset
        let line = low - 1;
        return Position.create(line, offset - lineOffsets[line]);
    }
    offsetAt(position) {
        let lineOffsets = this.getLineOffsets();
        if (position.line >= lineOffsets.length) {
            return this._content.length;
        }
        else if (position.line < 0) {
            return 0;
        }
        let lineOffset = lineOffsets[position.line];
        let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
        return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
    }
    get lineCount() {
        return this.getLineOffsets().length;
    }
}
var Is$4;
(function (Is) {
    const toString = Object.prototype.toString;
    function defined(value) {
        return typeof value !== 'undefined';
    }
    Is.defined = defined;
    function undefined$1(value) {
        return typeof value === 'undefined';
    }
    Is.undefined = undefined$1;
    function boolean(value) {
        return value === true || value === false;
    }
    Is.boolean = boolean;
    function string(value) {
        return toString.call(value) === '[object String]';
    }
    Is.string = string;
    function number(value) {
        return toString.call(value) === '[object Number]';
    }
    Is.number = number;
    function numberRange(value, min, max) {
        return toString.call(value) === '[object Number]' && min <= value && value <= max;
    }
    Is.numberRange = numberRange;
    function integer(value) {
        return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647;
    }
    Is.integer = integer;
    function uinteger(value) {
        return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647;
    }
    Is.uinteger = uinteger;
    function func(value) {
        return toString.call(value) === '[object Function]';
    }
    Is.func = func;
    function objectLiteral(value) {
        // Strictly speaking class instances pass this check as well. Since the LSP
        // doesn't use classes we ignore this for now. If we do we need to add something
        // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
        return value !== null && typeof value === 'object';
    }
    Is.objectLiteral = objectLiteral;
    function typedArray(value, check) {
        return Array.isArray(value) && value.every(check);
    }
    Is.typedArray = typedArray;
})(Is$4 || (Is$4 = {}));

var main = /*#__PURE__*/Object.freeze({
    __proto__: null,
    get AnnotatedTextEdit () { return AnnotatedTextEdit; },
    get ChangeAnnotation () { return ChangeAnnotation; },
    get ChangeAnnotationIdentifier () { return ChangeAnnotationIdentifier; },
    get CodeAction () { return CodeAction; },
    get CodeActionContext () { return CodeActionContext; },
    get CodeActionKind () { return CodeActionKind; },
    get CodeActionTriggerKind () { return CodeActionTriggerKind; },
    get CodeDescription () { return CodeDescription; },
    get CodeLens () { return CodeLens; },
    get Color () { return Color; },
    get ColorInformation () { return ColorInformation; },
    get ColorPresentation () { return ColorPresentation; },
    get Command () { return Command; },
    get CompletionItem () { return CompletionItem; },
    get CompletionItemKind () { return CompletionItemKind; },
    get CompletionItemLabelDetails () { return CompletionItemLabelDetails; },
    get CompletionItemTag () { return CompletionItemTag; },
    get CompletionList () { return CompletionList; },
    get CreateFile () { return CreateFile; },
    get DeleteFile () { return DeleteFile; },
    get Diagnostic () { return Diagnostic; },
    get DiagnosticRelatedInformation () { return DiagnosticRelatedInformation; },
    get DiagnosticSeverity () { return DiagnosticSeverity; },
    get DiagnosticTag () { return DiagnosticTag; },
    get DocumentHighlight () { return DocumentHighlight; },
    get DocumentHighlightKind () { return DocumentHighlightKind; },
    get DocumentLink () { return DocumentLink; },
    get DocumentSymbol () { return DocumentSymbol; },
    get DocumentUri () { return DocumentUri; },
    EOL: EOL,
    get FoldingRange () { return FoldingRange; },
    get FoldingRangeKind () { return FoldingRangeKind; },
    get FormattingOptions () { return FormattingOptions; },
    get Hover () { return Hover; },
    get InlayHint () { return InlayHint; },
    get InlayHintKind () { return InlayHintKind; },
    get InlayHintLabelPart () { return InlayHintLabelPart; },
    get InlineCompletionContext () { return InlineCompletionContext; },
    get InlineCompletionItem () { return InlineCompletionItem; },
    get InlineCompletionList () { return InlineCompletionList; },
    get InlineCompletionTriggerKind () { return InlineCompletionTriggerKind; },
    get InlineValueContext () { return InlineValueContext; },
    get InlineValueEvaluatableExpression () { return InlineValueEvaluatableExpression; },
    get InlineValueText () { return InlineValueText; },
    get InlineValueVariableLookup () { return InlineValueVariableLookup; },
    get InsertReplaceEdit () { return InsertReplaceEdit; },
    get InsertTextFormat () { return InsertTextFormat; },
    get InsertTextMode () { return InsertTextMode; },
    get Location () { return Location; },
    get LocationLink () { return LocationLink; },
    get MarkedString () { return MarkedString; },
    get MarkupContent () { return MarkupContent; },
    get MarkupKind () { return MarkupKind; },
    get OptionalVersionedTextDocumentIdentifier () { return OptionalVersionedTextDocumentIdentifier; },
    get ParameterInformation () { return ParameterInformation; },
    get Position () { return Position; },
    get Range () { return Range; },
    get RenameFile () { return RenameFile; },
    get SelectedCompletionInfo () { return SelectedCompletionInfo; },
    get SelectionRange () { return SelectionRange; },
    get SemanticTokenModifiers () { return SemanticTokenModifiers; },
    get SemanticTokenTypes () { return SemanticTokenTypes; },
    get SemanticTokens () { return SemanticTokens; },
    get SignatureInformation () { return SignatureInformation; },
    get StringValue () { return StringValue; },
    get SymbolInformation () { return SymbolInformation; },
    get SymbolKind () { return SymbolKind; },
    get SymbolTag () { return SymbolTag; },
    get TextDocument () { return TextDocument; },
    get TextDocumentEdit () { return TextDocumentEdit; },
    get TextDocumentIdentifier () { return TextDocumentIdentifier; },
    get TextDocumentItem () { return TextDocumentItem; },
    get TextEdit () { return TextEdit; },
    get URI () { return URI; },
    get VersionedTextDocumentIdentifier () { return VersionedTextDocumentIdentifier; },
    WorkspaceChange: WorkspaceChange,
    get WorkspaceEdit () { return WorkspaceEdit; },
    get WorkspaceFolder () { return WorkspaceFolder; },
    get WorkspaceSymbol () { return WorkspaceSymbol; },
    get integer () { return integer; },
    get uinteger () { return uinteger; }
});

var require$$1 = /*@__PURE__*/getAugmentedNamespace(main);

var messages = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(messages, "__esModule", { value: true });
messages.ProtocolNotificationType = messages.ProtocolNotificationType0 = messages.ProtocolRequestType = messages.ProtocolRequestType0 = messages.RegistrationType = messages.MessageDirection = void 0;
const vscode_jsonrpc_1$3 = main$1;
var MessageDirection;
(function (MessageDirection) {
    MessageDirection["clientToServer"] = "clientToServer";
    MessageDirection["serverToClient"] = "serverToClient";
    MessageDirection["both"] = "both";
})(MessageDirection || (messages.MessageDirection = MessageDirection = {}));
class RegistrationType {
    constructor(method) {
        this.method = method;
    }
}
messages.RegistrationType = RegistrationType;
class ProtocolRequestType0 extends vscode_jsonrpc_1$3.RequestType0 {
    constructor(method) {
        super(method);
    }
}
messages.ProtocolRequestType0 = ProtocolRequestType0;
class ProtocolRequestType extends vscode_jsonrpc_1$3.RequestType {
    constructor(method) {
        super(method, vscode_jsonrpc_1$3.ParameterStructures.byName);
    }
}
messages.ProtocolRequestType = ProtocolRequestType;
class ProtocolNotificationType0 extends vscode_jsonrpc_1$3.NotificationType0 {
    constructor(method) {
        super(method);
    }
}
messages.ProtocolNotificationType0 = ProtocolNotificationType0;
class ProtocolNotificationType extends vscode_jsonrpc_1$3.NotificationType {
    constructor(method) {
        super(method, vscode_jsonrpc_1$3.ParameterStructures.byName);
    }
}
messages.ProtocolNotificationType = ProtocolNotificationType;

var protocol = {};

var is$1 = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(is$1, "__esModule", { value: true });
is$1.objectLiteral = is$1.typedArray = is$1.stringArray = is$1.array = is$1.func = is$1.error = is$1.number = is$1.string = is$1.boolean = void 0;
function boolean$1(value) {
    return value === true || value === false;
}
is$1.boolean = boolean$1;
function string$1(value) {
    return typeof value === 'string' || value instanceof String;
}
is$1.string = string$1;
function number$1(value) {
    return typeof value === 'number' || value instanceof Number;
}
is$1.number = number$1;
function error$1(value) {
    return value instanceof Error;
}
is$1.error = error$1;
function func$1(value) {
    return typeof value === 'function';
}
is$1.func = func$1;
function array$1(value) {
    return Array.isArray(value);
}
is$1.array = array$1;
function stringArray$1(value) {
    return array$1(value) && value.every(elem => string$1(elem));
}
is$1.stringArray = stringArray$1;
function typedArray$1(value, check) {
    return Array.isArray(value) && value.every(check);
}
is$1.typedArray = typedArray$1;
function objectLiteral(value) {
    // Strictly speaking class instances pass this check as well. Since the LSP
    // doesn't use classes we ignore this for now. If we do we need to add something
    // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
    return value !== null && typeof value === 'object';
}
is$1.objectLiteral = objectLiteral;

var protocol_implementation = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_implementation, "__esModule", { value: true });
protocol_implementation.ImplementationRequest = void 0;
const messages_1$k = messages;
/**
 * A request to resolve the implementation locations of a symbol at a given text
 * document position. The request's parameter is of type {@link TextDocumentPositionParams}
 * the response is of type {@link Definition} or a Thenable that resolves to such.
 */
var ImplementationRequest;
(function (ImplementationRequest) {
    ImplementationRequest.method = 'textDocument/implementation';
    ImplementationRequest.messageDirection = messages_1$k.MessageDirection.clientToServer;
    ImplementationRequest.type = new messages_1$k.ProtocolRequestType(ImplementationRequest.method);
})(ImplementationRequest || (protocol_implementation.ImplementationRequest = ImplementationRequest = {}));

var protocol_typeDefinition = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_typeDefinition, "__esModule", { value: true });
protocol_typeDefinition.TypeDefinitionRequest = void 0;
const messages_1$j = messages;
/**
 * A request to resolve the type definition locations of a symbol at a given text
 * document position. The request's parameter is of type {@link TextDocumentPositionParams}
 * the response is of type {@link Definition} or a Thenable that resolves to such.
 */
var TypeDefinitionRequest;
(function (TypeDefinitionRequest) {
    TypeDefinitionRequest.method = 'textDocument/typeDefinition';
    TypeDefinitionRequest.messageDirection = messages_1$j.MessageDirection.clientToServer;
    TypeDefinitionRequest.type = new messages_1$j.ProtocolRequestType(TypeDefinitionRequest.method);
})(TypeDefinitionRequest || (protocol_typeDefinition.TypeDefinitionRequest = TypeDefinitionRequest = {}));

var protocol_workspaceFolder = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_workspaceFolder, "__esModule", { value: true });
protocol_workspaceFolder.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolder.WorkspaceFoldersRequest = void 0;
const messages_1$i = messages;
/**
 * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
 */
var WorkspaceFoldersRequest;
(function (WorkspaceFoldersRequest) {
    WorkspaceFoldersRequest.method = 'workspace/workspaceFolders';
    WorkspaceFoldersRequest.messageDirection = messages_1$i.MessageDirection.serverToClient;
    WorkspaceFoldersRequest.type = new messages_1$i.ProtocolRequestType0(WorkspaceFoldersRequest.method);
})(WorkspaceFoldersRequest || (protocol_workspaceFolder.WorkspaceFoldersRequest = WorkspaceFoldersRequest = {}));
/**
 * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
 * folder configuration changes.
 */
var DidChangeWorkspaceFoldersNotification;
(function (DidChangeWorkspaceFoldersNotification) {
    DidChangeWorkspaceFoldersNotification.method = 'workspace/didChangeWorkspaceFolders';
    DidChangeWorkspaceFoldersNotification.messageDirection = messages_1$i.MessageDirection.clientToServer;
    DidChangeWorkspaceFoldersNotification.type = new messages_1$i.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification.method);
})(DidChangeWorkspaceFoldersNotification || (protocol_workspaceFolder.DidChangeWorkspaceFoldersNotification = DidChangeWorkspaceFoldersNotification = {}));

var protocol_configuration = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_configuration, "__esModule", { value: true });
protocol_configuration.ConfigurationRequest = void 0;
const messages_1$h = messages;
//---- Get Configuration request ----
/**
 * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
 * configuration setting.
 *
 * This pull model replaces the old push model were the client signaled configuration change via an
 * event. If the server still needs to react to configuration changes (since the server caches the
 * result of `workspace/configuration` requests) the server should register for an empty configuration
 * change event and empty the cache if such an event is received.
 */
var ConfigurationRequest;
(function (ConfigurationRequest) {
    ConfigurationRequest.method = 'workspace/configuration';
    ConfigurationRequest.messageDirection = messages_1$h.MessageDirection.serverToClient;
    ConfigurationRequest.type = new messages_1$h.ProtocolRequestType(ConfigurationRequest.method);
})(ConfigurationRequest || (protocol_configuration.ConfigurationRequest = ConfigurationRequest = {}));

var protocol_colorProvider = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_colorProvider, "__esModule", { value: true });
protocol_colorProvider.ColorPresentationRequest = protocol_colorProvider.DocumentColorRequest = void 0;
const messages_1$g = messages;
/**
 * A request to list all color symbols found in a given text document. The request's
 * parameter is of type {@link DocumentColorParams} the
 * response is of type {@link ColorInformation ColorInformation[]} or a Thenable
 * that resolves to such.
 */
var DocumentColorRequest;
(function (DocumentColorRequest) {
    DocumentColorRequest.method = 'textDocument/documentColor';
    DocumentColorRequest.messageDirection = messages_1$g.MessageDirection.clientToServer;
    DocumentColorRequest.type = new messages_1$g.ProtocolRequestType(DocumentColorRequest.method);
})(DocumentColorRequest || (protocol_colorProvider.DocumentColorRequest = DocumentColorRequest = {}));
/**
 * A request to list all presentation for a color. The request's
 * parameter is of type {@link ColorPresentationParams} the
 * response is of type {@link ColorInformation ColorInformation[]} or a Thenable
 * that resolves to such.
 */
var ColorPresentationRequest;
(function (ColorPresentationRequest) {
    ColorPresentationRequest.method = 'textDocument/colorPresentation';
    ColorPresentationRequest.messageDirection = messages_1$g.MessageDirection.clientToServer;
    ColorPresentationRequest.type = new messages_1$g.ProtocolRequestType(ColorPresentationRequest.method);
})(ColorPresentationRequest || (protocol_colorProvider.ColorPresentationRequest = ColorPresentationRequest = {}));

var protocol_foldingRange = {};

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(protocol_foldingRange, "__esModule", { value: true });
protocol_foldingRange.FoldingRangeRefreshRequest = protocol_foldingRange.FoldingRangeRequest = void 0;
const messages_1$f = messages;
/**
 * A request to provide folding ranges in a document. The request's
 * parameter is of type {@link FoldingRangeParams}, the
 * response is of type {@link FoldingRangeList} or a Thenable
 * that resolves to such.
 */
var FoldingRangeRequest;
(function (FoldingRangeRequest) {
    FoldingRangeRequest.method = 'textDocument/foldingRange';
    FoldingRangeRequest.messageDirection = messages_1$f.MessageDirection.clientToServer;
    FoldingRangeRequest.type = new messages_1$f.ProtocolRequestType(FoldingRangeRequest.method);
})(FoldingRangeRequest || (protocol_foldingRange.FoldingRangeRequest = FoldingRangeRequest = {}));
/**
 * @since 3.18.0
 * @proposed
 */
var FoldingRangeRefreshRequest;
(function (FoldingRangeRefreshRequest) {
    FoldingRangeRefreshRequest.method = `workspace/foldingRange/refresh`;
    FoldingRangeRefreshRequest.messageDirection = messages_1$f.MessageDirection.serverToClient;
    FoldingRangeRefreshRequest.type = new messages_1$f.ProtocolRequestType0(FoldingRangeRefreshRequest.method);
})(FoldingRangeRefreshRequest || (protocol_foldingRange.FoldingRangeRefreshRequest = FoldingRangeRefreshRequest = {}));

var protocol_declaration = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_declaration, "__esModule", { value: true });
protocol_declaration.DeclarationRequest = void 0;
const messages_1$e = messages;
/**
 * A request to resolve the type definition locations of a symbol at a given text
 * document position. The request's parameter is of type {@link TextDocumentPositionParams}
 * the response is of type {@link Declaration} or a typed array of {@link DeclarationLink}
 * or a Thenable that resolves to such.
 */
var DeclarationRequest;
(function (DeclarationRequest) {
    DeclarationRequest.method = 'textDocument/declaration';
    DeclarationRequest.messageDirection = messages_1$e.MessageDirection.clientToServer;
    DeclarationRequest.type = new messages_1$e.ProtocolRequestType(DeclarationRequest.method);
})(DeclarationRequest || (protocol_declaration.DeclarationRequest = DeclarationRequest = {}));

var protocol_selectionRange = {};

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(protocol_selectionRange, "__esModule", { value: true });
protocol_selectionRange.SelectionRangeRequest = void 0;
const messages_1$d = messages;
/**
 * A request to provide selection ranges in a document. The request's
 * parameter is of type {@link SelectionRangeParams}, the
 * response is of type {@link SelectionRange SelectionRange[]} or a Thenable
 * that resolves to such.
 */
var SelectionRangeRequest;
(function (SelectionRangeRequest) {
    SelectionRangeRequest.method = 'textDocument/selectionRange';
    SelectionRangeRequest.messageDirection = messages_1$d.MessageDirection.clientToServer;
    SelectionRangeRequest.type = new messages_1$d.ProtocolRequestType(SelectionRangeRequest.method);
})(SelectionRangeRequest || (protocol_selectionRange.SelectionRangeRequest = SelectionRangeRequest = {}));

var protocol_progress = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_progress, "__esModule", { value: true });
protocol_progress.WorkDoneProgressCancelNotification = protocol_progress.WorkDoneProgressCreateRequest = protocol_progress.WorkDoneProgress = void 0;
const vscode_jsonrpc_1$2 = main$1;
const messages_1$c = messages;
var WorkDoneProgress;
(function (WorkDoneProgress) {
    WorkDoneProgress.type = new vscode_jsonrpc_1$2.ProgressType();
    function is(value) {
        return value === WorkDoneProgress.type;
    }
    WorkDoneProgress.is = is;
})(WorkDoneProgress || (protocol_progress.WorkDoneProgress = WorkDoneProgress = {}));
/**
 * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
 * reporting from the server.
 */
var WorkDoneProgressCreateRequest;
(function (WorkDoneProgressCreateRequest) {
    WorkDoneProgressCreateRequest.method = 'window/workDoneProgress/create';
    WorkDoneProgressCreateRequest.messageDirection = messages_1$c.MessageDirection.serverToClient;
    WorkDoneProgressCreateRequest.type = new messages_1$c.ProtocolRequestType(WorkDoneProgressCreateRequest.method);
})(WorkDoneProgressCreateRequest || (protocol_progress.WorkDoneProgressCreateRequest = WorkDoneProgressCreateRequest = {}));
/**
 * The `window/workDoneProgress/cancel` notification is sent from  the client to the server to cancel a progress
 * initiated on the server side.
 */
var WorkDoneProgressCancelNotification;
(function (WorkDoneProgressCancelNotification) {
    WorkDoneProgressCancelNotification.method = 'window/workDoneProgress/cancel';
    WorkDoneProgressCancelNotification.messageDirection = messages_1$c.MessageDirection.clientToServer;
    WorkDoneProgressCancelNotification.type = new messages_1$c.ProtocolNotificationType(WorkDoneProgressCancelNotification.method);
})(WorkDoneProgressCancelNotification || (protocol_progress.WorkDoneProgressCancelNotification = WorkDoneProgressCancelNotification = {}));

var protocol_callHierarchy = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) TypeFox, Microsoft and others. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_callHierarchy, "__esModule", { value: true });
protocol_callHierarchy.CallHierarchyOutgoingCallsRequest = protocol_callHierarchy.CallHierarchyIncomingCallsRequest = protocol_callHierarchy.CallHierarchyPrepareRequest = void 0;
const messages_1$b = messages;
/**
 * A request to result a `CallHierarchyItem` in a document at a given position.
 * Can be used as an input to an incoming or outgoing call hierarchy.
 *
 * @since 3.16.0
 */
var CallHierarchyPrepareRequest;
(function (CallHierarchyPrepareRequest) {
    CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
    CallHierarchyPrepareRequest.messageDirection = messages_1$b.MessageDirection.clientToServer;
    CallHierarchyPrepareRequest.type = new messages_1$b.ProtocolRequestType(CallHierarchyPrepareRequest.method);
})(CallHierarchyPrepareRequest || (protocol_callHierarchy.CallHierarchyPrepareRequest = CallHierarchyPrepareRequest = {}));
/**
 * A request to resolve the incoming calls for a given `CallHierarchyItem`.
 *
 * @since 3.16.0
 */
var CallHierarchyIncomingCallsRequest;
(function (CallHierarchyIncomingCallsRequest) {
    CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
    CallHierarchyIncomingCallsRequest.messageDirection = messages_1$b.MessageDirection.clientToServer;
    CallHierarchyIncomingCallsRequest.type = new messages_1$b.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
})(CallHierarchyIncomingCallsRequest || (protocol_callHierarchy.CallHierarchyIncomingCallsRequest = CallHierarchyIncomingCallsRequest = {}));
/**
 * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
 *
 * @since 3.16.0
 */
var CallHierarchyOutgoingCallsRequest;
(function (CallHierarchyOutgoingCallsRequest) {
    CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
    CallHierarchyOutgoingCallsRequest.messageDirection = messages_1$b.MessageDirection.clientToServer;
    CallHierarchyOutgoingCallsRequest.type = new messages_1$b.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
})(CallHierarchyOutgoingCallsRequest || (protocol_callHierarchy.CallHierarchyOutgoingCallsRequest = CallHierarchyOutgoingCallsRequest = {}));

var protocol_semanticTokens = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_semanticTokens, "__esModule", { value: true });
protocol_semanticTokens.SemanticTokensRefreshRequest = protocol_semanticTokens.SemanticTokensRangeRequest = protocol_semanticTokens.SemanticTokensDeltaRequest = protocol_semanticTokens.SemanticTokensRequest = protocol_semanticTokens.SemanticTokensRegistrationType = protocol_semanticTokens.TokenFormat = void 0;
const messages_1$a = messages;
//------- 'textDocument/semanticTokens' -----
var TokenFormat;
(function (TokenFormat) {
    TokenFormat.Relative = 'relative';
})(TokenFormat || (protocol_semanticTokens.TokenFormat = TokenFormat = {}));
var SemanticTokensRegistrationType;
(function (SemanticTokensRegistrationType) {
    SemanticTokensRegistrationType.method = 'textDocument/semanticTokens';
    SemanticTokensRegistrationType.type = new messages_1$a.RegistrationType(SemanticTokensRegistrationType.method);
})(SemanticTokensRegistrationType || (protocol_semanticTokens.SemanticTokensRegistrationType = SemanticTokensRegistrationType = {}));
/**
 * @since 3.16.0
 */
var SemanticTokensRequest;
(function (SemanticTokensRequest) {
    SemanticTokensRequest.method = 'textDocument/semanticTokens/full';
    SemanticTokensRequest.messageDirection = messages_1$a.MessageDirection.clientToServer;
    SemanticTokensRequest.type = new messages_1$a.ProtocolRequestType(SemanticTokensRequest.method);
    SemanticTokensRequest.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensRequest || (protocol_semanticTokens.SemanticTokensRequest = SemanticTokensRequest = {}));
/**
 * @since 3.16.0
 */
var SemanticTokensDeltaRequest;
(function (SemanticTokensDeltaRequest) {
    SemanticTokensDeltaRequest.method = 'textDocument/semanticTokens/full/delta';
    SemanticTokensDeltaRequest.messageDirection = messages_1$a.MessageDirection.clientToServer;
    SemanticTokensDeltaRequest.type = new messages_1$a.ProtocolRequestType(SemanticTokensDeltaRequest.method);
    SemanticTokensDeltaRequest.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensDeltaRequest || (protocol_semanticTokens.SemanticTokensDeltaRequest = SemanticTokensDeltaRequest = {}));
/**
 * @since 3.16.0
 */
var SemanticTokensRangeRequest;
(function (SemanticTokensRangeRequest) {
    SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
    SemanticTokensRangeRequest.messageDirection = messages_1$a.MessageDirection.clientToServer;
    SemanticTokensRangeRequest.type = new messages_1$a.ProtocolRequestType(SemanticTokensRangeRequest.method);
    SemanticTokensRangeRequest.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensRangeRequest || (protocol_semanticTokens.SemanticTokensRangeRequest = SemanticTokensRangeRequest = {}));
/**
 * @since 3.16.0
 */
var SemanticTokensRefreshRequest;
(function (SemanticTokensRefreshRequest) {
    SemanticTokensRefreshRequest.method = `workspace/semanticTokens/refresh`;
    SemanticTokensRefreshRequest.messageDirection = messages_1$a.MessageDirection.serverToClient;
    SemanticTokensRefreshRequest.type = new messages_1$a.ProtocolRequestType0(SemanticTokensRefreshRequest.method);
})(SemanticTokensRefreshRequest || (protocol_semanticTokens.SemanticTokensRefreshRequest = SemanticTokensRefreshRequest = {}));

var protocol_showDocument = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_showDocument, "__esModule", { value: true });
protocol_showDocument.ShowDocumentRequest = void 0;
const messages_1$9 = messages;
/**
 * A request to show a document. This request might open an
 * external program depending on the value of the URI to open.
 * For example a request to open `https://code.visualstudio.com/`
 * will very likely open the URI in a WEB browser.
 *
 * @since 3.16.0
*/
var ShowDocumentRequest;
(function (ShowDocumentRequest) {
    ShowDocumentRequest.method = 'window/showDocument';
    ShowDocumentRequest.messageDirection = messages_1$9.MessageDirection.serverToClient;
    ShowDocumentRequest.type = new messages_1$9.ProtocolRequestType(ShowDocumentRequest.method);
})(ShowDocumentRequest || (protocol_showDocument.ShowDocumentRequest = ShowDocumentRequest = {}));

var protocol_linkedEditingRange = {};

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(protocol_linkedEditingRange, "__esModule", { value: true });
protocol_linkedEditingRange.LinkedEditingRangeRequest = void 0;
const messages_1$8 = messages;
/**
 * A request to provide ranges that can be edited together.
 *
 * @since 3.16.0
 */
var LinkedEditingRangeRequest;
(function (LinkedEditingRangeRequest) {
    LinkedEditingRangeRequest.method = 'textDocument/linkedEditingRange';
    LinkedEditingRangeRequest.messageDirection = messages_1$8.MessageDirection.clientToServer;
    LinkedEditingRangeRequest.type = new messages_1$8.ProtocolRequestType(LinkedEditingRangeRequest.method);
})(LinkedEditingRangeRequest || (protocol_linkedEditingRange.LinkedEditingRangeRequest = LinkedEditingRangeRequest = {}));

var protocol_fileOperations = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_fileOperations, "__esModule", { value: true });
protocol_fileOperations.WillDeleteFilesRequest = protocol_fileOperations.DidDeleteFilesNotification = protocol_fileOperations.DidRenameFilesNotification = protocol_fileOperations.WillRenameFilesRequest = protocol_fileOperations.DidCreateFilesNotification = protocol_fileOperations.WillCreateFilesRequest = protocol_fileOperations.FileOperationPatternKind = void 0;
const messages_1$7 = messages;
/**
 * A pattern kind describing if a glob pattern matches a file a folder or
 * both.
 *
 * @since 3.16.0
 */
var FileOperationPatternKind;
(function (FileOperationPatternKind) {
    /**
     * The pattern matches a file only.
     */
    FileOperationPatternKind.file = 'file';
    /**
     * The pattern matches a folder only.
     */
    FileOperationPatternKind.folder = 'folder';
})(FileOperationPatternKind || (protocol_fileOperations.FileOperationPatternKind = FileOperationPatternKind = {}));
/**
 * The will create files request is sent from the client to the server before files are actually
 * created as long as the creation is triggered from within the client.
 *
 * The request can return a `WorkspaceEdit` which will be applied to workspace before the
 * files are created. Hence the `WorkspaceEdit` can not manipulate the content of the file
 * to be created.
 *
 * @since 3.16.0
 */
var WillCreateFilesRequest;
(function (WillCreateFilesRequest) {
    WillCreateFilesRequest.method = 'workspace/willCreateFiles';
    WillCreateFilesRequest.messageDirection = messages_1$7.MessageDirection.clientToServer;
    WillCreateFilesRequest.type = new messages_1$7.ProtocolRequestType(WillCreateFilesRequest.method);
})(WillCreateFilesRequest || (protocol_fileOperations.WillCreateFilesRequest = WillCreateFilesRequest = {}));
/**
 * The did create files notification is sent from the client to the server when
 * files were created from within the client.
 *
 * @since 3.16.0
 */
var DidCreateFilesNotification;
(function (DidCreateFilesNotification) {
    DidCreateFilesNotification.method = 'workspace/didCreateFiles';
    DidCreateFilesNotification.messageDirection = messages_1$7.MessageDirection.clientToServer;
    DidCreateFilesNotification.type = new messages_1$7.ProtocolNotificationType(DidCreateFilesNotification.method);
})(DidCreateFilesNotification || (protocol_fileOperations.DidCreateFilesNotification = DidCreateFilesNotification = {}));
/**
 * The will rename files request is sent from the client to the server before files are actually
 * renamed as long as the rename is triggered from within the client.
 *
 * @since 3.16.0
 */
var WillRenameFilesRequest;
(function (WillRenameFilesRequest) {
    WillRenameFilesRequest.method = 'workspace/willRenameFiles';
    WillRenameFilesRequest.messageDirection = messages_1$7.MessageDirection.clientToServer;
    WillRenameFilesRequest.type = new messages_1$7.ProtocolRequestType(WillRenameFilesRequest.method);
})(WillRenameFilesRequest || (protocol_fileOperations.WillRenameFilesRequest = WillRenameFilesRequest = {}));
/**
 * The did rename files notification is sent from the client to the server when
 * files were renamed from within the client.
 *
 * @since 3.16.0
 */
var DidRenameFilesNotification;
(function (DidRenameFilesNotification) {
    DidRenameFilesNotification.method = 'workspace/didRenameFiles';
    DidRenameFilesNotification.messageDirection = messages_1$7.MessageDirection.clientToServer;
    DidRenameFilesNotification.type = new messages_1$7.ProtocolNotificationType(DidRenameFilesNotification.method);
})(DidRenameFilesNotification || (protocol_fileOperations.DidRenameFilesNotification = DidRenameFilesNotification = {}));
/**
 * The will delete files request is sent from the client to the server before files are actually
 * deleted as long as the deletion is triggered from within the client.
 *
 * @since 3.16.0
 */
var DidDeleteFilesNotification;
(function (DidDeleteFilesNotification) {
    DidDeleteFilesNotification.method = 'workspace/didDeleteFiles';
    DidDeleteFilesNotification.messageDirection = messages_1$7.MessageDirection.clientToServer;
    DidDeleteFilesNotification.type = new messages_1$7.ProtocolNotificationType(DidDeleteFilesNotification.method);
})(DidDeleteFilesNotification || (protocol_fileOperations.DidDeleteFilesNotification = DidDeleteFilesNotification = {}));
/**
 * The did delete files notification is sent from the client to the server when
 * files were deleted from within the client.
 *
 * @since 3.16.0
 */
var WillDeleteFilesRequest;
(function (WillDeleteFilesRequest) {
    WillDeleteFilesRequest.method = 'workspace/willDeleteFiles';
    WillDeleteFilesRequest.messageDirection = messages_1$7.MessageDirection.clientToServer;
    WillDeleteFilesRequest.type = new messages_1$7.ProtocolRequestType(WillDeleteFilesRequest.method);
})(WillDeleteFilesRequest || (protocol_fileOperations.WillDeleteFilesRequest = WillDeleteFilesRequest = {}));

var protocol_moniker = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_moniker, "__esModule", { value: true });
protocol_moniker.MonikerRequest = protocol_moniker.MonikerKind = protocol_moniker.UniquenessLevel = void 0;
const messages_1$6 = messages;
/**
 * Moniker uniqueness level to define scope of the moniker.
 *
 * @since 3.16.0
 */
var UniquenessLevel;
(function (UniquenessLevel) {
    /**
     * The moniker is only unique inside a document
     */
    UniquenessLevel.document = 'document';
    /**
     * The moniker is unique inside a project for which a dump got created
     */
    UniquenessLevel.project = 'project';
    /**
     * The moniker is unique inside the group to which a project belongs
     */
    UniquenessLevel.group = 'group';
    /**
     * The moniker is unique inside the moniker scheme.
     */
    UniquenessLevel.scheme = 'scheme';
    /**
     * The moniker is globally unique
     */
    UniquenessLevel.global = 'global';
})(UniquenessLevel || (protocol_moniker.UniquenessLevel = UniquenessLevel = {}));
/**
 * The moniker kind.
 *
 * @since 3.16.0
 */
var MonikerKind;
(function (MonikerKind) {
    /**
     * The moniker represent a symbol that is imported into a project
     */
    MonikerKind.$import = 'import';
    /**
     * The moniker represents a symbol that is exported from a project
     */
    MonikerKind.$export = 'export';
    /**
     * The moniker represents a symbol that is local to a project (e.g. a local
     * variable of a function, a class not visible outside the project, ...)
     */
    MonikerKind.local = 'local';
})(MonikerKind || (protocol_moniker.MonikerKind = MonikerKind = {}));
/**
 * A request to get the moniker of a symbol at a given text document position.
 * The request parameter is of type {@link TextDocumentPositionParams}.
 * The response is of type {@link Moniker Moniker[]} or `null`.
 */
var MonikerRequest;
(function (MonikerRequest) {
    MonikerRequest.method = 'textDocument/moniker';
    MonikerRequest.messageDirection = messages_1$6.MessageDirection.clientToServer;
    MonikerRequest.type = new messages_1$6.ProtocolRequestType(MonikerRequest.method);
})(MonikerRequest || (protocol_moniker.MonikerRequest = MonikerRequest = {}));

var protocol_typeHierarchy = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) TypeFox, Microsoft and others. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_typeHierarchy, "__esModule", { value: true });
protocol_typeHierarchy.TypeHierarchySubtypesRequest = protocol_typeHierarchy.TypeHierarchySupertypesRequest = protocol_typeHierarchy.TypeHierarchyPrepareRequest = void 0;
const messages_1$5 = messages;
/**
 * A request to result a `TypeHierarchyItem` in a document at a given position.
 * Can be used as an input to a subtypes or supertypes type hierarchy.
 *
 * @since 3.17.0
 */
var TypeHierarchyPrepareRequest;
(function (TypeHierarchyPrepareRequest) {
    TypeHierarchyPrepareRequest.method = 'textDocument/prepareTypeHierarchy';
    TypeHierarchyPrepareRequest.messageDirection = messages_1$5.MessageDirection.clientToServer;
    TypeHierarchyPrepareRequest.type = new messages_1$5.ProtocolRequestType(TypeHierarchyPrepareRequest.method);
})(TypeHierarchyPrepareRequest || (protocol_typeHierarchy.TypeHierarchyPrepareRequest = TypeHierarchyPrepareRequest = {}));
/**
 * A request to resolve the supertypes for a given `TypeHierarchyItem`.
 *
 * @since 3.17.0
 */
var TypeHierarchySupertypesRequest;
(function (TypeHierarchySupertypesRequest) {
    TypeHierarchySupertypesRequest.method = 'typeHierarchy/supertypes';
    TypeHierarchySupertypesRequest.messageDirection = messages_1$5.MessageDirection.clientToServer;
    TypeHierarchySupertypesRequest.type = new messages_1$5.ProtocolRequestType(TypeHierarchySupertypesRequest.method);
})(TypeHierarchySupertypesRequest || (protocol_typeHierarchy.TypeHierarchySupertypesRequest = TypeHierarchySupertypesRequest = {}));
/**
 * A request to resolve the subtypes for a given `TypeHierarchyItem`.
 *
 * @since 3.17.0
 */
var TypeHierarchySubtypesRequest;
(function (TypeHierarchySubtypesRequest) {
    TypeHierarchySubtypesRequest.method = 'typeHierarchy/subtypes';
    TypeHierarchySubtypesRequest.messageDirection = messages_1$5.MessageDirection.clientToServer;
    TypeHierarchySubtypesRequest.type = new messages_1$5.ProtocolRequestType(TypeHierarchySubtypesRequest.method);
})(TypeHierarchySubtypesRequest || (protocol_typeHierarchy.TypeHierarchySubtypesRequest = TypeHierarchySubtypesRequest = {}));

var protocol_inlineValue = {};

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(protocol_inlineValue, "__esModule", { value: true });
protocol_inlineValue.InlineValueRefreshRequest = protocol_inlineValue.InlineValueRequest = void 0;
const messages_1$4 = messages;
/**
 * A request to provide inline values in a document. The request's parameter is of
 * type {@link InlineValueParams}, the response is of type
 * {@link InlineValue InlineValue[]} or a Thenable that resolves to such.
 *
 * @since 3.17.0
 */
var InlineValueRequest;
(function (InlineValueRequest) {
    InlineValueRequest.method = 'textDocument/inlineValue';
    InlineValueRequest.messageDirection = messages_1$4.MessageDirection.clientToServer;
    InlineValueRequest.type = new messages_1$4.ProtocolRequestType(InlineValueRequest.method);
})(InlineValueRequest || (protocol_inlineValue.InlineValueRequest = InlineValueRequest = {}));
/**
 * @since 3.17.0
 */
var InlineValueRefreshRequest;
(function (InlineValueRefreshRequest) {
    InlineValueRefreshRequest.method = `workspace/inlineValue/refresh`;
    InlineValueRefreshRequest.messageDirection = messages_1$4.MessageDirection.serverToClient;
    InlineValueRefreshRequest.type = new messages_1$4.ProtocolRequestType0(InlineValueRefreshRequest.method);
})(InlineValueRefreshRequest || (protocol_inlineValue.InlineValueRefreshRequest = InlineValueRefreshRequest = {}));

var protocol_inlayHint = {};

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(protocol_inlayHint, "__esModule", { value: true });
protocol_inlayHint.InlayHintRefreshRequest = protocol_inlayHint.InlayHintResolveRequest = protocol_inlayHint.InlayHintRequest = void 0;
const messages_1$3 = messages;
/**
 * A request to provide inlay hints in a document. The request's parameter is of
 * type {@link InlayHintsParams}, the response is of type
 * {@link InlayHint InlayHint[]} or a Thenable that resolves to such.
 *
 * @since 3.17.0
 */
var InlayHintRequest;
(function (InlayHintRequest) {
    InlayHintRequest.method = 'textDocument/inlayHint';
    InlayHintRequest.messageDirection = messages_1$3.MessageDirection.clientToServer;
    InlayHintRequest.type = new messages_1$3.ProtocolRequestType(InlayHintRequest.method);
})(InlayHintRequest || (protocol_inlayHint.InlayHintRequest = InlayHintRequest = {}));
/**
 * A request to resolve additional properties for an inlay hint.
 * The request's parameter is of type {@link InlayHint}, the response is
 * of type {@link InlayHint} or a Thenable that resolves to such.
 *
 * @since 3.17.0
 */
var InlayHintResolveRequest;
(function (InlayHintResolveRequest) {
    InlayHintResolveRequest.method = 'inlayHint/resolve';
    InlayHintResolveRequest.messageDirection = messages_1$3.MessageDirection.clientToServer;
    InlayHintResolveRequest.type = new messages_1$3.ProtocolRequestType(InlayHintResolveRequest.method);
})(InlayHintResolveRequest || (protocol_inlayHint.InlayHintResolveRequest = InlayHintResolveRequest = {}));
/**
 * @since 3.17.0
 */
var InlayHintRefreshRequest;
(function (InlayHintRefreshRequest) {
    InlayHintRefreshRequest.method = `workspace/inlayHint/refresh`;
    InlayHintRefreshRequest.messageDirection = messages_1$3.MessageDirection.serverToClient;
    InlayHintRefreshRequest.type = new messages_1$3.ProtocolRequestType0(InlayHintRefreshRequest.method);
})(InlayHintRefreshRequest || (protocol_inlayHint.InlayHintRefreshRequest = InlayHintRefreshRequest = {}));

var protocol_diagnostic = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_diagnostic, "__esModule", { value: true });
protocol_diagnostic.DiagnosticRefreshRequest = protocol_diagnostic.WorkspaceDiagnosticRequest = protocol_diagnostic.DocumentDiagnosticRequest = protocol_diagnostic.DocumentDiagnosticReportKind = protocol_diagnostic.DiagnosticServerCancellationData = void 0;
const vscode_jsonrpc_1$1 = main$1;
const Is$3 = is$1;
const messages_1$2 = messages;
/**
 * @since 3.17.0
 */
var DiagnosticServerCancellationData;
(function (DiagnosticServerCancellationData) {
    function is(value) {
        const candidate = value;
        return candidate && Is$3.boolean(candidate.retriggerRequest);
    }
    DiagnosticServerCancellationData.is = is;
})(DiagnosticServerCancellationData || (protocol_diagnostic.DiagnosticServerCancellationData = DiagnosticServerCancellationData = {}));
/**
 * The document diagnostic report kinds.
 *
 * @since 3.17.0
 */
var DocumentDiagnosticReportKind;
(function (DocumentDiagnosticReportKind) {
    /**
     * A diagnostic report with a full
     * set of problems.
     */
    DocumentDiagnosticReportKind.Full = 'full';
    /**
     * A report indicating that the last
     * returned report is still accurate.
     */
    DocumentDiagnosticReportKind.Unchanged = 'unchanged';
})(DocumentDiagnosticReportKind || (protocol_diagnostic.DocumentDiagnosticReportKind = DocumentDiagnosticReportKind = {}));
/**
 * The document diagnostic request definition.
 *
 * @since 3.17.0
 */
var DocumentDiagnosticRequest;
(function (DocumentDiagnosticRequest) {
    DocumentDiagnosticRequest.method = 'textDocument/diagnostic';
    DocumentDiagnosticRequest.messageDirection = messages_1$2.MessageDirection.clientToServer;
    DocumentDiagnosticRequest.type = new messages_1$2.ProtocolRequestType(DocumentDiagnosticRequest.method);
    DocumentDiagnosticRequest.partialResult = new vscode_jsonrpc_1$1.ProgressType();
})(DocumentDiagnosticRequest || (protocol_diagnostic.DocumentDiagnosticRequest = DocumentDiagnosticRequest = {}));
/**
 * The workspace diagnostic request definition.
 *
 * @since 3.17.0
 */
var WorkspaceDiagnosticRequest;
(function (WorkspaceDiagnosticRequest) {
    WorkspaceDiagnosticRequest.method = 'workspace/diagnostic';
    WorkspaceDiagnosticRequest.messageDirection = messages_1$2.MessageDirection.clientToServer;
    WorkspaceDiagnosticRequest.type = new messages_1$2.ProtocolRequestType(WorkspaceDiagnosticRequest.method);
    WorkspaceDiagnosticRequest.partialResult = new vscode_jsonrpc_1$1.ProgressType();
})(WorkspaceDiagnosticRequest || (protocol_diagnostic.WorkspaceDiagnosticRequest = WorkspaceDiagnosticRequest = {}));
/**
 * The diagnostic refresh request definition.
 *
 * @since 3.17.0
 */
var DiagnosticRefreshRequest;
(function (DiagnosticRefreshRequest) {
    DiagnosticRefreshRequest.method = `workspace/diagnostic/refresh`;
    DiagnosticRefreshRequest.messageDirection = messages_1$2.MessageDirection.serverToClient;
    DiagnosticRefreshRequest.type = new messages_1$2.ProtocolRequestType0(DiagnosticRefreshRequest.method);
})(DiagnosticRefreshRequest || (protocol_diagnostic.DiagnosticRefreshRequest = DiagnosticRefreshRequest = {}));

var protocol_notebook = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(protocol_notebook, "__esModule", { value: true });
protocol_notebook.DidCloseNotebookDocumentNotification = protocol_notebook.DidSaveNotebookDocumentNotification = protocol_notebook.DidChangeNotebookDocumentNotification = protocol_notebook.NotebookCellArrayChange = protocol_notebook.DidOpenNotebookDocumentNotification = protocol_notebook.NotebookDocumentSyncRegistrationType = protocol_notebook.NotebookDocument = protocol_notebook.NotebookCell = protocol_notebook.ExecutionSummary = protocol_notebook.NotebookCellKind = void 0;
const vscode_languageserver_types_1 = require$$1;
const Is$2 = is$1;
const messages_1$1 = messages;
/**
 * A notebook cell kind.
 *
 * @since 3.17.0
 */
var NotebookCellKind;
(function (NotebookCellKind) {
    /**
     * A markup-cell is formatted source that is used for display.
     */
    NotebookCellKind.Markup = 1;
    /**
     * A code-cell is source code.
     */
    NotebookCellKind.Code = 2;
    function is(value) {
        return value === 1 || value === 2;
    }
    NotebookCellKind.is = is;
})(NotebookCellKind || (protocol_notebook.NotebookCellKind = NotebookCellKind = {}));
var ExecutionSummary;
(function (ExecutionSummary) {
    function create(executionOrder, success) {
        const result = { executionOrder };
        if (success === true || success === false) {
            result.success = success;
        }
        return result;
    }
    ExecutionSummary.create = create;
    function is(value) {
        const candidate = value;
        return Is$2.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.executionOrder) && (candidate.success === undefined || Is$2.boolean(candidate.success));
    }
    ExecutionSummary.is = is;
    function equals(one, other) {
        if (one === other) {
            return true;
        }
        if (one === null || one === undefined || other === null || other === undefined) {
            return false;
        }
        return one.executionOrder === other.executionOrder && one.success === other.success;
    }
    ExecutionSummary.equals = equals;
})(ExecutionSummary || (protocol_notebook.ExecutionSummary = ExecutionSummary = {}));
var NotebookCell;
(function (NotebookCell) {
    function create(kind, document) {
        return { kind, document };
    }
    NotebookCell.create = create;
    function is(value) {
        const candidate = value;
        return Is$2.objectLiteral(candidate) && NotebookCellKind.is(candidate.kind) && vscode_languageserver_types_1.DocumentUri.is(candidate.document) &&
            (candidate.metadata === undefined || Is$2.objectLiteral(candidate.metadata));
    }
    NotebookCell.is = is;
    function diff(one, two) {
        const result = new Set();
        if (one.document !== two.document) {
            result.add('document');
        }
        if (one.kind !== two.kind) {
            result.add('kind');
        }
        if (one.executionSummary !== two.executionSummary) {
            result.add('executionSummary');
        }
        if ((one.metadata !== undefined || two.metadata !== undefined) && !equalsMetadata(one.metadata, two.metadata)) {
            result.add('metadata');
        }
        if ((one.executionSummary !== undefined || two.executionSummary !== undefined) && !ExecutionSummary.equals(one.executionSummary, two.executionSummary)) {
            result.add('executionSummary');
        }
        return result;
    }
    NotebookCell.diff = diff;
    function equalsMetadata(one, other) {
        if (one === other) {
            return true;
        }
        if (one === null || one === undefined || other === null || other === undefined) {
            return false;
        }
        if (typeof one !== typeof other) {
            return false;
        }
        if (typeof one !== 'object') {
            return false;
        }
        const oneArray = Array.isArray(one);
        const otherArray = Array.isArray(other);
        if (oneArray !== otherArray) {
            return false;
        }
        if (oneArray && otherArray) {
            if (one.length !== other.length) {
                return false;
            }
            for (let i = 0; i < one.length; i++) {
                if (!equalsMetadata(one[i], other[i])) {
                    return false;
                }
            }
        }
        if (Is$2.objectLiteral(one) && Is$2.objectLiteral(other)) {
            const oneKeys = Object.keys(one);
            const otherKeys = Object.keys(other);
            if (oneKeys.length !== otherKeys.length) {
                return false;
            }
            oneKeys.sort();
            otherKeys.sort();
            if (!equalsMetadata(oneKeys, otherKeys)) {
                return false;
            }
            for (let i = 0; i < oneKeys.length; i++) {
                const prop = oneKeys[i];
                if (!equalsMetadata(one[prop], other[prop])) {
                    return false;
                }
            }
        }
        return true;
    }
})(NotebookCell || (protocol_notebook.NotebookCell = NotebookCell = {}));
var NotebookDocument;
(function (NotebookDocument) {
    function create(uri, notebookType, version, cells) {
        return { uri, notebookType, version, cells };
    }
    NotebookDocument.create = create;
    function is(value) {
        const candidate = value;
        return Is$2.objectLiteral(candidate) && Is$2.string(candidate.uri) && vscode_languageserver_types_1.integer.is(candidate.version) && Is$2.typedArray(candidate.cells, NotebookCell.is);
    }
    NotebookDocument.is = is;
})(NotebookDocument || (protocol_notebook.NotebookDocument = NotebookDocument = {}));
var NotebookDocumentSyncRegistrationType;
(function (NotebookDocumentSyncRegistrationType) {
    NotebookDocumentSyncRegistrationType.method = 'notebookDocument/sync';
    NotebookDocumentSyncRegistrationType.messageDirection = messages_1$1.MessageDirection.clientToServer;
    NotebookDocumentSyncRegistrationType.type = new messages_1$1.RegistrationType(NotebookDocumentSyncRegistrationType.method);
})(NotebookDocumentSyncRegistrationType || (protocol_notebook.NotebookDocumentSyncRegistrationType = NotebookDocumentSyncRegistrationType = {}));
/**
 * A notification sent when a notebook opens.
 *
 * @since 3.17.0
 */
var DidOpenNotebookDocumentNotification;
(function (DidOpenNotebookDocumentNotification) {
    DidOpenNotebookDocumentNotification.method = 'notebookDocument/didOpen';
    DidOpenNotebookDocumentNotification.messageDirection = messages_1$1.MessageDirection.clientToServer;
    DidOpenNotebookDocumentNotification.type = new messages_1$1.ProtocolNotificationType(DidOpenNotebookDocumentNotification.method);
    DidOpenNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidOpenNotebookDocumentNotification || (protocol_notebook.DidOpenNotebookDocumentNotification = DidOpenNotebookDocumentNotification = {}));
var NotebookCellArrayChange;
(function (NotebookCellArrayChange) {
    function is(value) {
        const candidate = value;
        return Is$2.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.start) && vscode_languageserver_types_1.uinteger.is(candidate.deleteCount) && (candidate.cells === undefined || Is$2.typedArray(candidate.cells, NotebookCell.is));
    }
    NotebookCellArrayChange.is = is;
    function create(start, deleteCount, cells) {
        const result = { start, deleteCount };
        if (cells !== undefined) {
            result.cells = cells;
        }
        return result;
    }
    NotebookCellArrayChange.create = create;
})(NotebookCellArrayChange || (protocol_notebook.NotebookCellArrayChange = NotebookCellArrayChange = {}));
var DidChangeNotebookDocumentNotification;
(function (DidChangeNotebookDocumentNotification) {
    DidChangeNotebookDocumentNotification.method = 'notebookDocument/didChange';
    DidChangeNotebookDocumentNotification.messageDirection = messages_1$1.MessageDirection.clientToServer;
    DidChangeNotebookDocumentNotification.type = new messages_1$1.ProtocolNotificationType(DidChangeNotebookDocumentNotification.method);
    DidChangeNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidChangeNotebookDocumentNotification || (protocol_notebook.DidChangeNotebookDocumentNotification = DidChangeNotebookDocumentNotification = {}));
/**
 * A notification sent when a notebook document is saved.
 *
 * @since 3.17.0
 */
var DidSaveNotebookDocumentNotification;
(function (DidSaveNotebookDocumentNotification) {
    DidSaveNotebookDocumentNotification.method = 'notebookDocument/didSave';
    DidSaveNotebookDocumentNotification.messageDirection = messages_1$1.MessageDirection.clientToServer;
    DidSaveNotebookDocumentNotification.type = new messages_1$1.ProtocolNotificationType(DidSaveNotebookDocumentNotification.method);
    DidSaveNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidSaveNotebookDocumentNotification || (protocol_notebook.DidSaveNotebookDocumentNotification = DidSaveNotebookDocumentNotification = {}));
/**
 * A notification sent when a notebook closes.
 *
 * @since 3.17.0
 */
var DidCloseNotebookDocumentNotification;
(function (DidCloseNotebookDocumentNotification) {
    DidCloseNotebookDocumentNotification.method = 'notebookDocument/didClose';
    DidCloseNotebookDocumentNotification.messageDirection = messages_1$1.MessageDirection.clientToServer;
    DidCloseNotebookDocumentNotification.type = new messages_1$1.ProtocolNotificationType(DidCloseNotebookDocumentNotification.method);
    DidCloseNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidCloseNotebookDocumentNotification || (protocol_notebook.DidCloseNotebookDocumentNotification = DidCloseNotebookDocumentNotification = {}));

var protocol_inlineCompletion = {};

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(protocol_inlineCompletion, "__esModule", { value: true });
protocol_inlineCompletion.InlineCompletionRequest = void 0;
const messages_1 = messages;
/**
 * A request to provide inline completions in a document. The request's parameter is of
 * type {@link InlineCompletionParams}, the response is of type
 * {@link InlineCompletion InlineCompletion[]} or a Thenable that resolves to such.
 *
 * @since 3.18.0
 * @proposed
 */
var InlineCompletionRequest;
(function (InlineCompletionRequest) {
    InlineCompletionRequest.method = 'textDocument/inlineCompletion';
    InlineCompletionRequest.messageDirection = messages_1.MessageDirection.clientToServer;
    InlineCompletionRequest.type = new messages_1.ProtocolRequestType(InlineCompletionRequest.method);
})(InlineCompletionRequest || (protocol_inlineCompletion.InlineCompletionRequest = InlineCompletionRequest = {}));

(function (exports) {
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.WorkspaceSymbolRequest = exports.CodeActionResolveRequest = exports.CodeActionRequest = exports.DocumentSymbolRequest = exports.DocumentHighlightRequest = exports.ReferencesRequest = exports.DefinitionRequest = exports.SignatureHelpRequest = exports.SignatureHelpTriggerKind = exports.HoverRequest = exports.CompletionResolveRequest = exports.CompletionRequest = exports.CompletionTriggerKind = exports.PublishDiagnosticsNotification = exports.WatchKind = exports.RelativePattern = exports.FileChangeType = exports.DidChangeWatchedFilesNotification = exports.WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentNotification = exports.TextDocumentSaveReason = exports.DidSaveTextDocumentNotification = exports.DidCloseTextDocumentNotification = exports.DidChangeTextDocumentNotification = exports.TextDocumentContentChangeEvent = exports.DidOpenTextDocumentNotification = exports.TextDocumentSyncKind = exports.TelemetryEventNotification = exports.LogMessageNotification = exports.ShowMessageRequest = exports.ShowMessageNotification = exports.MessageType = exports.DidChangeConfigurationNotification = exports.ExitNotification = exports.ShutdownRequest = exports.InitializedNotification = exports.InitializeErrorCodes = exports.InitializeRequest = exports.WorkDoneProgressOptions = exports.TextDocumentRegistrationOptions = exports.StaticRegistrationOptions = exports.PositionEncodingKind = exports.FailureHandlingKind = exports.ResourceOperationKind = exports.UnregistrationRequest = exports.RegistrationRequest = exports.DocumentSelector = exports.NotebookCellTextDocumentFilter = exports.NotebookDocumentFilter = exports.TextDocumentFilter = void 0;
	exports.MonikerRequest = exports.MonikerKind = exports.UniquenessLevel = exports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.WillRenameFilesRequest = exports.DidRenameFilesNotification = exports.WillCreateFilesRequest = exports.DidCreateFilesNotification = exports.FileOperationPatternKind = exports.LinkedEditingRangeRequest = exports.ShowDocumentRequest = exports.SemanticTokensRegistrationType = exports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.TokenFormat = exports.CallHierarchyPrepareRequest = exports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = exports.SelectionRangeRequest = exports.DeclarationRequest = exports.FoldingRangeRefreshRequest = exports.FoldingRangeRequest = exports.ColorPresentationRequest = exports.DocumentColorRequest = exports.ConfigurationRequest = exports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = exports.TypeDefinitionRequest = exports.ImplementationRequest = exports.ApplyWorkspaceEditRequest = exports.ExecuteCommandRequest = exports.PrepareRenameRequest = exports.RenameRequest = exports.PrepareSupportDefaultBehavior = exports.DocumentOnTypeFormattingRequest = exports.DocumentRangesFormattingRequest = exports.DocumentRangeFormattingRequest = exports.DocumentFormattingRequest = exports.DocumentLinkResolveRequest = exports.DocumentLinkRequest = exports.CodeLensRefreshRequest = exports.CodeLensResolveRequest = exports.CodeLensRequest = exports.WorkspaceSymbolResolveRequest = void 0;
	exports.InlineCompletionRequest = exports.DidCloseNotebookDocumentNotification = exports.DidSaveNotebookDocumentNotification = exports.DidChangeNotebookDocumentNotification = exports.NotebookCellArrayChange = exports.DidOpenNotebookDocumentNotification = exports.NotebookDocumentSyncRegistrationType = exports.NotebookDocument = exports.NotebookCell = exports.ExecutionSummary = exports.NotebookCellKind = exports.DiagnosticRefreshRequest = exports.WorkspaceDiagnosticRequest = exports.DocumentDiagnosticRequest = exports.DocumentDiagnosticReportKind = exports.DiagnosticServerCancellationData = exports.InlayHintRefreshRequest = exports.InlayHintResolveRequest = exports.InlayHintRequest = exports.InlineValueRefreshRequest = exports.InlineValueRequest = exports.TypeHierarchySupertypesRequest = exports.TypeHierarchySubtypesRequest = exports.TypeHierarchyPrepareRequest = void 0;
	const messages_1 = messages;
	const vscode_languageserver_types_1 = require$$1;
	const Is = is$1;
	const protocol_implementation_1 = protocol_implementation;
	Object.defineProperty(exports, "ImplementationRequest", { enumerable: true, get: function () { return protocol_implementation_1.ImplementationRequest; } });
	const protocol_typeDefinition_1 = protocol_typeDefinition;
	Object.defineProperty(exports, "TypeDefinitionRequest", { enumerable: true, get: function () { return protocol_typeDefinition_1.TypeDefinitionRequest; } });
	const protocol_workspaceFolder_1 = protocol_workspaceFolder;
	Object.defineProperty(exports, "WorkspaceFoldersRequest", { enumerable: true, get: function () { return protocol_workspaceFolder_1.WorkspaceFoldersRequest; } });
	Object.defineProperty(exports, "DidChangeWorkspaceFoldersNotification", { enumerable: true, get: function () { return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification; } });
	const protocol_configuration_1 = protocol_configuration;
	Object.defineProperty(exports, "ConfigurationRequest", { enumerable: true, get: function () { return protocol_configuration_1.ConfigurationRequest; } });
	const protocol_colorProvider_1 = protocol_colorProvider;
	Object.defineProperty(exports, "DocumentColorRequest", { enumerable: true, get: function () { return protocol_colorProvider_1.DocumentColorRequest; } });
	Object.defineProperty(exports, "ColorPresentationRequest", { enumerable: true, get: function () { return protocol_colorProvider_1.ColorPresentationRequest; } });
	const protocol_foldingRange_1 = protocol_foldingRange;
	Object.defineProperty(exports, "FoldingRangeRequest", { enumerable: true, get: function () { return protocol_foldingRange_1.FoldingRangeRequest; } });
	Object.defineProperty(exports, "FoldingRangeRefreshRequest", { enumerable: true, get: function () { return protocol_foldingRange_1.FoldingRangeRefreshRequest; } });
	const protocol_declaration_1 = protocol_declaration;
	Object.defineProperty(exports, "DeclarationRequest", { enumerable: true, get: function () { return protocol_declaration_1.DeclarationRequest; } });
	const protocol_selectionRange_1 = protocol_selectionRange;
	Object.defineProperty(exports, "SelectionRangeRequest", { enumerable: true, get: function () { return protocol_selectionRange_1.SelectionRangeRequest; } });
	const protocol_progress_1 = protocol_progress;
	Object.defineProperty(exports, "WorkDoneProgress", { enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgress; } });
	Object.defineProperty(exports, "WorkDoneProgressCreateRequest", { enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgressCreateRequest; } });
	Object.defineProperty(exports, "WorkDoneProgressCancelNotification", { enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgressCancelNotification; } });
	const protocol_callHierarchy_1 = protocol_callHierarchy;
	Object.defineProperty(exports, "CallHierarchyIncomingCallsRequest", { enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest; } });
	Object.defineProperty(exports, "CallHierarchyOutgoingCallsRequest", { enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest; } });
	Object.defineProperty(exports, "CallHierarchyPrepareRequest", { enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyPrepareRequest; } });
	const protocol_semanticTokens_1 = protocol_semanticTokens;
	Object.defineProperty(exports, "TokenFormat", { enumerable: true, get: function () { return protocol_semanticTokens_1.TokenFormat; } });
	Object.defineProperty(exports, "SemanticTokensRequest", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRequest; } });
	Object.defineProperty(exports, "SemanticTokensDeltaRequest", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensDeltaRequest; } });
	Object.defineProperty(exports, "SemanticTokensRangeRequest", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRangeRequest; } });
	Object.defineProperty(exports, "SemanticTokensRefreshRequest", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRefreshRequest; } });
	Object.defineProperty(exports, "SemanticTokensRegistrationType", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRegistrationType; } });
	const protocol_showDocument_1 = protocol_showDocument;
	Object.defineProperty(exports, "ShowDocumentRequest", { enumerable: true, get: function () { return protocol_showDocument_1.ShowDocumentRequest; } });
	const protocol_linkedEditingRange_1 = protocol_linkedEditingRange;
	Object.defineProperty(exports, "LinkedEditingRangeRequest", { enumerable: true, get: function () { return protocol_linkedEditingRange_1.LinkedEditingRangeRequest; } });
	const protocol_fileOperations_1 = protocol_fileOperations;
	Object.defineProperty(exports, "FileOperationPatternKind", { enumerable: true, get: function () { return protocol_fileOperations_1.FileOperationPatternKind; } });
	Object.defineProperty(exports, "DidCreateFilesNotification", { enumerable: true, get: function () { return protocol_fileOperations_1.DidCreateFilesNotification; } });
	Object.defineProperty(exports, "WillCreateFilesRequest", { enumerable: true, get: function () { return protocol_fileOperations_1.WillCreateFilesRequest; } });
	Object.defineProperty(exports, "DidRenameFilesNotification", { enumerable: true, get: function () { return protocol_fileOperations_1.DidRenameFilesNotification; } });
	Object.defineProperty(exports, "WillRenameFilesRequest", { enumerable: true, get: function () { return protocol_fileOperations_1.WillRenameFilesRequest; } });
	Object.defineProperty(exports, "DidDeleteFilesNotification", { enumerable: true, get: function () { return protocol_fileOperations_1.DidDeleteFilesNotification; } });
	Object.defineProperty(exports, "WillDeleteFilesRequest", { enumerable: true, get: function () { return protocol_fileOperations_1.WillDeleteFilesRequest; } });
	const protocol_moniker_1 = protocol_moniker;
	Object.defineProperty(exports, "UniquenessLevel", { enumerable: true, get: function () { return protocol_moniker_1.UniquenessLevel; } });
	Object.defineProperty(exports, "MonikerKind", { enumerable: true, get: function () { return protocol_moniker_1.MonikerKind; } });
	Object.defineProperty(exports, "MonikerRequest", { enumerable: true, get: function () { return protocol_moniker_1.MonikerRequest; } });
	const protocol_typeHierarchy_1 = protocol_typeHierarchy;
	Object.defineProperty(exports, "TypeHierarchyPrepareRequest", { enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest; } });
	Object.defineProperty(exports, "TypeHierarchySubtypesRequest", { enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest; } });
	Object.defineProperty(exports, "TypeHierarchySupertypesRequest", { enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest; } });
	const protocol_inlineValue_1 = protocol_inlineValue;
	Object.defineProperty(exports, "InlineValueRequest", { enumerable: true, get: function () { return protocol_inlineValue_1.InlineValueRequest; } });
	Object.defineProperty(exports, "InlineValueRefreshRequest", { enumerable: true, get: function () { return protocol_inlineValue_1.InlineValueRefreshRequest; } });
	const protocol_inlayHint_1 = protocol_inlayHint;
	Object.defineProperty(exports, "InlayHintRequest", { enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintRequest; } });
	Object.defineProperty(exports, "InlayHintResolveRequest", { enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintResolveRequest; } });
	Object.defineProperty(exports, "InlayHintRefreshRequest", { enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintRefreshRequest; } });
	const protocol_diagnostic_1 = protocol_diagnostic;
	Object.defineProperty(exports, "DiagnosticServerCancellationData", { enumerable: true, get: function () { return protocol_diagnostic_1.DiagnosticServerCancellationData; } });
	Object.defineProperty(exports, "DocumentDiagnosticReportKind", { enumerable: true, get: function () { return protocol_diagnostic_1.DocumentDiagnosticReportKind; } });
	Object.defineProperty(exports, "DocumentDiagnosticRequest", { enumerable: true, get: function () { return protocol_diagnostic_1.DocumentDiagnosticRequest; } });
	Object.defineProperty(exports, "WorkspaceDiagnosticRequest", { enumerable: true, get: function () { return protocol_diagnostic_1.WorkspaceDiagnosticRequest; } });
	Object.defineProperty(exports, "DiagnosticRefreshRequest", { enumerable: true, get: function () { return protocol_diagnostic_1.DiagnosticRefreshRequest; } });
	const protocol_notebook_1 = protocol_notebook;
	Object.defineProperty(exports, "NotebookCellKind", { enumerable: true, get: function () { return protocol_notebook_1.NotebookCellKind; } });
	Object.defineProperty(exports, "ExecutionSummary", { enumerable: true, get: function () { return protocol_notebook_1.ExecutionSummary; } });
	Object.defineProperty(exports, "NotebookCell", { enumerable: true, get: function () { return protocol_notebook_1.NotebookCell; } });
	Object.defineProperty(exports, "NotebookDocument", { enumerable: true, get: function () { return protocol_notebook_1.NotebookDocument; } });
	Object.defineProperty(exports, "NotebookDocumentSyncRegistrationType", { enumerable: true, get: function () { return protocol_notebook_1.NotebookDocumentSyncRegistrationType; } });
	Object.defineProperty(exports, "DidOpenNotebookDocumentNotification", { enumerable: true, get: function () { return protocol_notebook_1.DidOpenNotebookDocumentNotification; } });
	Object.defineProperty(exports, "NotebookCellArrayChange", { enumerable: true, get: function () { return protocol_notebook_1.NotebookCellArrayChange; } });
	Object.defineProperty(exports, "DidChangeNotebookDocumentNotification", { enumerable: true, get: function () { return protocol_notebook_1.DidChangeNotebookDocumentNotification; } });
	Object.defineProperty(exports, "DidSaveNotebookDocumentNotification", { enumerable: true, get: function () { return protocol_notebook_1.DidSaveNotebookDocumentNotification; } });
	Object.defineProperty(exports, "DidCloseNotebookDocumentNotification", { enumerable: true, get: function () { return protocol_notebook_1.DidCloseNotebookDocumentNotification; } });
	const protocol_inlineCompletion_1 = protocol_inlineCompletion;
	Object.defineProperty(exports, "InlineCompletionRequest", { enumerable: true, get: function () { return protocol_inlineCompletion_1.InlineCompletionRequest; } });
	/**
	 * The TextDocumentFilter namespace provides helper functions to work with
	 * {@link TextDocumentFilter} literals.
	 *
	 * @since 3.17.0
	 */
	var TextDocumentFilter;
	(function (TextDocumentFilter) {
	    function is(value) {
	        const candidate = value;
	        return Is.string(candidate) || (Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern));
	    }
	    TextDocumentFilter.is = is;
	})(TextDocumentFilter || (exports.TextDocumentFilter = TextDocumentFilter = {}));
	/**
	 * The NotebookDocumentFilter namespace provides helper functions to work with
	 * {@link NotebookDocumentFilter} literals.
	 *
	 * @since 3.17.0
	 */
	var NotebookDocumentFilter;
	(function (NotebookDocumentFilter) {
	    function is(value) {
	        const candidate = value;
	        return Is.objectLiteral(candidate) && (Is.string(candidate.notebookType) || Is.string(candidate.scheme) || Is.string(candidate.pattern));
	    }
	    NotebookDocumentFilter.is = is;
	})(NotebookDocumentFilter || (exports.NotebookDocumentFilter = NotebookDocumentFilter = {}));
	/**
	 * The NotebookCellTextDocumentFilter namespace provides helper functions to work with
	 * {@link NotebookCellTextDocumentFilter} literals.
	 *
	 * @since 3.17.0
	 */
	var NotebookCellTextDocumentFilter;
	(function (NotebookCellTextDocumentFilter) {
	    function is(value) {
	        const candidate = value;
	        return Is.objectLiteral(candidate)
	            && (Is.string(candidate.notebook) || NotebookDocumentFilter.is(candidate.notebook))
	            && (candidate.language === undefined || Is.string(candidate.language));
	    }
	    NotebookCellTextDocumentFilter.is = is;
	})(NotebookCellTextDocumentFilter || (exports.NotebookCellTextDocumentFilter = NotebookCellTextDocumentFilter = {}));
	/**
	 * The DocumentSelector namespace provides helper functions to work with
	 * {@link DocumentSelector}s.
	 */
	var DocumentSelector;
	(function (DocumentSelector) {
	    function is(value) {
	        if (!Array.isArray(value)) {
	            return false;
	        }
	        for (let elem of value) {
	            if (!Is.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) {
	                return false;
	            }
	        }
	        return true;
	    }
	    DocumentSelector.is = is;
	})(DocumentSelector || (exports.DocumentSelector = DocumentSelector = {}));
	/**
	 * The `client/registerCapability` request is sent from the server to the client to register a new capability
	 * handler on the client side.
	 */
	var RegistrationRequest;
	(function (RegistrationRequest) {
	    RegistrationRequest.method = 'client/registerCapability';
	    RegistrationRequest.messageDirection = messages_1.MessageDirection.serverToClient;
	    RegistrationRequest.type = new messages_1.ProtocolRequestType(RegistrationRequest.method);
	})(RegistrationRequest || (exports.RegistrationRequest = RegistrationRequest = {}));
	/**
	 * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
	 * handler on the client side.
	 */
	var UnregistrationRequest;
	(function (UnregistrationRequest) {
	    UnregistrationRequest.method = 'client/unregisterCapability';
	    UnregistrationRequest.messageDirection = messages_1.MessageDirection.serverToClient;
	    UnregistrationRequest.type = new messages_1.ProtocolRequestType(UnregistrationRequest.method);
	})(UnregistrationRequest || (exports.UnregistrationRequest = UnregistrationRequest = {}));
	var ResourceOperationKind;
	(function (ResourceOperationKind) {
	    /**
	     * Supports creating new files and folders.
	     */
	    ResourceOperationKind.Create = 'create';
	    /**
	     * Supports renaming existing files and folders.
	     */
	    ResourceOperationKind.Rename = 'rename';
	    /**
	     * Supports deleting existing files and folders.
	     */
	    ResourceOperationKind.Delete = 'delete';
	})(ResourceOperationKind || (exports.ResourceOperationKind = ResourceOperationKind = {}));
	var FailureHandlingKind;
	(function (FailureHandlingKind) {
	    /**
	     * Applying the workspace change is simply aborted if one of the changes provided
	     * fails. All operations executed before the failing operation stay executed.
	     */
	    FailureHandlingKind.Abort = 'abort';
	    /**
	     * All operations are executed transactional. That means they either all
	     * succeed or no changes at all are applied to the workspace.
	     */
	    FailureHandlingKind.Transactional = 'transactional';
	    /**
	     * If the workspace edit contains only textual file changes they are executed transactional.
	     * If resource changes (create, rename or delete file) are part of the change the failure
	     * handling strategy is abort.
	     */
	    FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
	    /**
	     * The client tries to undo the operations already executed. But there is no
	     * guarantee that this is succeeding.
	     */
	    FailureHandlingKind.Undo = 'undo';
	})(FailureHandlingKind || (exports.FailureHandlingKind = FailureHandlingKind = {}));
	/**
	 * A set of predefined position encoding kinds.
	 *
	 * @since 3.17.0
	 */
	var PositionEncodingKind;
	(function (PositionEncodingKind) {
	    /**
	     * Character offsets count UTF-8 code units (e.g. bytes).
	     */
	    PositionEncodingKind.UTF8 = 'utf-8';
	    /**
	     * Character offsets count UTF-16 code units.
	     *
	     * This is the default and must always be supported
	     * by servers
	     */
	    PositionEncodingKind.UTF16 = 'utf-16';
	    /**
	     * Character offsets count UTF-32 code units.
	     *
	     * Implementation note: these are the same as Unicode codepoints,
	     * so this `PositionEncodingKind` may also be used for an
	     * encoding-agnostic representation of character offsets.
	     */
	    PositionEncodingKind.UTF32 = 'utf-32';
	})(PositionEncodingKind || (exports.PositionEncodingKind = PositionEncodingKind = {}));
	/**
	 * The StaticRegistrationOptions namespace provides helper functions to work with
	 * {@link StaticRegistrationOptions} literals.
	 */
	var StaticRegistrationOptions;
	(function (StaticRegistrationOptions) {
	    function hasId(value) {
	        const candidate = value;
	        return candidate && Is.string(candidate.id) && candidate.id.length > 0;
	    }
	    StaticRegistrationOptions.hasId = hasId;
	})(StaticRegistrationOptions || (exports.StaticRegistrationOptions = StaticRegistrationOptions = {}));
	/**
	 * The TextDocumentRegistrationOptions namespace provides helper functions to work with
	 * {@link TextDocumentRegistrationOptions} literals.
	 */
	var TextDocumentRegistrationOptions;
	(function (TextDocumentRegistrationOptions) {
	    function is(value) {
	        const candidate = value;
	        return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
	    }
	    TextDocumentRegistrationOptions.is = is;
	})(TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = TextDocumentRegistrationOptions = {}));
	/**
	 * The WorkDoneProgressOptions namespace provides helper functions to work with
	 * {@link WorkDoneProgressOptions} literals.
	 */
	var WorkDoneProgressOptions;
	(function (WorkDoneProgressOptions) {
	    function is(value) {
	        const candidate = value;
	        return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
	    }
	    WorkDoneProgressOptions.is = is;
	    function hasWorkDoneProgress(value) {
	        const candidate = value;
	        return candidate && Is.boolean(candidate.workDoneProgress);
	    }
	    WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
	})(WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = WorkDoneProgressOptions = {}));
	/**
	 * The initialize request is sent from the client to the server.
	 * It is sent once as the request after starting up the server.
	 * The requests parameter is of type {@link InitializeParams}
	 * the response if of type {@link InitializeResult} of a Thenable that
	 * resolves to such.
	 */
	var InitializeRequest;
	(function (InitializeRequest) {
	    InitializeRequest.method = 'initialize';
	    InitializeRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    InitializeRequest.type = new messages_1.ProtocolRequestType(InitializeRequest.method);
	})(InitializeRequest || (exports.InitializeRequest = InitializeRequest = {}));
	/**
	 * Known error codes for an `InitializeErrorCodes`;
	 */
	var InitializeErrorCodes;
	(function (InitializeErrorCodes) {
	    /**
	     * If the protocol version provided by the client can't be handled by the server.
	     *
	     * @deprecated This initialize error got replaced by client capabilities. There is
	     * no version handshake in version 3.0x
	     */
	    InitializeErrorCodes.unknownProtocolVersion = 1;
	})(InitializeErrorCodes || (exports.InitializeErrorCodes = InitializeErrorCodes = {}));
	/**
	 * The initialized notification is sent from the client to the
	 * server after the client is fully initialized and the server
	 * is allowed to send requests from the server to the client.
	 */
	var InitializedNotification;
	(function (InitializedNotification) {
	    InitializedNotification.method = 'initialized';
	    InitializedNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    InitializedNotification.type = new messages_1.ProtocolNotificationType(InitializedNotification.method);
	})(InitializedNotification || (exports.InitializedNotification = InitializedNotification = {}));
	//---- Shutdown Method ----
	/**
	 * A shutdown request is sent from the client to the server.
	 * It is sent once when the client decides to shutdown the
	 * server. The only notification that is sent after a shutdown request
	 * is the exit event.
	 */
	var ShutdownRequest;
	(function (ShutdownRequest) {
	    ShutdownRequest.method = 'shutdown';
	    ShutdownRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    ShutdownRequest.type = new messages_1.ProtocolRequestType0(ShutdownRequest.method);
	})(ShutdownRequest || (exports.ShutdownRequest = ShutdownRequest = {}));
	//---- Exit Notification ----
	/**
	 * The exit event is sent from the client to the server to
	 * ask the server to exit its process.
	 */
	var ExitNotification;
	(function (ExitNotification) {
	    ExitNotification.method = 'exit';
	    ExitNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    ExitNotification.type = new messages_1.ProtocolNotificationType0(ExitNotification.method);
	})(ExitNotification || (exports.ExitNotification = ExitNotification = {}));
	/**
	 * The configuration change notification is sent from the client to the server
	 * when the client's configuration has changed. The notification contains
	 * the changed configuration as defined by the language client.
	 */
	var DidChangeConfigurationNotification;
	(function (DidChangeConfigurationNotification) {
	    DidChangeConfigurationNotification.method = 'workspace/didChangeConfiguration';
	    DidChangeConfigurationNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification.method);
	})(DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = DidChangeConfigurationNotification = {}));
	//---- Message show and log notifications ----
	/**
	 * The message type
	 */
	var MessageType;
	(function (MessageType) {
	    /**
	     * An error message.
	     */
	    MessageType.Error = 1;
	    /**
	     * A warning message.
	     */
	    MessageType.Warning = 2;
	    /**
	     * An information message.
	     */
	    MessageType.Info = 3;
	    /**
	     * A log message.
	     */
	    MessageType.Log = 4;
	    /**
	     * A debug message.
	     *
	     * @since 3.18.0
	     */
	    MessageType.Debug = 5;
	})(MessageType || (exports.MessageType = MessageType = {}));
	/**
	 * The show message notification is sent from a server to a client to ask
	 * the client to display a particular message in the user interface.
	 */
	var ShowMessageNotification;
	(function (ShowMessageNotification) {
	    ShowMessageNotification.method = 'window/showMessage';
	    ShowMessageNotification.messageDirection = messages_1.MessageDirection.serverToClient;
	    ShowMessageNotification.type = new messages_1.ProtocolNotificationType(ShowMessageNotification.method);
	})(ShowMessageNotification || (exports.ShowMessageNotification = ShowMessageNotification = {}));
	/**
	 * The show message request is sent from the server to the client to show a message
	 * and a set of options actions to the user.
	 */
	var ShowMessageRequest;
	(function (ShowMessageRequest) {
	    ShowMessageRequest.method = 'window/showMessageRequest';
	    ShowMessageRequest.messageDirection = messages_1.MessageDirection.serverToClient;
	    ShowMessageRequest.type = new messages_1.ProtocolRequestType(ShowMessageRequest.method);
	})(ShowMessageRequest || (exports.ShowMessageRequest = ShowMessageRequest = {}));
	/**
	 * The log message notification is sent from the server to the client to ask
	 * the client to log a particular message.
	 */
	var LogMessageNotification;
	(function (LogMessageNotification) {
	    LogMessageNotification.method = 'window/logMessage';
	    LogMessageNotification.messageDirection = messages_1.MessageDirection.serverToClient;
	    LogMessageNotification.type = new messages_1.ProtocolNotificationType(LogMessageNotification.method);
	})(LogMessageNotification || (exports.LogMessageNotification = LogMessageNotification = {}));
	//---- Telemetry notification
	/**
	 * The telemetry event notification is sent from the server to the client to ask
	 * the client to log telemetry data.
	 */
	var TelemetryEventNotification;
	(function (TelemetryEventNotification) {
	    TelemetryEventNotification.method = 'telemetry/event';
	    TelemetryEventNotification.messageDirection = messages_1.MessageDirection.serverToClient;
	    TelemetryEventNotification.type = new messages_1.ProtocolNotificationType(TelemetryEventNotification.method);
	})(TelemetryEventNotification || (exports.TelemetryEventNotification = TelemetryEventNotification = {}));
	/**
	 * Defines how the host (editor) should sync
	 * document changes to the language server.
	 */
	var TextDocumentSyncKind;
	(function (TextDocumentSyncKind) {
	    /**
	     * Documents should not be synced at all.
	     */
	    TextDocumentSyncKind.None = 0;
	    /**
	     * Documents are synced by always sending the full content
	     * of the document.
	     */
	    TextDocumentSyncKind.Full = 1;
	    /**
	     * Documents are synced by sending the full content on open.
	     * After that only incremental updates to the document are
	     * send.
	     */
	    TextDocumentSyncKind.Incremental = 2;
	})(TextDocumentSyncKind || (exports.TextDocumentSyncKind = TextDocumentSyncKind = {}));
	/**
	 * The document open notification is sent from the client to the server to signal
	 * newly opened text documents. The document's truth is now managed by the client
	 * and the server must not try to read the document's truth using the document's
	 * uri. Open in this sense means it is managed by the client. It doesn't necessarily
	 * mean that its content is presented in an editor. An open notification must not
	 * be sent more than once without a corresponding close notification send before.
	 * This means open and close notification must be balanced and the max open count
	 * is one.
	 */
	var DidOpenTextDocumentNotification;
	(function (DidOpenTextDocumentNotification) {
	    DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
	    DidOpenTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
	})(DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = DidOpenTextDocumentNotification = {}));
	var TextDocumentContentChangeEvent;
	(function (TextDocumentContentChangeEvent) {
	    /**
	     * Checks whether the information describes a delta event.
	     */
	    function isIncremental(event) {
	        let candidate = event;
	        return candidate !== undefined && candidate !== null &&
	            typeof candidate.text === 'string' && candidate.range !== undefined &&
	            (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');
	    }
	    TextDocumentContentChangeEvent.isIncremental = isIncremental;
	    /**
	     * Checks whether the information describes a full replacement event.
	     */
	    function isFull(event) {
	        let candidate = event;
	        return candidate !== undefined && candidate !== null &&
	            typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;
	    }
	    TextDocumentContentChangeEvent.isFull = isFull;
	})(TextDocumentContentChangeEvent || (exports.TextDocumentContentChangeEvent = TextDocumentContentChangeEvent = {}));
	/**
	 * The document change notification is sent from the client to the server to signal
	 * changes to a text document.
	 */
	var DidChangeTextDocumentNotification;
	(function (DidChangeTextDocumentNotification) {
	    DidChangeTextDocumentNotification.method = 'textDocument/didChange';
	    DidChangeTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
	})(DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = DidChangeTextDocumentNotification = {}));
	/**
	 * The document close notification is sent from the client to the server when
	 * the document got closed in the client. The document's truth now exists where
	 * the document's uri points to (e.g. if the document's uri is a file uri the
	 * truth now exists on disk). As with the open notification the close notification
	 * is about managing the document's content. Receiving a close notification
	 * doesn't mean that the document was open in an editor before. A close
	 * notification requires a previous open notification to be sent.
	 */
	var DidCloseTextDocumentNotification;
	(function (DidCloseTextDocumentNotification) {
	    DidCloseTextDocumentNotification.method = 'textDocument/didClose';
	    DidCloseTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
	})(DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = DidCloseTextDocumentNotification = {}));
	/**
	 * The document save notification is sent from the client to the server when
	 * the document got saved in the client.
	 */
	var DidSaveTextDocumentNotification;
	(function (DidSaveTextDocumentNotification) {
	    DidSaveTextDocumentNotification.method = 'textDocument/didSave';
	    DidSaveTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
	})(DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = DidSaveTextDocumentNotification = {}));
	/**
	 * Represents reasons why a text document is saved.
	 */
	var TextDocumentSaveReason;
	(function (TextDocumentSaveReason) {
	    /**
	     * Manually triggered, e.g. by the user pressing save, by starting debugging,
	     * or by an API call.
	     */
	    TextDocumentSaveReason.Manual = 1;
	    /**
	     * Automatic after a delay.
	     */
	    TextDocumentSaveReason.AfterDelay = 2;
	    /**
	     * When the editor lost focus.
	     */
	    TextDocumentSaveReason.FocusOut = 3;
	})(TextDocumentSaveReason || (exports.TextDocumentSaveReason = TextDocumentSaveReason = {}));
	/**
	 * A document will save notification is sent from the client to the server before
	 * the document is actually saved.
	 */
	var WillSaveTextDocumentNotification;
	(function (WillSaveTextDocumentNotification) {
	    WillSaveTextDocumentNotification.method = 'textDocument/willSave';
	    WillSaveTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
	})(WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = WillSaveTextDocumentNotification = {}));
	/**
	 * A document will save request is sent from the client to the server before
	 * the document is actually saved. The request can return an array of TextEdits
	 * which will be applied to the text document before it is saved. Please note that
	 * clients might drop results if computing the text edits took too long or if a
	 * server constantly fails on this request. This is done to keep the save fast and
	 * reliable.
	 */
	var WillSaveTextDocumentWaitUntilRequest;
	(function (WillSaveTextDocumentWaitUntilRequest) {
	    WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
	    WillSaveTextDocumentWaitUntilRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
	})(WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = WillSaveTextDocumentWaitUntilRequest = {}));
	/**
	 * The watched files notification is sent from the client to the server when
	 * the client detects changes to file watched by the language client.
	 */
	var DidChangeWatchedFilesNotification;
	(function (DidChangeWatchedFilesNotification) {
	    DidChangeWatchedFilesNotification.method = 'workspace/didChangeWatchedFiles';
	    DidChangeWatchedFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;
	    DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification.method);
	})(DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = DidChangeWatchedFilesNotification = {}));
	/**
	 * The file event type
	 */
	var FileChangeType;
	(function (FileChangeType) {
	    /**
	     * The file got created.
	     */
	    FileChangeType.Created = 1;
	    /**
	     * The file got changed.
	     */
	    FileChangeType.Changed = 2;
	    /**
	     * The file got deleted.
	     */
	    FileChangeType.Deleted = 3;
	})(FileChangeType || (exports.FileChangeType = FileChangeType = {}));
	var RelativePattern;
	(function (RelativePattern) {
	    function is(value) {
	        const candidate = value;
	        return Is.objectLiteral(candidate) && (vscode_languageserver_types_1.URI.is(candidate.baseUri) || vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri)) && Is.string(candidate.pattern);
	    }
	    RelativePattern.is = is;
	})(RelativePattern || (exports.RelativePattern = RelativePattern = {}));
	var WatchKind;
	(function (WatchKind) {
	    /**
	     * Interested in create events.
	     */
	    WatchKind.Create = 1;
	    /**
	     * Interested in change events
	     */
	    WatchKind.Change = 2;
	    /**
	     * Interested in delete events
	     */
	    WatchKind.Delete = 4;
	})(WatchKind || (exports.WatchKind = WatchKind = {}));
	/**
	 * Diagnostics notification are sent from the server to the client to signal
	 * results of validation runs.
	 */
	var PublishDiagnosticsNotification;
	(function (PublishDiagnosticsNotification) {
	    PublishDiagnosticsNotification.method = 'textDocument/publishDiagnostics';
	    PublishDiagnosticsNotification.messageDirection = messages_1.MessageDirection.serverToClient;
	    PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification.method);
	})(PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = PublishDiagnosticsNotification = {}));
	/**
	 * How a completion was triggered
	 */
	var CompletionTriggerKind;
	(function (CompletionTriggerKind) {
	    /**
	     * Completion was triggered by typing an identifier (24x7 code
	     * complete), manual invocation (e.g Ctrl+Space) or via API.
	     */
	    CompletionTriggerKind.Invoked = 1;
	    /**
	     * Completion was triggered by a trigger character specified by
	     * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
	     */
	    CompletionTriggerKind.TriggerCharacter = 2;
	    /**
	     * Completion was re-triggered as current completion list is incomplete
	     */
	    CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
	})(CompletionTriggerKind || (exports.CompletionTriggerKind = CompletionTriggerKind = {}));
	/**
	 * Request to request completion at a given text document position. The request's
	 * parameter is of type {@link TextDocumentPosition} the response
	 * is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList}
	 * or a Thenable that resolves to such.
	 *
	 * The request can delay the computation of the {@link CompletionItem.detail `detail`}
	 * and {@link CompletionItem.documentation `documentation`} properties to the `completionItem/resolve`
	 * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
	 * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
	 */
	var CompletionRequest;
	(function (CompletionRequest) {
	    CompletionRequest.method = 'textDocument/completion';
	    CompletionRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
	})(CompletionRequest || (exports.CompletionRequest = CompletionRequest = {}));
	/**
	 * Request to resolve additional information for a given completion item.The request's
	 * parameter is of type {@link CompletionItem} the response
	 * is of type {@link CompletionItem} or a Thenable that resolves to such.
	 */
	var CompletionResolveRequest;
	(function (CompletionResolveRequest) {
	    CompletionResolveRequest.method = 'completionItem/resolve';
	    CompletionResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
	})(CompletionResolveRequest || (exports.CompletionResolveRequest = CompletionResolveRequest = {}));
	/**
	 * Request to request hover information at a given text document position. The request's
	 * parameter is of type {@link TextDocumentPosition} the response is of
	 * type {@link Hover} or a Thenable that resolves to such.
	 */
	var HoverRequest;
	(function (HoverRequest) {
	    HoverRequest.method = 'textDocument/hover';
	    HoverRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
	})(HoverRequest || (exports.HoverRequest = HoverRequest = {}));
	/**
	 * How a signature help was triggered.
	 *
	 * @since 3.15.0
	 */
	var SignatureHelpTriggerKind;
	(function (SignatureHelpTriggerKind) {
	    /**
	     * Signature help was invoked manually by the user or by a command.
	     */
	    SignatureHelpTriggerKind.Invoked = 1;
	    /**
	     * Signature help was triggered by a trigger character.
	     */
	    SignatureHelpTriggerKind.TriggerCharacter = 2;
	    /**
	     * Signature help was triggered by the cursor moving or by the document content changing.
	     */
	    SignatureHelpTriggerKind.ContentChange = 3;
	})(SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {}));
	var SignatureHelpRequest;
	(function (SignatureHelpRequest) {
	    SignatureHelpRequest.method = 'textDocument/signatureHelp';
	    SignatureHelpRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
	})(SignatureHelpRequest || (exports.SignatureHelpRequest = SignatureHelpRequest = {}));
	/**
	 * A request to resolve the definition location of a symbol at a given text
	 * document position. The request's parameter is of type {@link TextDocumentPosition}
	 * the response is of either type {@link Definition} or a typed array of
	 * {@link DefinitionLink} or a Thenable that resolves to such.
	 */
	var DefinitionRequest;
	(function (DefinitionRequest) {
	    DefinitionRequest.method = 'textDocument/definition';
	    DefinitionRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
	})(DefinitionRequest || (exports.DefinitionRequest = DefinitionRequest = {}));
	/**
	 * A request to resolve project-wide references for the symbol denoted
	 * by the given text document position. The request's parameter is of
	 * type {@link ReferenceParams} the response is of type
	 * {@link Location Location[]} or a Thenable that resolves to such.
	 */
	var ReferencesRequest;
	(function (ReferencesRequest) {
	    ReferencesRequest.method = 'textDocument/references';
	    ReferencesRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
	})(ReferencesRequest || (exports.ReferencesRequest = ReferencesRequest = {}));
	/**
	 * Request to resolve a {@link DocumentHighlight} for a given
	 * text document position. The request's parameter is of type {@link TextDocumentPosition}
	 * the request response is an array of type {@link DocumentHighlight}
	 * or a Thenable that resolves to such.
	 */
	var DocumentHighlightRequest;
	(function (DocumentHighlightRequest) {
	    DocumentHighlightRequest.method = 'textDocument/documentHighlight';
	    DocumentHighlightRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
	})(DocumentHighlightRequest || (exports.DocumentHighlightRequest = DocumentHighlightRequest = {}));
	/**
	 * A request to list all symbols found in a given text document. The request's
	 * parameter is of type {@link TextDocumentIdentifier} the
	 * response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable
	 * that resolves to such.
	 */
	var DocumentSymbolRequest;
	(function (DocumentSymbolRequest) {
	    DocumentSymbolRequest.method = 'textDocument/documentSymbol';
	    DocumentSymbolRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
	})(DocumentSymbolRequest || (exports.DocumentSymbolRequest = DocumentSymbolRequest = {}));
	/**
	 * A request to provide commands for the given text document and range.
	 */
	var CodeActionRequest;
	(function (CodeActionRequest) {
	    CodeActionRequest.method = 'textDocument/codeAction';
	    CodeActionRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
	})(CodeActionRequest || (exports.CodeActionRequest = CodeActionRequest = {}));
	/**
	 * Request to resolve additional information for a given code action.The request's
	 * parameter is of type {@link CodeAction} the response
	 * is of type {@link CodeAction} or a Thenable that resolves to such.
	 */
	var CodeActionResolveRequest;
	(function (CodeActionResolveRequest) {
	    CodeActionResolveRequest.method = 'codeAction/resolve';
	    CodeActionResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    CodeActionResolveRequest.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest.method);
	})(CodeActionResolveRequest || (exports.CodeActionResolveRequest = CodeActionResolveRequest = {}));
	/**
	 * A request to list project-wide symbols matching the query string given
	 * by the {@link WorkspaceSymbolParams}. The response is
	 * of type {@link SymbolInformation SymbolInformation[]} or a Thenable that
	 * resolves to such.
	 *
	 * @since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients
	 *  need to advertise support for WorkspaceSymbols via the client capability
	 *  `workspace.symbol.resolveSupport`.
	 *
	 */
	var WorkspaceSymbolRequest;
	(function (WorkspaceSymbolRequest) {
	    WorkspaceSymbolRequest.method = 'workspace/symbol';
	    WorkspaceSymbolRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
	})(WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = WorkspaceSymbolRequest = {}));
	/**
	 * A request to resolve the range inside the workspace
	 * symbol's location.
	 *
	 * @since 3.17.0
	 */
	var WorkspaceSymbolResolveRequest;
	(function (WorkspaceSymbolResolveRequest) {
	    WorkspaceSymbolResolveRequest.method = 'workspaceSymbol/resolve';
	    WorkspaceSymbolResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    WorkspaceSymbolResolveRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest.method);
	})(WorkspaceSymbolResolveRequest || (exports.WorkspaceSymbolResolveRequest = WorkspaceSymbolResolveRequest = {}));
	/**
	 * A request to provide code lens for the given text document.
	 */
	var CodeLensRequest;
	(function (CodeLensRequest) {
	    CodeLensRequest.method = 'textDocument/codeLens';
	    CodeLensRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    CodeLensRequest.type = new messages_1.ProtocolRequestType(CodeLensRequest.method);
	})(CodeLensRequest || (exports.CodeLensRequest = CodeLensRequest = {}));
	/**
	 * A request to resolve a command for a given code lens.
	 */
	var CodeLensResolveRequest;
	(function (CodeLensResolveRequest) {
	    CodeLensResolveRequest.method = 'codeLens/resolve';
	    CodeLensResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    CodeLensResolveRequest.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest.method);
	})(CodeLensResolveRequest || (exports.CodeLensResolveRequest = CodeLensResolveRequest = {}));
	/**
	 * A request to refresh all code actions
	 *
	 * @since 3.16.0
	 */
	var CodeLensRefreshRequest;
	(function (CodeLensRefreshRequest) {
	    CodeLensRefreshRequest.method = `workspace/codeLens/refresh`;
	    CodeLensRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;
	    CodeLensRefreshRequest.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest.method);
	})(CodeLensRefreshRequest || (exports.CodeLensRefreshRequest = CodeLensRefreshRequest = {}));
	/**
	 * A request to provide document links
	 */
	var DocumentLinkRequest;
	(function (DocumentLinkRequest) {
	    DocumentLinkRequest.method = 'textDocument/documentLink';
	    DocumentLinkRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
	})(DocumentLinkRequest || (exports.DocumentLinkRequest = DocumentLinkRequest = {}));
	/**
	 * Request to resolve additional information for a given document link. The request's
	 * parameter is of type {@link DocumentLink} the response
	 * is of type {@link DocumentLink} or a Thenable that resolves to such.
	 */
	var DocumentLinkResolveRequest;
	(function (DocumentLinkResolveRequest) {
	    DocumentLinkResolveRequest.method = 'documentLink/resolve';
	    DocumentLinkResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest.method);
	})(DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = DocumentLinkResolveRequest = {}));
	/**
	 * A request to format a whole document.
	 */
	var DocumentFormattingRequest;
	(function (DocumentFormattingRequest) {
	    DocumentFormattingRequest.method = 'textDocument/formatting';
	    DocumentFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
	})(DocumentFormattingRequest || (exports.DocumentFormattingRequest = DocumentFormattingRequest = {}));
	/**
	 * A request to format a range in a document.
	 */
	var DocumentRangeFormattingRequest;
	(function (DocumentRangeFormattingRequest) {
	    DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
	    DocumentRangeFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
	})(DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = DocumentRangeFormattingRequest = {}));
	/**
	 * A request to format ranges in a document.
	 *
	 * @since 3.18.0
	 * @proposed
	 */
	var DocumentRangesFormattingRequest;
	(function (DocumentRangesFormattingRequest) {
	    DocumentRangesFormattingRequest.method = 'textDocument/rangesFormatting';
	    DocumentRangesFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DocumentRangesFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest.method);
	})(DocumentRangesFormattingRequest || (exports.DocumentRangesFormattingRequest = DocumentRangesFormattingRequest = {}));
	/**
	 * A request to format a document on type.
	 */
	var DocumentOnTypeFormattingRequest;
	(function (DocumentOnTypeFormattingRequest) {
	    DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
	    DocumentOnTypeFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
	})(DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = DocumentOnTypeFormattingRequest = {}));
	//---- Rename ----------------------------------------------
	var PrepareSupportDefaultBehavior;
	(function (PrepareSupportDefaultBehavior) {
	    /**
	     * The client's default behavior is to select the identifier
	     * according the to language's syntax rule.
	     */
	    PrepareSupportDefaultBehavior.Identifier = 1;
	})(PrepareSupportDefaultBehavior || (exports.PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior = {}));
	/**
	 * A request to rename a symbol.
	 */
	var RenameRequest;
	(function (RenameRequest) {
	    RenameRequest.method = 'textDocument/rename';
	    RenameRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
	})(RenameRequest || (exports.RenameRequest = RenameRequest = {}));
	/**
	 * A request to test and perform the setup necessary for a rename.
	 *
	 * @since 3.16 - support for default behavior
	 */
	var PrepareRenameRequest;
	(function (PrepareRenameRequest) {
	    PrepareRenameRequest.method = 'textDocument/prepareRename';
	    PrepareRenameRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
	})(PrepareRenameRequest || (exports.PrepareRenameRequest = PrepareRenameRequest = {}));
	/**
	 * A request send from the client to the server to execute a command. The request might return
	 * a workspace edit which the client will apply to the workspace.
	 */
	var ExecuteCommandRequest;
	(function (ExecuteCommandRequest) {
	    ExecuteCommandRequest.method = 'workspace/executeCommand';
	    ExecuteCommandRequest.messageDirection = messages_1.MessageDirection.clientToServer;
	    ExecuteCommandRequest.type = new messages_1.ProtocolRequestType(ExecuteCommandRequest.method);
	})(ExecuteCommandRequest || (exports.ExecuteCommandRequest = ExecuteCommandRequest = {}));
	/**
	 * A request sent from the server to the client to modified certain resources.
	 */
	var ApplyWorkspaceEditRequest;
	(function (ApplyWorkspaceEditRequest) {
	    ApplyWorkspaceEditRequest.method = 'workspace/applyEdit';
	    ApplyWorkspaceEditRequest.messageDirection = messages_1.MessageDirection.serverToClient;
	    ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
	})(ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = ApplyWorkspaceEditRequest = {})); 
} (protocol));

var connection = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(connection, "__esModule", { value: true });
connection.createProtocolConnection = void 0;
const vscode_jsonrpc_1 = main$1;
function createProtocolConnection(input, output, logger, options) {
    if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {
        options = { connectionStrategy: options };
    }
    return (0, vscode_jsonrpc_1.createMessageConnection)(input, output, logger, options);
}
connection.createProtocolConnection = createProtocolConnection;

(function (exports) {
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	var __createBinding = (commonjsGlobal && commonjsGlobal.__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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
	    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.LSPErrorCodes = exports.createProtocolConnection = void 0;
	__exportStar(main$1, exports);
	__exportStar(require$$1, exports);
	__exportStar(messages, exports);
	__exportStar(protocol, exports);
	var connection_1 = connection;
	Object.defineProperty(exports, "createProtocolConnection", { enumerable: true, get: function () { return connection_1.createProtocolConnection; } });
	var LSPErrorCodes;
	(function (LSPErrorCodes) {
	    /**
	    * This is the start range of LSP reserved error codes.
	    * It doesn't denote a real error code.
	    *
	    * @since 3.16.0
	    */
	    LSPErrorCodes.lspReservedErrorRangeStart = -32899;
	    /**
	     * A request failed but it was syntactically correct, e.g the
	     * method name was known and the parameters were valid. The error
	     * message should contain human readable information about why
	     * the request failed.
	     *
	     * @since 3.17.0
	     */
	    LSPErrorCodes.RequestFailed = -32803;
	    /**
	     * The server cancelled the request. This error code should
	     * only be used for requests that explicitly support being
	     * server cancellable.
	     *
	     * @since 3.17.0
	     */
	    LSPErrorCodes.ServerCancelled = -32802;
	    /**
	     * The server detected that the content of a document got
	     * modified outside normal conditions. A server should
	     * NOT send this error code if it detects a content change
	     * in it unprocessed messages. The result even computed
	     * on an older state might still be useful for the client.
	     *
	     * If a client decides that a result is not of any use anymore
	     * the client should cancel the request.
	     */
	    LSPErrorCodes.ContentModified = -32801;
	    /**
	     * The client has canceled a request and a server as detected
	     * the cancel.
	     */
	    LSPErrorCodes.RequestCancelled = -32800;
	    /**
	    * This is the end range of LSP reserved error codes.
	    * It doesn't denote a real error code.
	    *
	    * @since 3.16.0
	    */
	    LSPErrorCodes.lspReservedErrorRangeEnd = -32800;
	})(LSPErrorCodes || (exports.LSPErrorCodes = LSPErrorCodes = {})); 
} (api));

(function (exports) {
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	var __createBinding = (commonjsGlobal && commonjsGlobal.__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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
	    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.createProtocolConnection = void 0;
	const browser_1 = browser$1;
	__exportStar(browser$1, exports);
	__exportStar(api, exports);
	function createProtocolConnection(reader, writer, logger, options) {
	    return (0, browser_1.createMessageConnection)(reader, writer, logger, options);
	}
	exports.createProtocolConnection = createProtocolConnection; 
} (main$2));

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(semanticTokens, "__esModule", { value: true });
semanticTokens.SemanticTokensBuilder = semanticTokens.SemanticTokensDiff = semanticTokens.SemanticTokensFeature = void 0;
const vscode_languageserver_protocol_1$h = main$2;
const SemanticTokensFeature = (Base) => {
    return class extends Base {
        get semanticTokens() {
            return {
                refresh: () => {
                    return this.connection.sendRequest(vscode_languageserver_protocol_1$h.SemanticTokensRefreshRequest.type);
                },
                on: (handler) => {
                    const type = vscode_languageserver_protocol_1$h.SemanticTokensRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                },
                onDelta: (handler) => {
                    const type = vscode_languageserver_protocol_1$h.SemanticTokensDeltaRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                },
                onRange: (handler) => {
                    const type = vscode_languageserver_protocol_1$h.SemanticTokensRangeRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                }
            };
        }
    };
};
semanticTokens.SemanticTokensFeature = SemanticTokensFeature;
class SemanticTokensDiff {
    constructor(originalSequence, modifiedSequence) {
        this.originalSequence = originalSequence;
        this.modifiedSequence = modifiedSequence;
    }
    computeDiff() {
        const originalLength = this.originalSequence.length;
        const modifiedLength = this.modifiedSequence.length;
        let startIndex = 0;
        while (startIndex < modifiedLength && startIndex < originalLength && this.originalSequence[startIndex] === this.modifiedSequence[startIndex]) {
            startIndex++;
        }
        if (startIndex < modifiedLength && startIndex < originalLength) {
            let originalEndIndex = originalLength - 1;
            let modifiedEndIndex = modifiedLength - 1;
            while (originalEndIndex >= startIndex && modifiedEndIndex >= startIndex && this.originalSequence[originalEndIndex] === this.modifiedSequence[modifiedEndIndex]) {
                originalEndIndex--;
                modifiedEndIndex--;
            }
            // if one moved behind the start index move them forward again
            if (originalEndIndex < startIndex || modifiedEndIndex < startIndex) {
                originalEndIndex++;
                modifiedEndIndex++;
            }
            const deleteCount = originalEndIndex - startIndex + 1;
            const newData = this.modifiedSequence.slice(startIndex, modifiedEndIndex + 1);
            // If we moved behind the start index we could have missed a simple delete.
            if (newData.length === 1 && newData[0] === this.originalSequence[originalEndIndex]) {
                return [
                    { start: startIndex, deleteCount: deleteCount - 1 }
                ];
            }
            else {
                return [
                    { start: startIndex, deleteCount, data: newData }
                ];
            }
        }
        else if (startIndex < modifiedLength) {
            return [
                { start: startIndex, deleteCount: 0, data: this.modifiedSequence.slice(startIndex) }
            ];
        }
        else if (startIndex < originalLength) {
            return [
                { start: startIndex, deleteCount: originalLength - startIndex }
            ];
        }
        else {
            // The two arrays are the same.
            return [];
        }
    }
}
semanticTokens.SemanticTokensDiff = SemanticTokensDiff;
class SemanticTokensBuilder {
    constructor() {
        this._prevData = undefined;
        this.initialize();
    }
    initialize() {
        this._id = Date.now();
        this._prevLine = 0;
        this._prevChar = 0;
        this._data = [];
        this._dataLen = 0;
    }
    push(line, char, length, tokenType, tokenModifiers) {
        let pushLine = line;
        let pushChar = char;
        if (this._dataLen > 0) {
            pushLine -= this._prevLine;
            if (pushLine === 0) {
                pushChar -= this._prevChar;
            }
        }
        this._data[this._dataLen++] = pushLine;
        this._data[this._dataLen++] = pushChar;
        this._data[this._dataLen++] = length;
        this._data[this._dataLen++] = tokenType;
        this._data[this._dataLen++] = tokenModifiers;
        this._prevLine = line;
        this._prevChar = char;
    }
    get id() {
        return this._id.toString();
    }
    previousResult(id) {
        if (this.id === id) {
            this._prevData = this._data;
        }
        this.initialize();
    }
    build() {
        this._prevData = undefined;
        return {
            resultId: this.id,
            data: this._data
        };
    }
    canBuildEdits() {
        return this._prevData !== undefined;
    }
    buildEdits() {
        if (this._prevData !== undefined) {
            return {
                resultId: this.id,
                edits: (new SemanticTokensDiff(this._prevData, this._data)).computeDiff()
            };
        }
        else {
            return this.build();
        }
    }
}
semanticTokens.SemanticTokensBuilder = SemanticTokensBuilder;

var inlineCompletion_proposed = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(inlineCompletion_proposed, "__esModule", { value: true });
inlineCompletion_proposed.InlineCompletionFeature = void 0;
const vscode_languageserver_protocol_1$g = main$2;
const InlineCompletionFeature = (Base) => {
    return class extends Base {
        get inlineCompletion() {
            return {
                on: (handler) => {
                    return this.connection.onRequest(vscode_languageserver_protocol_1$g.InlineCompletionRequest.type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params));
                    });
                }
            };
        }
    };
};
inlineCompletion_proposed.InlineCompletionFeature = InlineCompletionFeature;

var textDocuments = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(textDocuments, "__esModule", { value: true });
textDocuments.TextDocuments = void 0;
const vscode_languageserver_protocol_1$f = main$2;
/**
 * A manager for simple text documents. The manager requires at a minimum that
 * the server registered for the following text document sync events in the
 * initialize handler or via dynamic registration:
 *
 * - open and close events.
 * - change events.
 *
 * Registering for save and will save events is optional.
 */
class TextDocuments {
    /**
     * Create a new text document manager.
     */
    constructor(configuration) {
        this._configuration = configuration;
        this._syncedDocuments = new Map();
        this._onDidChangeContent = new vscode_languageserver_protocol_1$f.Emitter();
        this._onDidOpen = new vscode_languageserver_protocol_1$f.Emitter();
        this._onDidClose = new vscode_languageserver_protocol_1$f.Emitter();
        this._onDidSave = new vscode_languageserver_protocol_1$f.Emitter();
        this._onWillSave = new vscode_languageserver_protocol_1$f.Emitter();
    }
    /**
     * An event that fires when a text document managed by this manager
     * has been opened.
     */
    get onDidOpen() {
        return this._onDidOpen.event;
    }
    /**
     * An event that fires when a text document managed by this manager
     * has been opened or the content changes.
     */
    get onDidChangeContent() {
        return this._onDidChangeContent.event;
    }
    /**
     * An event that fires when a text document managed by this manager
     * will be saved.
     */
    get onWillSave() {
        return this._onWillSave.event;
    }
    /**
     * Sets a handler that will be called if a participant wants to provide
     * edits during a text document save.
     */
    onWillSaveWaitUntil(handler) {
        this._willSaveWaitUntil = handler;
    }
    /**
     * An event that fires when a text document managed by this manager
     * has been saved.
     */
    get onDidSave() {
        return this._onDidSave.event;
    }
    /**
     * An event that fires when a text document managed by this manager
     * has been closed.
     */
    get onDidClose() {
        return this._onDidClose.event;
    }
    /**
     * Returns the document for the given URI. Returns undefined if
     * the document is not managed by this instance.
     *
     * @param uri The text document's URI to retrieve.
     * @return the text document or `undefined`.
     */
    get(uri) {
        return this._syncedDocuments.get(uri);
    }
    /**
     * Returns all text documents managed by this instance.
     *
     * @return all text documents.
     */
    all() {
        return Array.from(this._syncedDocuments.values());
    }
    /**
     * Returns the URIs of all text documents managed by this instance.
     *
     * @return the URI's of all text documents.
     */
    keys() {
        return Array.from(this._syncedDocuments.keys());
    }
    /**
     * Listens for `low level` notification on the given connection to
     * update the text documents managed by this instance.
     *
     * Please note that the connection only provides handlers not an event model. Therefore
     * listening on a connection will overwrite the following handlers on a connection:
     * `onDidOpenTextDocument`, `onDidChangeTextDocument`, `onDidCloseTextDocument`,
     * `onWillSaveTextDocument`, `onWillSaveTextDocumentWaitUntil` and `onDidSaveTextDocument`.
     *
     * Use the corresponding events on the TextDocuments instance instead.
     *
     * @param connection The connection to listen on.
     */
    listen(connection) {
        connection.__textDocumentSync = vscode_languageserver_protocol_1$f.TextDocumentSyncKind.Incremental;
        const disposables = [];
        disposables.push(connection.onDidOpenTextDocument((event) => {
            const td = event.textDocument;
            const document = this._configuration.create(td.uri, td.languageId, td.version, td.text);
            this._syncedDocuments.set(td.uri, document);
            const toFire = Object.freeze({ document });
            this._onDidOpen.fire(toFire);
            this._onDidChangeContent.fire(toFire);
        }));
        disposables.push(connection.onDidChangeTextDocument((event) => {
            const td = event.textDocument;
            const changes = event.contentChanges;
            if (changes.length === 0) {
                return;
            }
            const { version } = td;
            if (version === null || version === undefined) {
                throw new Error(`Received document change event for ${td.uri} without valid version identifier`);
            }
            let syncedDocument = this._syncedDocuments.get(td.uri);
            if (syncedDocument !== undefined) {
                syncedDocument = this._configuration.update(syncedDocument, changes, version);
                this._syncedDocuments.set(td.uri, syncedDocument);
                this._onDidChangeContent.fire(Object.freeze({ document: syncedDocument }));
            }
        }));
        disposables.push(connection.onDidCloseTextDocument((event) => {
            let syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
            if (syncedDocument !== undefined) {
                this._syncedDocuments.delete(event.textDocument.uri);
                this._onDidClose.fire(Object.freeze({ document: syncedDocument }));
            }
        }));
        disposables.push(connection.onWillSaveTextDocument((event) => {
            let syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
            if (syncedDocument !== undefined) {
                this._onWillSave.fire(Object.freeze({ document: syncedDocument, reason: event.reason }));
            }
        }));
        disposables.push(connection.onWillSaveTextDocumentWaitUntil((event, token) => {
            let syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
            if (syncedDocument !== undefined && this._willSaveWaitUntil) {
                return this._willSaveWaitUntil(Object.freeze({ document: syncedDocument, reason: event.reason }), token);
            }
            else {
                return [];
            }
        }));
        disposables.push(connection.onDidSaveTextDocument((event) => {
            let syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
            if (syncedDocument !== undefined) {
                this._onDidSave.fire(Object.freeze({ document: syncedDocument }));
            }
        }));
        return vscode_languageserver_protocol_1$f.Disposable.create(() => { disposables.forEach(disposable => disposable.dispose()); });
    }
}
textDocuments.TextDocuments = TextDocuments;

var notebook = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(notebook, "__esModule", { value: true });
notebook.NotebookDocuments = notebook.NotebookSyncFeature = void 0;
const vscode_languageserver_protocol_1$e = main$2;
const textDocuments_1 = textDocuments;
const NotebookSyncFeature = (Base) => {
    return class extends Base {
        get synchronization() {
            return {
                onDidOpenNotebookDocument: (handler) => {
                    return this.connection.onNotification(vscode_languageserver_protocol_1$e.DidOpenNotebookDocumentNotification.type, (params) => {
                        handler(params);
                    });
                },
                onDidChangeNotebookDocument: (handler) => {
                    return this.connection.onNotification(vscode_languageserver_protocol_1$e.DidChangeNotebookDocumentNotification.type, (params) => {
                        handler(params);
                    });
                },
                onDidSaveNotebookDocument: (handler) => {
                    return this.connection.onNotification(vscode_languageserver_protocol_1$e.DidSaveNotebookDocumentNotification.type, (params) => {
                        handler(params);
                    });
                },
                onDidCloseNotebookDocument: (handler) => {
                    return this.connection.onNotification(vscode_languageserver_protocol_1$e.DidCloseNotebookDocumentNotification.type, (params) => {
                        handler(params);
                    });
                }
            };
        }
    };
};
notebook.NotebookSyncFeature = NotebookSyncFeature;
class CellTextDocumentConnection {
    onDidOpenTextDocument(handler) {
        this.openHandler = handler;
        return vscode_languageserver_protocol_1$e.Disposable.create(() => { this.openHandler = undefined; });
    }
    openTextDocument(params) {
        this.openHandler && this.openHandler(params);
    }
    onDidChangeTextDocument(handler) {
        this.changeHandler = handler;
        return vscode_languageserver_protocol_1$e.Disposable.create(() => { this.changeHandler = handler; });
    }
    changeTextDocument(params) {
        this.changeHandler && this.changeHandler(params);
    }
    onDidCloseTextDocument(handler) {
        this.closeHandler = handler;
        return vscode_languageserver_protocol_1$e.Disposable.create(() => { this.closeHandler = undefined; });
    }
    closeTextDocument(params) {
        this.closeHandler && this.closeHandler(params);
    }
    onWillSaveTextDocument() {
        return CellTextDocumentConnection.NULL_DISPOSE;
    }
    onWillSaveTextDocumentWaitUntil() {
        return CellTextDocumentConnection.NULL_DISPOSE;
    }
    onDidSaveTextDocument() {
        return CellTextDocumentConnection.NULL_DISPOSE;
    }
}
CellTextDocumentConnection.NULL_DISPOSE = Object.freeze({ dispose: () => { } });
class NotebookDocuments {
    constructor(configurationOrTextDocuments) {
        if (configurationOrTextDocuments instanceof textDocuments_1.TextDocuments) {
            this._cellTextDocuments = configurationOrTextDocuments;
        }
        else {
            this._cellTextDocuments = new textDocuments_1.TextDocuments(configurationOrTextDocuments);
        }
        this.notebookDocuments = new Map();
        this.notebookCellMap = new Map();
        this._onDidOpen = new vscode_languageserver_protocol_1$e.Emitter();
        this._onDidChange = new vscode_languageserver_protocol_1$e.Emitter();
        this._onDidSave = new vscode_languageserver_protocol_1$e.Emitter();
        this._onDidClose = new vscode_languageserver_protocol_1$e.Emitter();
    }
    get cellTextDocuments() {
        return this._cellTextDocuments;
    }
    getCellTextDocument(cell) {
        return this._cellTextDocuments.get(cell.document);
    }
    getNotebookDocument(uri) {
        return this.notebookDocuments.get(uri);
    }
    getNotebookCell(uri) {
        const value = this.notebookCellMap.get(uri);
        return value && value[0];
    }
    findNotebookDocumentForCell(cell) {
        const key = typeof cell === 'string' ? cell : cell.document;
        const value = this.notebookCellMap.get(key);
        return value && value[1];
    }
    get onDidOpen() {
        return this._onDidOpen.event;
    }
    get onDidSave() {
        return this._onDidSave.event;
    }
    get onDidChange() {
        return this._onDidChange.event;
    }
    get onDidClose() {
        return this._onDidClose.event;
    }
    /**
     * Listens for `low level` notification on the given connection to
     * update the notebook documents managed by this instance.
     *
     * Please note that the connection only provides handlers not an event model. Therefore
     * listening on a connection will overwrite the following handlers on a connection:
     * `onDidOpenNotebookDocument`, `onDidChangeNotebookDocument`, `onDidSaveNotebookDocument`,
     *  and `onDidCloseNotebookDocument`.
     *
     * @param connection The connection to listen on.
     */
    listen(connection) {
        const cellTextDocumentConnection = new CellTextDocumentConnection();
        const disposables = [];
        disposables.push(this.cellTextDocuments.listen(cellTextDocumentConnection));
        disposables.push(connection.notebooks.synchronization.onDidOpenNotebookDocument((params) => {
            this.notebookDocuments.set(params.notebookDocument.uri, params.notebookDocument);
            for (const cellTextDocument of params.cellTextDocuments) {
                cellTextDocumentConnection.openTextDocument({ textDocument: cellTextDocument });
            }
            this.updateCellMap(params.notebookDocument);
            this._onDidOpen.fire(params.notebookDocument);
        }));
        disposables.push(connection.notebooks.synchronization.onDidChangeNotebookDocument((params) => {
            const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
            if (notebookDocument === undefined) {
                return;
            }
            notebookDocument.version = params.notebookDocument.version;
            const oldMetadata = notebookDocument.metadata;
            let metadataChanged = false;
            const change = params.change;
            if (change.metadata !== undefined) {
                metadataChanged = true;
                notebookDocument.metadata = change.metadata;
            }
            const opened = [];
            const closed = [];
            const data = [];
            const text = [];
            if (change.cells !== undefined) {
                const changedCells = change.cells;
                if (changedCells.structure !== undefined) {
                    const array = changedCells.structure.array;
                    notebookDocument.cells.splice(array.start, array.deleteCount, ...(array.cells !== undefined ? array.cells : []));
                    // Additional open cell text documents.
                    if (changedCells.structure.didOpen !== undefined) {
                        for (const open of changedCells.structure.didOpen) {
                            cellTextDocumentConnection.openTextDocument({ textDocument: open });
                            opened.push(open.uri);
                        }
                    }
                    // Additional closed cell test documents.
                    if (changedCells.structure.didClose) {
                        for (const close of changedCells.structure.didClose) {
                            cellTextDocumentConnection.closeTextDocument({ textDocument: close });
                            closed.push(close.uri);
                        }
                    }
                }
                if (changedCells.data !== undefined) {
                    const cellUpdates = new Map(changedCells.data.map(cell => [cell.document, cell]));
                    for (let i = 0; i <= notebookDocument.cells.length; i++) {
                        const change = cellUpdates.get(notebookDocument.cells[i].document);
                        if (change !== undefined) {
                            const old = notebookDocument.cells.splice(i, 1, change);
                            data.push({ old: old[0], new: change });
                            cellUpdates.delete(change.document);
                            if (cellUpdates.size === 0) {
                                break;
                            }
                        }
                    }
                }
                if (changedCells.textContent !== undefined) {
                    for (const cellTextDocument of changedCells.textContent) {
                        cellTextDocumentConnection.changeTextDocument({ textDocument: cellTextDocument.document, contentChanges: cellTextDocument.changes });
                        text.push(cellTextDocument.document.uri);
                    }
                }
            }
            // Update internal data structure.
            this.updateCellMap(notebookDocument);
            const changeEvent = { notebookDocument };
            if (metadataChanged) {
                changeEvent.metadata = { old: oldMetadata, new: notebookDocument.metadata };
            }
            const added = [];
            for (const open of opened) {
                added.push(this.getNotebookCell(open));
            }
            const removed = [];
            for (const close of closed) {
                removed.push(this.getNotebookCell(close));
            }
            const textContent = [];
            for (const change of text) {
                textContent.push(this.getNotebookCell(change));
            }
            if (added.length > 0 || removed.length > 0 || data.length > 0 || textContent.length > 0) {
                changeEvent.cells = { added, removed, changed: { data, textContent } };
            }
            if (changeEvent.metadata !== undefined || changeEvent.cells !== undefined) {
                this._onDidChange.fire(changeEvent);
            }
        }));
        disposables.push(connection.notebooks.synchronization.onDidSaveNotebookDocument((params) => {
            const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
            if (notebookDocument === undefined) {
                return;
            }
            this._onDidSave.fire(notebookDocument);
        }));
        disposables.push(connection.notebooks.synchronization.onDidCloseNotebookDocument((params) => {
            const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
            if (notebookDocument === undefined) {
                return;
            }
            this._onDidClose.fire(notebookDocument);
            for (const cellTextDocument of params.cellTextDocuments) {
                cellTextDocumentConnection.closeTextDocument({ textDocument: cellTextDocument });
            }
            this.notebookDocuments.delete(params.notebookDocument.uri);
            for (const cell of notebookDocument.cells) {
                this.notebookCellMap.delete(cell.document);
            }
        }));
        return vscode_languageserver_protocol_1$e.Disposable.create(() => { disposables.forEach(disposable => disposable.dispose()); });
    }
    updateCellMap(notebookDocument) {
        for (const cell of notebookDocument.cells) {
            this.notebookCellMap.set(cell.document, [cell, notebookDocument]);
        }
    }
}
notebook.NotebookDocuments = NotebookDocuments;

var server = {};

var is = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(is, "__esModule", { value: true });
is.thenable = is.typedArray = is.stringArray = is.array = is.func = is.error = is.number = is.string = is.boolean = void 0;
function boolean(value) {
    return value === true || value === false;
}
is.boolean = boolean;
function string(value) {
    return typeof value === 'string' || value instanceof String;
}
is.string = string;
function number(value) {
    return typeof value === 'number' || value instanceof Number;
}
is.number = number;
function error(value) {
    return value instanceof Error;
}
is.error = error;
function func(value) {
    return typeof value === 'function';
}
is.func = func;
function array(value) {
    return Array.isArray(value);
}
is.array = array;
function stringArray(value) {
    return array(value) && value.every(elem => string(elem));
}
is.stringArray = stringArray;
function typedArray(value, check) {
    return Array.isArray(value) && value.every(check);
}
is.typedArray = typedArray;
function thenable(value) {
    return value && func(value.then);
}
is.thenable = thenable;

var uuid = {};

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(uuid, "__esModule", { value: true });
uuid.generateUuid = uuid.parse = uuid.isUUID = uuid.v4 = uuid.empty = void 0;
class ValueUUID {
    constructor(_value) {
        this._value = _value;
        // empty
    }
    asHex() {
        return this._value;
    }
    equals(other) {
        return this.asHex() === other.asHex();
    }
}
class V4UUID extends ValueUUID {
    static _oneOf(array) {
        return array[Math.floor(array.length * Math.random())];
    }
    static _randomHex() {
        return V4UUID._oneOf(V4UUID._chars);
    }
    constructor() {
        super([
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            '-',
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            '-',
            '4',
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            '-',
            V4UUID._oneOf(V4UUID._timeHighBits),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            '-',
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
        ].join(''));
    }
}
V4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
V4UUID._timeHighBits = ['8', '9', 'a', 'b'];
/**
 * An empty UUID that contains only zeros.
 */
uuid.empty = new ValueUUID('00000000-0000-0000-0000-000000000000');
function v4() {
    return new V4UUID();
}
uuid.v4 = v4;
const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isUUID(value) {
    return _UUIDPattern.test(value);
}
uuid.isUUID = isUUID;
/**
 * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
 * @param value A uuid string.
 */
function parse(value) {
    if (!isUUID(value)) {
        throw new Error('invalid uuid');
    }
    return new ValueUUID(value);
}
uuid.parse = parse;
function generateUuid() {
    return v4().asHex();
}
uuid.generateUuid = generateUuid;

var progress = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(progress, "__esModule", { value: true });
progress.attachPartialResult = progress.ProgressFeature = progress.attachWorkDone = void 0;
const vscode_languageserver_protocol_1$d = main$2;
const uuid_1 = uuid;
class WorkDoneProgressReporterImpl {
    constructor(_connection, _token) {
        this._connection = _connection;
        this._token = _token;
        WorkDoneProgressReporterImpl.Instances.set(this._token, this);
    }
    begin(title, percentage, message, cancellable) {
        let param = {
            kind: 'begin',
            title,
            percentage,
            message,
            cancellable
        };
        this._connection.sendProgress(vscode_languageserver_protocol_1$d.WorkDoneProgress.type, this._token, param);
    }
    report(arg0, arg1) {
        let param = {
            kind: 'report'
        };
        if (typeof arg0 === 'number') {
            param.percentage = arg0;
            if (arg1 !== undefined) {
                param.message = arg1;
            }
        }
        else {
            param.message = arg0;
        }
        this._connection.sendProgress(vscode_languageserver_protocol_1$d.WorkDoneProgress.type, this._token, param);
    }
    done() {
        WorkDoneProgressReporterImpl.Instances.delete(this._token);
        this._connection.sendProgress(vscode_languageserver_protocol_1$d.WorkDoneProgress.type, this._token, { kind: 'end' });
    }
}
WorkDoneProgressReporterImpl.Instances = new Map();
class WorkDoneProgressServerReporterImpl extends WorkDoneProgressReporterImpl {
    constructor(connection, token) {
        super(connection, token);
        this._source = new vscode_languageserver_protocol_1$d.CancellationTokenSource();
    }
    get token() {
        return this._source.token;
    }
    done() {
        this._source.dispose();
        super.done();
    }
    cancel() {
        this._source.cancel();
    }
}
class NullProgressReporter {
    constructor() {
    }
    begin() {
    }
    report() {
    }
    done() {
    }
}
class NullProgressServerReporter extends NullProgressReporter {
    constructor() {
        super();
        this._source = new vscode_languageserver_protocol_1$d.CancellationTokenSource();
    }
    get token() {
        return this._source.token;
    }
    done() {
        this._source.dispose();
    }
    cancel() {
        this._source.cancel();
    }
}
function attachWorkDone(connection, params) {
    if (params === undefined || params.workDoneToken === undefined) {
        return new NullProgressReporter();
    }
    const token = params.workDoneToken;
    delete params.workDoneToken;
    return new WorkDoneProgressReporterImpl(connection, token);
}
progress.attachWorkDone = attachWorkDone;
const ProgressFeature = (Base) => {
    return class extends Base {
        constructor() {
            super();
            this._progressSupported = false;
        }
        initialize(capabilities) {
            super.initialize(capabilities);
            if (capabilities?.window?.workDoneProgress === true) {
                this._progressSupported = true;
                this.connection.onNotification(vscode_languageserver_protocol_1$d.WorkDoneProgressCancelNotification.type, (params) => {
                    let progress = WorkDoneProgressReporterImpl.Instances.get(params.token);
                    if (progress instanceof WorkDoneProgressServerReporterImpl || progress instanceof NullProgressServerReporter) {
                        progress.cancel();
                    }
                });
            }
        }
        attachWorkDoneProgress(token) {
            if (token === undefined) {
                return new NullProgressReporter();
            }
            else {
                return new WorkDoneProgressReporterImpl(this.connection, token);
            }
        }
        createWorkDoneProgress() {
            if (this._progressSupported) {
                const token = (0, uuid_1.generateUuid)();
                return this.connection.sendRequest(vscode_languageserver_protocol_1$d.WorkDoneProgressCreateRequest.type, { token }).then(() => {
                    const result = new WorkDoneProgressServerReporterImpl(this.connection, token);
                    return result;
                });
            }
            else {
                return Promise.resolve(new NullProgressServerReporter());
            }
        }
    };
};
progress.ProgressFeature = ProgressFeature;
var ResultProgress;
(function (ResultProgress) {
    ResultProgress.type = new vscode_languageserver_protocol_1$d.ProgressType();
})(ResultProgress || (ResultProgress = {}));
class ResultProgressReporterImpl {
    constructor(_connection, _token) {
        this._connection = _connection;
        this._token = _token;
    }
    report(data) {
        this._connection.sendProgress(ResultProgress.type, this._token, data);
    }
}
function attachPartialResult(connection, params) {
    if (params === undefined || params.partialResultToken === undefined) {
        return undefined;
    }
    const token = params.partialResultToken;
    delete params.partialResultToken;
    return new ResultProgressReporterImpl(connection, token);
}
progress.attachPartialResult = attachPartialResult;

var configuration = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(configuration, "__esModule", { value: true });
configuration.ConfigurationFeature = void 0;
const vscode_languageserver_protocol_1$c = main$2;
const Is$1 = is;
const ConfigurationFeature = (Base) => {
    return class extends Base {
        getConfiguration(arg) {
            if (!arg) {
                return this._getConfiguration({});
            }
            else if (Is$1.string(arg)) {
                return this._getConfiguration({ section: arg });
            }
            else {
                return this._getConfiguration(arg);
            }
        }
        _getConfiguration(arg) {
            let params = {
                items: Array.isArray(arg) ? arg : [arg]
            };
            return this.connection.sendRequest(vscode_languageserver_protocol_1$c.ConfigurationRequest.type, params).then((result) => {
                if (Array.isArray(result)) {
                    return Array.isArray(arg) ? result : result[0];
                }
                else {
                    return Array.isArray(arg) ? [] : null;
                }
            });
        }
    };
};
configuration.ConfigurationFeature = ConfigurationFeature;

var workspaceFolder = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(workspaceFolder, "__esModule", { value: true });
workspaceFolder.WorkspaceFoldersFeature = void 0;
const vscode_languageserver_protocol_1$b = main$2;
const WorkspaceFoldersFeature = (Base) => {
    return class extends Base {
        constructor() {
            super();
            this._notificationIsAutoRegistered = false;
        }
        initialize(capabilities) {
            super.initialize(capabilities);
            let workspaceCapabilities = capabilities.workspace;
            if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) {
                this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1$b.Emitter();
                this.connection.onNotification(vscode_languageserver_protocol_1$b.DidChangeWorkspaceFoldersNotification.type, (params) => {
                    this._onDidChangeWorkspaceFolders.fire(params.event);
                });
            }
        }
        fillServerCapabilities(capabilities) {
            super.fillServerCapabilities(capabilities);
            const changeNotifications = capabilities.workspace?.workspaceFolders?.changeNotifications;
            this._notificationIsAutoRegistered = changeNotifications === true || typeof changeNotifications === 'string';
        }
        getWorkspaceFolders() {
            return this.connection.sendRequest(vscode_languageserver_protocol_1$b.WorkspaceFoldersRequest.type);
        }
        get onDidChangeWorkspaceFolders() {
            if (!this._onDidChangeWorkspaceFolders) {
                throw new Error('Client doesn\'t support sending workspace folder change events.');
            }
            if (!this._notificationIsAutoRegistered && !this._unregistration) {
                this._unregistration = this.connection.client.register(vscode_languageserver_protocol_1$b.DidChangeWorkspaceFoldersNotification.type);
            }
            return this._onDidChangeWorkspaceFolders.event;
        }
    };
};
workspaceFolder.WorkspaceFoldersFeature = WorkspaceFoldersFeature;

var callHierarchy = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(callHierarchy, "__esModule", { value: true });
callHierarchy.CallHierarchyFeature = void 0;
const vscode_languageserver_protocol_1$a = main$2;
const CallHierarchyFeature = (Base) => {
    return class extends Base {
        get callHierarchy() {
            return {
                onPrepare: (handler) => {
                    return this.connection.onRequest(vscode_languageserver_protocol_1$a.CallHierarchyPrepareRequest.type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), undefined);
                    });
                },
                onIncomingCalls: (handler) => {
                    const type = vscode_languageserver_protocol_1$a.CallHierarchyIncomingCallsRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                },
                onOutgoingCalls: (handler) => {
                    const type = vscode_languageserver_protocol_1$a.CallHierarchyOutgoingCallsRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                }
            };
        }
    };
};
callHierarchy.CallHierarchyFeature = CallHierarchyFeature;

var showDocument = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(showDocument, "__esModule", { value: true });
showDocument.ShowDocumentFeature = void 0;
const vscode_languageserver_protocol_1$9 = main$2;
const ShowDocumentFeature = (Base) => {
    return class extends Base {
        showDocument(params) {
            return this.connection.sendRequest(vscode_languageserver_protocol_1$9.ShowDocumentRequest.type, params);
        }
    };
};
showDocument.ShowDocumentFeature = ShowDocumentFeature;

var fileOperations = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(fileOperations, "__esModule", { value: true });
fileOperations.FileOperationsFeature = void 0;
const vscode_languageserver_protocol_1$8 = main$2;
const FileOperationsFeature = (Base) => {
    return class extends Base {
        onDidCreateFiles(handler) {
            return this.connection.onNotification(vscode_languageserver_protocol_1$8.DidCreateFilesNotification.type, (params) => {
                handler(params);
            });
        }
        onDidRenameFiles(handler) {
            return this.connection.onNotification(vscode_languageserver_protocol_1$8.DidRenameFilesNotification.type, (params) => {
                handler(params);
            });
        }
        onDidDeleteFiles(handler) {
            return this.connection.onNotification(vscode_languageserver_protocol_1$8.DidDeleteFilesNotification.type, (params) => {
                handler(params);
            });
        }
        onWillCreateFiles(handler) {
            return this.connection.onRequest(vscode_languageserver_protocol_1$8.WillCreateFilesRequest.type, (params, cancel) => {
                return handler(params, cancel);
            });
        }
        onWillRenameFiles(handler) {
            return this.connection.onRequest(vscode_languageserver_protocol_1$8.WillRenameFilesRequest.type, (params, cancel) => {
                return handler(params, cancel);
            });
        }
        onWillDeleteFiles(handler) {
            return this.connection.onRequest(vscode_languageserver_protocol_1$8.WillDeleteFilesRequest.type, (params, cancel) => {
                return handler(params, cancel);
            });
        }
    };
};
fileOperations.FileOperationsFeature = FileOperationsFeature;

var linkedEditingRange = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(linkedEditingRange, "__esModule", { value: true });
linkedEditingRange.LinkedEditingRangeFeature = void 0;
const vscode_languageserver_protocol_1$7 = main$2;
const LinkedEditingRangeFeature = (Base) => {
    return class extends Base {
        onLinkedEditingRange(handler) {
            return this.connection.onRequest(vscode_languageserver_protocol_1$7.LinkedEditingRangeRequest.type, (params, cancel) => {
                return handler(params, cancel, this.attachWorkDoneProgress(params), undefined);
            });
        }
    };
};
linkedEditingRange.LinkedEditingRangeFeature = LinkedEditingRangeFeature;

var typeHierarchy = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(typeHierarchy, "__esModule", { value: true });
typeHierarchy.TypeHierarchyFeature = void 0;
const vscode_languageserver_protocol_1$6 = main$2;
const TypeHierarchyFeature = (Base) => {
    return class extends Base {
        get typeHierarchy() {
            return {
                onPrepare: (handler) => {
                    return this.connection.onRequest(vscode_languageserver_protocol_1$6.TypeHierarchyPrepareRequest.type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), undefined);
                    });
                },
                onSupertypes: (handler) => {
                    const type = vscode_languageserver_protocol_1$6.TypeHierarchySupertypesRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                },
                onSubtypes: (handler) => {
                    const type = vscode_languageserver_protocol_1$6.TypeHierarchySubtypesRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                }
            };
        }
    };
};
typeHierarchy.TypeHierarchyFeature = TypeHierarchyFeature;

var inlineValue = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(inlineValue, "__esModule", { value: true });
inlineValue.InlineValueFeature = void 0;
const vscode_languageserver_protocol_1$5 = main$2;
const InlineValueFeature = (Base) => {
    return class extends Base {
        get inlineValue() {
            return {
                refresh: () => {
                    return this.connection.sendRequest(vscode_languageserver_protocol_1$5.InlineValueRefreshRequest.type);
                },
                on: (handler) => {
                    return this.connection.onRequest(vscode_languageserver_protocol_1$5.InlineValueRequest.type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params));
                    });
                }
            };
        }
    };
};
inlineValue.InlineValueFeature = InlineValueFeature;

var foldingRange = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(foldingRange, "__esModule", { value: true });
foldingRange.FoldingRangeFeature = void 0;
const vscode_languageserver_protocol_1$4 = main$2;
const FoldingRangeFeature = (Base) => {
    return class extends Base {
        get foldingRange() {
            return {
                refresh: () => {
                    return this.connection.sendRequest(vscode_languageserver_protocol_1$4.FoldingRangeRefreshRequest.type);
                },
                on: (handler) => {
                    const type = vscode_languageserver_protocol_1$4.FoldingRangeRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                }
            };
        }
    };
};
foldingRange.FoldingRangeFeature = FoldingRangeFeature;

var inlayHint = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(inlayHint, "__esModule", { value: true });
inlayHint.InlayHintFeature = void 0;
const vscode_languageserver_protocol_1$3 = main$2;
const InlayHintFeature = (Base) => {
    return class extends Base {
        get inlayHint() {
            return {
                refresh: () => {
                    return this.connection.sendRequest(vscode_languageserver_protocol_1$3.InlayHintRefreshRequest.type);
                },
                on: (handler) => {
                    return this.connection.onRequest(vscode_languageserver_protocol_1$3.InlayHintRequest.type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params));
                    });
                },
                resolve: (handler) => {
                    return this.connection.onRequest(vscode_languageserver_protocol_1$3.InlayHintResolveRequest.type, (params, cancel) => {
                        return handler(params, cancel);
                    });
                }
            };
        }
    };
};
inlayHint.InlayHintFeature = InlayHintFeature;

var diagnostic = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(diagnostic, "__esModule", { value: true });
diagnostic.DiagnosticFeature = void 0;
const vscode_languageserver_protocol_1$2 = main$2;
const DiagnosticFeature = (Base) => {
    return class extends Base {
        get diagnostics() {
            return {
                refresh: () => {
                    return this.connection.sendRequest(vscode_languageserver_protocol_1$2.DiagnosticRefreshRequest.type);
                },
                on: (handler) => {
                    return this.connection.onRequest(vscode_languageserver_protocol_1$2.DocumentDiagnosticRequest.type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(vscode_languageserver_protocol_1$2.DocumentDiagnosticRequest.partialResult, params));
                    });
                },
                onWorkspace: (handler) => {
                    return this.connection.onRequest(vscode_languageserver_protocol_1$2.WorkspaceDiagnosticRequest.type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(vscode_languageserver_protocol_1$2.WorkspaceDiagnosticRequest.partialResult, params));
                    });
                }
            };
        }
    };
};
diagnostic.DiagnosticFeature = DiagnosticFeature;

var moniker = {};

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(moniker, "__esModule", { value: true });
moniker.MonikerFeature = void 0;
const vscode_languageserver_protocol_1$1 = main$2;
const MonikerFeature = (Base) => {
    return class extends Base {
        get moniker() {
            return {
                on: (handler) => {
                    const type = vscode_languageserver_protocol_1$1.MonikerRequest.type;
                    return this.connection.onRequest(type, (params, cancel) => {
                        return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                    });
                },
            };
        }
    };
};
moniker.MonikerFeature = MonikerFeature;

/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */
Object.defineProperty(server, "__esModule", { value: true });
server.createConnection = server.combineFeatures = server.combineNotebooksFeatures = server.combineLanguagesFeatures = server.combineWorkspaceFeatures = server.combineWindowFeatures = server.combineClientFeatures = server.combineTracerFeatures = server.combineTelemetryFeatures = server.combineConsoleFeatures = server._NotebooksImpl = server._LanguagesImpl = server.BulkUnregistration = server.BulkRegistration = server.ErrorMessageTracker = void 0;
const vscode_languageserver_protocol_1 = main$2;
const Is = is;
const UUID = uuid;
const progress_1 = progress;
const configuration_1 = configuration;
const workspaceFolder_1 = workspaceFolder;
const callHierarchy_1 = callHierarchy;
const semanticTokens_1 = semanticTokens;
const showDocument_1 = showDocument;
const fileOperations_1 = fileOperations;
const linkedEditingRange_1 = linkedEditingRange;
const typeHierarchy_1 = typeHierarchy;
const inlineValue_1 = inlineValue;
const foldingRange_1 = foldingRange;
// import { InlineCompletionFeatureShape, InlineCompletionFeature } from './inlineCompletion.proposed';
const inlayHint_1 = inlayHint;
const diagnostic_1 = diagnostic;
const notebook_1 = notebook;
const moniker_1 = moniker;
function null2Undefined(value) {
    if (value === null) {
        return undefined;
    }
    return value;
}
/**
 * Helps tracking error message. Equal occurrences of the same
 * message are only stored once. This class is for example
 * useful if text documents are validated in a loop and equal
 * error message should be folded into one.
 */
class ErrorMessageTracker {
    constructor() {
        this._messages = Object.create(null);
    }
    /**
     * Add a message to the tracker.
     *
     * @param message The message to add.
     */
    add(message) {
        let count = this._messages[message];
        if (!count) {
            count = 0;
        }
        count++;
        this._messages[message] = count;
    }
    /**
     * Send all tracked messages to the connection's window.
     *
     * @param connection The connection established between client and server.
     */
    sendErrors(connection) {
        Object.keys(this._messages).forEach(message => {
            connection.window.showErrorMessage(message);
        });
    }
}
server.ErrorMessageTracker = ErrorMessageTracker;
class RemoteConsoleImpl {
    constructor() {
    }
    rawAttach(connection) {
        this._rawConnection = connection;
    }
    attach(connection) {
        this._connection = connection;
    }
    get connection() {
        if (!this._connection) {
            throw new Error('Remote is not attached to a connection yet.');
        }
        return this._connection;
    }
    fillServerCapabilities(_capabilities) {
    }
    initialize(_capabilities) {
    }
    error(message) {
        this.send(vscode_languageserver_protocol_1.MessageType.Error, message);
    }
    warn(message) {
        this.send(vscode_languageserver_protocol_1.MessageType.Warning, message);
    }
    info(message) {
        this.send(vscode_languageserver_protocol_1.MessageType.Info, message);
    }
    log(message) {
        this.send(vscode_languageserver_protocol_1.MessageType.Log, message);
    }
    debug(message) {
        this.send(vscode_languageserver_protocol_1.MessageType.Debug, message);
    }
    send(type, message) {
        if (this._rawConnection) {
            this._rawConnection.sendNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, { type, message }).catch(() => {
                (0, vscode_languageserver_protocol_1.RAL)().console.error(`Sending log message failed`);
            });
        }
    }
}
class _RemoteWindowImpl {
    constructor() {
    }
    attach(connection) {
        this._connection = connection;
    }
    get connection() {
        if (!this._connection) {
            throw new Error('Remote is not attached to a connection yet.');
        }
        return this._connection;
    }
    initialize(_capabilities) {
    }
    fillServerCapabilities(_capabilities) {
    }
    showErrorMessage(message, ...actions) {
        let params = { type: vscode_languageserver_protocol_1.MessageType.Error, message, actions };
        return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
    }
    showWarningMessage(message, ...actions) {
        let params = { type: vscode_languageserver_protocol_1.MessageType.Warning, message, actions };
        return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
    }
    showInformationMessage(message, ...actions) {
        let params = { type: vscode_languageserver_protocol_1.MessageType.Info, message, actions };
        return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
    }
}
const RemoteWindowImpl = (0, showDocument_1.ShowDocumentFeature)((0, progress_1.ProgressFeature)(_RemoteWindowImpl));
var BulkRegistration;
(function (BulkRegistration) {
    /**
     * Creates a new bulk registration.
     * @return an empty bulk registration.
     */
    function create() {
        return new BulkRegistrationImpl();
    }
    BulkRegistration.create = create;
})(BulkRegistration || (server.BulkRegistration = BulkRegistration = {}));
class BulkRegistrationImpl {
    constructor() {
        this._registrations = [];
        this._registered = new Set();
    }
    add(type, registerOptions) {
        const method = Is.string(type) ? type : type.method;
        if (this._registered.has(method)) {
            throw new Error(`${method} is already added to this registration`);
        }
        const id = UUID.generateUuid();
        this._registrations.push({
            id: id,
            method: method,
            registerOptions: registerOptions || {}
        });
        this._registered.add(method);
    }
    asRegistrationParams() {
        return {
            registrations: this._registrations
        };
    }
}
var BulkUnregistration;
(function (BulkUnregistration) {
    function create() {
        return new BulkUnregistrationImpl(undefined, []);
    }
    BulkUnregistration.create = create;
})(BulkUnregistration || (server.BulkUnregistration = BulkUnregistration = {}));
class BulkUnregistrationImpl {
    constructor(_connection, unregistrations) {
        this._connection = _connection;
        this._unregistrations = new Map();
        unregistrations.forEach(unregistration => {
            this._unregistrations.set(unregistration.method, unregistration);
        });
    }
    get isAttached() {
        return !!this._connection;
    }
    attach(connection) {
        this._connection = connection;
    }
    add(unregistration) {
        this._unregistrations.set(unregistration.method, unregistration);
    }
    dispose() {
        let unregistrations = [];
        for (let unregistration of this._unregistrations.values()) {
            unregistrations.push(unregistration);
        }
        let params = {
            unregisterations: unregistrations
        };
        this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).catch(() => {
            this._connection.console.info(`Bulk unregistration failed.`);
        });
    }
    disposeSingle(arg) {
        const method = Is.string(arg) ? arg : arg.method;
        const unregistration = this._unregistrations.get(method);
        if (!unregistration) {
            return false;
        }
        let params = {
            unregisterations: [unregistration]
        };
        this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(() => {
            this._unregistrations.delete(method);
        }, (_error) => {
            this._connection.console.info(`Un-registering request handler for ${unregistration.id} failed.`);
        });
        return true;
    }
}
class RemoteClientImpl {
    attach(connection) {
        this._connection = connection;
    }
    get connection() {
        if (!this._connection) {
            throw new Error('Remote is not attached to a connection yet.');
        }
        return this._connection;
    }
    initialize(_capabilities) {
    }
    fillServerCapabilities(_capabilities) {
    }
    register(typeOrRegistrations, registerOptionsOrType, registerOptions) {
        if (typeOrRegistrations instanceof BulkRegistrationImpl) {
            return this.registerMany(typeOrRegistrations);
        }
        else if (typeOrRegistrations instanceof BulkUnregistrationImpl) {
            return this.registerSingle1(typeOrRegistrations, registerOptionsOrType, registerOptions);
        }
        else {
            return this.registerSingle2(typeOrRegistrations, registerOptionsOrType);
        }
    }
    registerSingle1(unregistration, type, registerOptions) {
        const method = Is.string(type) ? type : type.method;
        const id = UUID.generateUuid();
        let params = {
            registrations: [{ id, method, registerOptions: registerOptions || {} }]
        };
        if (!unregistration.isAttached) {
            unregistration.attach(this.connection);
        }
        return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
            unregistration.add({ id: id, method: method });
            return unregistration;
        }, (_error) => {
            this.connection.console.info(`Registering request handler for ${method} failed.`);
            return Promise.reject(_error);
        });
    }
    registerSingle2(type, registerOptions) {
        const method = Is.string(type) ? type : type.method;
        const id = UUID.generateUuid();
        let params = {
            registrations: [{ id, method, registerOptions: registerOptions || {} }]
        };
        return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
            return vscode_languageserver_protocol_1.Disposable.create(() => {
                this.unregisterSingle(id, method).catch(() => { this.connection.console.info(`Un-registering capability with id ${id} failed.`); });
            });
        }, (_error) => {
            this.connection.console.info(`Registering request handler for ${method} failed.`);
            return Promise.reject(_error);
        });
    }
    unregisterSingle(id, method) {
        let params = {
            unregisterations: [{ id, method }]
        };
        return this.connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).catch(() => {
            this.connection.console.info(`Un-registering request handler for ${id} failed.`);
        });
    }
    registerMany(registrations) {
        let params = registrations.asRegistrationParams();
        return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then(() => {
            return new BulkUnregistrationImpl(this._connection, params.registrations.map(registration => { return { id: registration.id, method: registration.method }; }));
        }, (_error) => {
            this.connection.console.info(`Bulk registration failed.`);
            return Promise.reject(_error);
        });
    }
}
class _RemoteWorkspaceImpl {
    constructor() {
    }
    attach(connection) {
        this._connection = connection;
    }
    get connection() {
        if (!this._connection) {
            throw new Error('Remote is not attached to a connection yet.');
        }
        return this._connection;
    }
    initialize(_capabilities) {
    }
    fillServerCapabilities(_capabilities) {
    }
    applyEdit(paramOrEdit) {
        function isApplyWorkspaceEditParams(value) {
            return value && !!value.edit;
        }
        let params = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit };
        return this.connection.sendRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params);
    }
}
const RemoteWorkspaceImpl = (0, fileOperations_1.FileOperationsFeature)((0, workspaceFolder_1.WorkspaceFoldersFeature)((0, configuration_1.ConfigurationFeature)(_RemoteWorkspaceImpl)));
class TracerImpl {
    constructor() {
        this._trace = vscode_languageserver_protocol_1.Trace.Off;
    }
    attach(connection) {
        this._connection = connection;
    }
    get connection() {
        if (!this._connection) {
            throw new Error('Remote is not attached to a connection yet.');
        }
        return this._connection;
    }
    initialize(_capabilities) {
    }
    fillServerCapabilities(_capabilities) {
    }
    set trace(value) {
        this._trace = value;
    }
    log(message, verbose) {
        if (this._trace === vscode_languageserver_protocol_1.Trace.Off) {
            return;
        }
        this.connection.sendNotification(vscode_languageserver_protocol_1.LogTraceNotification.type, {
            message: message,
            verbose: this._trace === vscode_languageserver_protocol_1.Trace.Verbose ? verbose : undefined
        }).catch(() => {
            // Very hard to decide what to do. We tried to send a log
            // message which failed so we can't simply send another :-(.
        });
    }
}
class TelemetryImpl {
    constructor() {
    }
    attach(connection) {
        this._connection = connection;
    }
    get connection() {
        if (!this._connection) {
            throw new Error('Remote is not attached to a connection yet.');
        }
        return this._connection;
    }
    initialize(_capabilities) {
    }
    fillServerCapabilities(_capabilities) {
    }
    logEvent(data) {
        this.connection.sendNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, data).catch(() => {
            this.connection.console.log(`Sending TelemetryEventNotification failed`);
        });
    }
}
class _LanguagesImpl {
    constructor() {
    }
    attach(connection) {
        this._connection = connection;
    }
    get connection() {
        if (!this._connection) {
            throw new Error('Remote is not attached to a connection yet.');
        }
        return this._connection;
    }
    initialize(_capabilities) {
    }
    fillServerCapabilities(_capabilities) {
    }
    attachWorkDoneProgress(params) {
        return (0, progress_1.attachWorkDone)(this.connection, params);
    }
    attachPartialResultProgress(_type, params) {
        return (0, progress_1.attachPartialResult)(this.connection, params);
    }
}
server._LanguagesImpl = _LanguagesImpl;
const LanguagesImpl = (0, foldingRange_1.FoldingRangeFeature)((0, moniker_1.MonikerFeature)((0, diagnostic_1.DiagnosticFeature)((0, inlayHint_1.InlayHintFeature)((0, inlineValue_1.InlineValueFeature)((0, typeHierarchy_1.TypeHierarchyFeature)((0, linkedEditingRange_1.LinkedEditingRangeFeature)((0, semanticTokens_1.SemanticTokensFeature)((0, callHierarchy_1.CallHierarchyFeature)(_LanguagesImpl)))))))));
class _NotebooksImpl {
    constructor() {
    }
    attach(connection) {
        this._connection = connection;
    }
    get connection() {
        if (!this._connection) {
            throw new Error('Remote is not attached to a connection yet.');
        }
        return this._connection;
    }
    initialize(_capabilities) {
    }
    fillServerCapabilities(_capabilities) {
    }
    attachWorkDoneProgress(params) {
        return (0, progress_1.attachWorkDone)(this.connection, params);
    }
    attachPartialResultProgress(_type, params) {
        return (0, progress_1.attachPartialResult)(this.connection, params);
    }
}
server._NotebooksImpl = _NotebooksImpl;
const NotebooksImpl = (0, notebook_1.NotebookSyncFeature)(_NotebooksImpl);
function combineConsoleFeatures(one, two) {
    return function (Base) {
        return two(one(Base));
    };
}
server.combineConsoleFeatures = combineConsoleFeatures;
function combineTelemetryFeatures(one, two) {
    return function (Base) {
        return two(one(Base));
    };
}
server.combineTelemetryFeatures = combineTelemetryFeatures;
function combineTracerFeatures(one, two) {
    return function (Base) {
        return two(one(Base));
    };
}
server.combineTracerFeatures = combineTracerFeatures;
function combineClientFeatures(one, two) {
    return function (Base) {
        return two(one(Base));
    };
}
server.combineClientFeatures = combineClientFeatures;
function combineWindowFeatures(one, two) {
    return function (Base) {
        return two(one(Base));
    };
}
server.combineWindowFeatures = combineWindowFeatures;
function combineWorkspaceFeatures(one, two) {
    return function (Base) {
        return two(one(Base));
    };
}
server.combineWorkspaceFeatures = combineWorkspaceFeatures;
function combineLanguagesFeatures(one, two) {
    return function (Base) {
        return two(one(Base));
    };
}
server.combineLanguagesFeatures = combineLanguagesFeatures;
function combineNotebooksFeatures(one, two) {
    return function (Base) {
        return two(one(Base));
    };
}
server.combineNotebooksFeatures = combineNotebooksFeatures;
function combineFeatures(one, two) {
    function combine(one, two, func) {
        if (one && two) {
            return func(one, two);
        }
        else if (one) {
            return one;
        }
        else {
            return two;
        }
    }
    let result = {
        __brand: 'features',
        console: combine(one.console, two.console, combineConsoleFeatures),
        tracer: combine(one.tracer, two.tracer, combineTracerFeatures),
        telemetry: combine(one.telemetry, two.telemetry, combineTelemetryFeatures),
        client: combine(one.client, two.client, combineClientFeatures),
        window: combine(one.window, two.window, combineWindowFeatures),
        workspace: combine(one.workspace, two.workspace, combineWorkspaceFeatures),
        languages: combine(one.languages, two.languages, combineLanguagesFeatures),
        notebooks: combine(one.notebooks, two.notebooks, combineNotebooksFeatures)
    };
    return result;
}
server.combineFeatures = combineFeatures;
function createConnection(connectionFactory, watchDog, factories) {
    const logger = (factories && factories.console ? new (factories.console(RemoteConsoleImpl))() : new RemoteConsoleImpl());
    const connection = connectionFactory(logger);
    logger.rawAttach(connection);
    const tracer = (factories && factories.tracer ? new (factories.tracer(TracerImpl))() : new TracerImpl());
    const telemetry = (factories && factories.telemetry ? new (factories.telemetry(TelemetryImpl))() : new TelemetryImpl());
    const client = (factories && factories.client ? new (factories.client(RemoteClientImpl))() : new RemoteClientImpl());
    const remoteWindow = (factories && factories.window ? new (factories.window(RemoteWindowImpl))() : new RemoteWindowImpl());
    const workspace = (factories && factories.workspace ? new (factories.workspace(RemoteWorkspaceImpl))() : new RemoteWorkspaceImpl());
    const languages = (factories && factories.languages ? new (factories.languages(LanguagesImpl))() : new LanguagesImpl());
    const notebooks = (factories && factories.notebooks ? new (factories.notebooks(NotebooksImpl))() : new NotebooksImpl());
    const allRemotes = [logger, tracer, telemetry, client, remoteWindow, workspace, languages, notebooks];
    function asPromise(value) {
        if (value instanceof Promise) {
            return value;
        }
        else if (Is.thenable(value)) {
            return new Promise((resolve, reject) => {
                value.then((resolved) => resolve(resolved), (error) => reject(error));
            });
        }
        else {
            return Promise.resolve(value);
        }
    }
    let shutdownHandler = undefined;
    let initializeHandler = undefined;
    let exitHandler = undefined;
    let protocolConnection = {
        listen: () => connection.listen(),
        sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params),
        onRequest: (type, handler) => connection.onRequest(type, handler),
        sendNotification: (type, param) => {
            const method = Is.string(type) ? type : type.method;
            return connection.sendNotification(method, param);
        },
        onNotification: (type, handler) => connection.onNotification(type, handler),
        onProgress: connection.onProgress,
        sendProgress: connection.sendProgress,
        onInitialize: (handler) => {
            initializeHandler = handler;
            return {
                dispose: () => {
                    initializeHandler = undefined;
                }
            };
        },
        onInitialized: (handler) => connection.onNotification(vscode_languageserver_protocol_1.InitializedNotification.type, handler),
        onShutdown: (handler) => {
            shutdownHandler = handler;
            return {
                dispose: () => {
                    shutdownHandler = undefined;
                }
            };
        },
        onExit: (handler) => {
            exitHandler = handler;
            return {
                dispose: () => {
                    exitHandler = undefined;
                }
            };
        },
        get console() { return logger; },
        get telemetry() { return telemetry; },
        get tracer() { return tracer; },
        get client() { return client; },
        get window() { return remoteWindow; },
        get workspace() { return workspace; },
        get languages() { return languages; },
        get notebooks() { return notebooks; },
        onDidChangeConfiguration: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, handler),
        onDidChangeWatchedFiles: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, handler),
        __textDocumentSync: undefined,
        onDidOpenTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, handler),
        onDidChangeTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, handler),
        onDidCloseTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, handler),
        onWillSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, handler),
        onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, handler),
        onDidSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, handler),
        sendDiagnostics: (params) => connection.sendNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params),
        onHover: (handler) => connection.onRequest(vscode_languageserver_protocol_1.HoverRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined);
        }),
        onCompletion: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onCompletionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, handler),
        onSignatureHelp: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined);
        }),
        onDeclaration: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onTypeDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onImplementation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onReferences: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onDocumentHighlight: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onDocumentSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onWorkspaceSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onWorkspaceSymbolResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, handler),
        onCodeAction: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onCodeActionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, (params, cancel) => {
            return handler(params, cancel);
        }),
        onCodeLens: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onCodeLensResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, (params, cancel) => {
            return handler(params, cancel);
        }),
        onDocumentFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined);
        }),
        onDocumentRangeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined);
        }),
        onDocumentOnTypeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, (params, cancel) => {
            return handler(params, cancel);
        }),
        onRenameRequest: (handler) => connection.onRequest(vscode_languageserver_protocol_1.RenameRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined);
        }),
        onPrepareRename: (handler) => connection.onRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, (params, cancel) => {
            return handler(params, cancel);
        }),
        onDocumentLinks: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onDocumentLinkResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, (params, cancel) => {
            return handler(params, cancel);
        }),
        onDocumentColor: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onColorPresentation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onFoldingRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onSelectionRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
        }),
        onExecuteCommand: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined);
        }),
        dispose: () => connection.dispose()
    };
    for (let remote of allRemotes) {
        remote.attach(protocolConnection);
    }
    connection.onRequest(vscode_languageserver_protocol_1.InitializeRequest.type, (params) => {
        watchDog.initialize(params);
        if (Is.string(params.trace)) {
            tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.trace);
        }
        for (let remote of allRemotes) {
            remote.initialize(params.capabilities);
        }
        if (initializeHandler) {
            let result = initializeHandler(params, new vscode_languageserver_protocol_1.CancellationTokenSource().token, (0, progress_1.attachWorkDone)(connection, params), undefined);
            return asPromise(result).then((value) => {
                if (value instanceof vscode_languageserver_protocol_1.ResponseError) {
                    return value;
                }
                let result = value;
                if (!result) {
                    result = { capabilities: {} };
                }
                let capabilities = result.capabilities;
                if (!capabilities) {
                    capabilities = {};
                    result.capabilities = capabilities;
                }
                if (capabilities.textDocumentSync === undefined || capabilities.textDocumentSync === null) {
                    capabilities.textDocumentSync = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
                }
                else if (!Is.number(capabilities.textDocumentSync) && !Is.number(capabilities.textDocumentSync.change)) {
                    capabilities.textDocumentSync.change = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
                }
                for (let remote of allRemotes) {
                    remote.fillServerCapabilities(capabilities);
                }
                return result;
            });
        }
        else {
            let result = { capabilities: { textDocumentSync: vscode_languageserver_protocol_1.TextDocumentSyncKind.None } };
            for (let remote of allRemotes) {
                remote.fillServerCapabilities(result.capabilities);
            }
            return result;
        }
    });
    connection.onRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, () => {
        watchDog.shutdownReceived = true;
        if (shutdownHandler) {
            return shutdownHandler(new vscode_languageserver_protocol_1.CancellationTokenSource().token);
        }
        else {
            return undefined;
        }
    });
    connection.onNotification(vscode_languageserver_protocol_1.ExitNotification.type, () => {
        try {
            if (exitHandler) {
                exitHandler();
            }
        }
        finally {
            if (watchDog.shutdownReceived) {
                watchDog.exit(0);
            }
            else {
                watchDog.exit(1);
            }
        }
    });
    connection.onNotification(vscode_languageserver_protocol_1.SetTraceNotification.type, (params) => {
        tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.value);
    });
    return protocolConnection;
}
server.createConnection = createConnection;

(function (exports) {
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	var __createBinding = (commonjsGlobal && commonjsGlobal.__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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
	    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ProposedFeatures = exports.NotebookDocuments = exports.TextDocuments = exports.SemanticTokensBuilder = void 0;
	const semanticTokens_1 = semanticTokens;
	Object.defineProperty(exports, "SemanticTokensBuilder", { enumerable: true, get: function () { return semanticTokens_1.SemanticTokensBuilder; } });
	const ic = inlineCompletion_proposed;
	__exportStar(main$2, exports);
	const textDocuments_1 = textDocuments;
	Object.defineProperty(exports, "TextDocuments", { enumerable: true, get: function () { return textDocuments_1.TextDocuments; } });
	const notebook_1 = notebook;
	Object.defineProperty(exports, "NotebookDocuments", { enumerable: true, get: function () { return notebook_1.NotebookDocuments; } });
	__exportStar(server, exports);
	var ProposedFeatures;
	(function (ProposedFeatures) {
	    ProposedFeatures.all = {
	        __brand: 'features',
	        languages: ic.InlineCompletionFeature
	    };
	})(ProposedFeatures || (exports.ProposedFeatures = ProposedFeatures = {})); 
} (api$2));

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

var browser = main$2;

(function (exports) {
	/* --------------------------------------------------------------------------------------------
	 * Copyright (c) Microsoft Corporation. All rights reserved.
	 * Licensed under the MIT License. See License.txt in the project root for license information.
	 * ------------------------------------------------------------------------------------------ */
	var __createBinding = (commonjsGlobal && commonjsGlobal.__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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
	    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.createConnection = void 0;
	const api_1 = api$2;
	__exportStar(browser, exports);
	__exportStar(api$2, exports);
	let _shutdownReceived = false;
	const watchDog = {
	    initialize: (_params) => {
	    },
	    get shutdownReceived() {
	        return _shutdownReceived;
	    },
	    set shutdownReceived(value) {
	        _shutdownReceived = value;
	    },
	    exit: (_code) => {
	    }
	};
	function createConnection(arg1, arg2, arg3, arg4) {
	    let factories;
	    let reader;
	    let writer;
	    let options;
	    if (arg1 !== void 0 && arg1.__brand === 'features') {
	        factories = arg1;
	        arg1 = arg2;
	        arg2 = arg3;
	        arg3 = arg4;
	    }
	    if (api_1.ConnectionStrategy.is(arg1) || api_1.ConnectionOptions.is(arg1)) {
	        options = arg1;
	    }
	    else {
	        reader = arg1;
	        writer = arg2;
	        options = arg3;
	    }
	    const connectionFactory = (logger) => {
	        return (0, api_1.createProtocolConnection)(reader, writer, logger, options);
	    };
	    return (0, api_1.createConnection)(connectionFactory, watchDog, factories);
	}
	exports.createConnection = createConnection; 
} (main$3));

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

var node = main$3;

async function resolveCodeFix(codeFix) {
    const context = createCodeFixContext();
    const values = await codeFix.fix(context);
    const textEdit = values === undefined ? [] : isArray(values) ? values : [values];
    return textEdit;
}
function createCodeFixContext() {
    return {
        prependText,
        appendText,
        replaceText,
    };
    function prependText(node, text) {
        return {
            kind: "insert-text",
            pos: node.pos,
            text,
            file: node.file,
        };
    }
    function appendText(node, text) {
        return {
            kind: "insert-text",
            pos: "end" in node ? node.end : node.pos,
            text,
            file: node.file,
        };
    }
    function replaceText(node, text) {
        return {
            kind: "replace-text",
            pos: node.pos,
            end: node.end,
            file: node.file,
            text,
        };
    }
}

var SemanticTokenKind;
(function (SemanticTokenKind) {
    SemanticTokenKind[SemanticTokenKind["Namespace"] = 0] = "Namespace";
    SemanticTokenKind[SemanticTokenKind["Type"] = 1] = "Type";
    SemanticTokenKind[SemanticTokenKind["Class"] = 2] = "Class";
    SemanticTokenKind[SemanticTokenKind["Enum"] = 3] = "Enum";
    SemanticTokenKind[SemanticTokenKind["Interface"] = 4] = "Interface";
    SemanticTokenKind[SemanticTokenKind["Struct"] = 5] = "Struct";
    SemanticTokenKind[SemanticTokenKind["TypeParameter"] = 6] = "TypeParameter";
    SemanticTokenKind[SemanticTokenKind["Parameter"] = 7] = "Parameter";
    SemanticTokenKind[SemanticTokenKind["Variable"] = 8] = "Variable";
    SemanticTokenKind[SemanticTokenKind["Property"] = 9] = "Property";
    SemanticTokenKind[SemanticTokenKind["EnumMember"] = 10] = "EnumMember";
    SemanticTokenKind[SemanticTokenKind["Event"] = 11] = "Event";
    SemanticTokenKind[SemanticTokenKind["Function"] = 12] = "Function";
    SemanticTokenKind[SemanticTokenKind["Method"] = 13] = "Method";
    SemanticTokenKind[SemanticTokenKind["Macro"] = 14] = "Macro";
    SemanticTokenKind[SemanticTokenKind["Keyword"] = 15] = "Keyword";
    SemanticTokenKind[SemanticTokenKind["Comment"] = 16] = "Comment";
    SemanticTokenKind[SemanticTokenKind["String"] = 17] = "String";
    SemanticTokenKind[SemanticTokenKind["Number"] = 18] = "Number";
    SemanticTokenKind[SemanticTokenKind["Regexp"] = 19] = "Regexp";
    SemanticTokenKind[SemanticTokenKind["Operator"] = 20] = "Operator";
    SemanticTokenKind[SemanticTokenKind["DocCommentTag"] = 21] = "DocCommentTag";
})(SemanticTokenKind || (SemanticTokenKind = {}));

/**
 * Compute the semantic tokens for the given AST.
 * @returns Semantic tokens
 */
function getSemanticTokens(ast) {
    const ignore = -1;
    const defer = -2;
    const file = ast.file;
    const tokens = mapTokens();
    classifyNode(ast);
    return Array.from(tokens.values()).filter((t) => t.kind !== undefined);
    function mapTokens() {
        const tokens = new Map();
        const scanner = createScanner(file, () => { });
        const templateStack = [];
        while (scanner.scan() !== Token.EndOfFile) {
            if (scanner.tokenFlags & TokenFlags.DocComment) {
                classifyDocComment({ pos: scanner.tokenPosition, end: scanner.position });
            }
            else {
                handleToken(scanner.token, scanner.tokenFlags, {
                    pos: scanner.tokenPosition,
                    end: scanner.position,
                });
            }
        }
        return tokens;
        function classifyDocComment(range) {
            scanner.scanRange(range, () => {
                while (scanner.scanDoc() !== Token.EndOfFile) {
                    const kind = classifyDocToken(scanner.token);
                    if (kind === ignore) {
                        continue;
                    }
                    tokens.set(scanner.tokenPosition, {
                        kind: kind === defer ? undefined : kind,
                        pos: scanner.tokenPosition,
                        end: scanner.position,
                    });
                }
            });
        }
        function handleToken(token, tokenFlags, range) {
            switch (token) {
                case Token.StringTemplateHead:
                    templateStack.push([token, tokenFlags]);
                    classifyStringTemplate(token, range);
                    break;
                case Token.OpenBrace:
                    // If we don't have anything on the template stack,
                    // then we aren't trying to keep track of a previously scanned template head.
                    if (templateStack.length > 0) {
                        templateStack.push([token, tokenFlags]);
                    }
                    handleSimpleToken(token, range);
                    break;
                case Token.CloseBrace:
                    // If we don't have anything on the template stack,
                    // then we aren't trying to keep track of a previously scanned template head.
                    if (templateStack.length > 0) {
                        const [lastToken, lastTokenFlags] = templateStack[templateStack.length - 1];
                        if (lastToken === Token.StringTemplateHead) {
                            token = scanner.reScanStringTemplate(lastTokenFlags);
                            // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us.
                            if (token === Token.StringTemplateTail) {
                                templateStack.pop();
                                classifyStringTemplate(token, {
                                    pos: scanner.tokenPosition,
                                    end: scanner.position,
                                });
                            }
                            else {
                                compilerAssert(token === Token.StringTemplateMiddle, "Should have been a template middle.");
                                classifyStringTemplate(token, {
                                    pos: scanner.tokenPosition,
                                    end: scanner.position,
                                });
                            }
                        }
                        else {
                            compilerAssert(lastToken === Token.OpenBrace, "Should have been an open brace");
                            templateStack.pop();
                        }
                        break;
                    }
                    handleSimpleToken(token, range);
                    break;
                default:
                    handleSimpleToken(token, range);
            }
        }
        function handleSimpleToken(token, range) {
            const kind = classifyToken(scanner.token);
            if (kind === ignore) {
                return;
            }
            tokens.set(range.pos, {
                kind: kind === defer ? undefined : kind,
                ...range,
            });
        }
        function classifyStringTemplate(token, range) {
            const stringStart = token === Token.StringTemplateHead ? range.pos : range.pos + 1;
            const stringEnd = token === Token.StringTemplateTail ? range.end : range.end - 2;
            if (stringStart !== range.pos) {
                tokens.set(range.pos, {
                    kind: SemanticTokenKind.Operator,
                    pos: range.pos,
                    end: stringStart,
                });
            }
            tokens.set(stringStart, {
                kind: SemanticTokenKind.String,
                pos: stringStart,
                end: stringEnd,
            });
            if (stringEnd !== range.end) {
                tokens.set(stringEnd, {
                    kind: SemanticTokenKind.Operator,
                    pos: stringEnd,
                    end: range.end,
                });
            }
        }
    }
    function classifyToken(token) {
        switch (token) {
            case Token.Identifier:
                return defer;
            case Token.StringLiteral:
                return SemanticTokenKind.String;
            case Token.NumericLiteral:
                return SemanticTokenKind.Number;
            case Token.MultiLineComment:
            case Token.SingleLineComment:
                return SemanticTokenKind.Comment;
            default:
                if (isKeyword(token)) {
                    return SemanticTokenKind.Keyword;
                }
                if (isPunctuation(token)) {
                    return SemanticTokenKind.Operator;
                }
                return ignore;
        }
    }
    /** Classify tokens when scanning doc comment. */
    function classifyDocToken(token) {
        switch (token) {
            case Token.NewLine:
            case Token.Whitespace:
                return ignore;
            case Token.DocText:
            case Token.Star:
            case Token.Identifier:
                return SemanticTokenKind.Comment;
            case Token.At:
                return defer;
            default:
                return ignore;
        }
    }
    function classifyNode(node) {
        switch (node.kind) {
            case SyntaxKind.DirectiveExpression:
                classify(node.target, SemanticTokenKind.Keyword);
                break;
            case SyntaxKind.TemplateParameterDeclaration:
                classify(node.id, SemanticTokenKind.TypeParameter);
                break;
            case SyntaxKind.ModelProperty:
            case SyntaxKind.ObjectLiteralProperty:
            case SyntaxKind.UnionVariant:
                if (node.id) {
                    classify(node.id, SemanticTokenKind.Property);
                }
                break;
            case SyntaxKind.AliasStatement:
                classify(node.id, SemanticTokenKind.Struct);
                break;
            case SyntaxKind.ModelStatement:
                classify(node.id, SemanticTokenKind.Struct);
                break;
            case SyntaxKind.ScalarStatement:
                classify(node.id, SemanticTokenKind.Type);
                break;
            case SyntaxKind.ScalarConstructor:
                classify(node.id, SemanticTokenKind.Function);
                break;
            case SyntaxKind.UsingStatement:
                if (node.name.kind === SyntaxKind.Identifier) {
                    classify(node.name, SemanticTokenKind.Namespace);
                }
                break;
            case SyntaxKind.EnumStatement:
                classify(node.id, SemanticTokenKind.Enum);
                break;
            case SyntaxKind.UnionStatement:
                classify(node.id, SemanticTokenKind.Enum);
                break;
            case SyntaxKind.EnumMember:
                classify(node.id, SemanticTokenKind.EnumMember);
                break;
            case SyntaxKind.NamespaceStatement:
                classify(node.id, SemanticTokenKind.Namespace);
                break;
            case SyntaxKind.InterfaceStatement:
                classify(node.id, SemanticTokenKind.Interface);
                break;
            case SyntaxKind.OperationStatement:
                classify(node.id, SemanticTokenKind.Function);
                break;
            case SyntaxKind.DecoratorDeclarationStatement:
                classify(node.id, SemanticTokenKind.Function);
                break;
            case SyntaxKind.FunctionDeclarationStatement:
                classify(node.id, SemanticTokenKind.Function);
                break;
            case SyntaxKind.ConstStatement:
                classify(node.id, SemanticTokenKind.Variable);
                break;
            case SyntaxKind.FunctionParameter:
                classify(node.id, SemanticTokenKind.Parameter);
                break;
            case SyntaxKind.AugmentDecoratorStatement:
                classifyReference(node.targetType, SemanticTokenKind.Type);
                classifyReference(node.target, SemanticTokenKind.Macro);
                break;
            case SyntaxKind.DecoratorExpression:
                classifyReference(node.target, SemanticTokenKind.Macro);
                break;
            case SyntaxKind.CallExpression:
                classifyReference(node.target, SemanticTokenKind.Function);
                break;
            case SyntaxKind.TypeReference:
                classifyReference(node.target);
                break;
            case SyntaxKind.MemberExpression:
                classifyReference(node);
                break;
            case SyntaxKind.ProjectionStatement:
                classifyReference(node.selector);
                classify(node.id, SemanticTokenKind.Variable);
                break;
            case SyntaxKind.Projection:
                classify(node.directionId, SemanticTokenKind.Keyword);
                for (const modifierId of node.modifierIds) {
                    classify(modifierId, SemanticTokenKind.Keyword);
                }
                break;
            case SyntaxKind.ProjectionParameterDeclaration:
                classifyReference(node.id, SemanticTokenKind.Parameter);
                break;
            case SyntaxKind.ProjectionCallExpression:
                classifyReference(node.target, SemanticTokenKind.Function);
                for (const arg of node.arguments) {
                    classifyReference(arg);
                }
                break;
            case SyntaxKind.ProjectionMemberExpression:
                classifyReference(node.id);
                break;
            case SyntaxKind.DocParamTag:
            case SyntaxKind.DocTemplateTag:
                classifyDocTag(node.tagName, SemanticTokenKind.DocCommentTag);
                classifyOverride(node.paramName, SemanticTokenKind.Variable);
                break;
            case SyntaxKind.DocPropTag:
                classifyDocTag(node.tagName, SemanticTokenKind.DocCommentTag);
                classifyOverride(node.propName, SemanticTokenKind.Variable);
                break;
            case SyntaxKind.DocReturnsTag:
                classifyDocTag(node.tagName, SemanticTokenKind.DocCommentTag);
                break;
            case SyntaxKind.DocUnknownTag:
                classifyDocTag(node.tagName, SemanticTokenKind.Macro);
                break;
            case SyntaxKind.TemplateArgument:
                if (node.name)
                    classify(node.name, SemanticTokenKind.TypeParameter);
                break;
        }
        visitChildren(node, classifyNode);
    }
    function classifyDocTag(node, kind) {
        classifyOverride(node, kind);
        const token = tokens.get(node.pos - 1); // Get the `@` token
        if (token) {
            token.kind = kind;
        }
    }
    function classify(node, kind) {
        const token = tokens.get(node.pos);
        if (token && token.kind === undefined) {
            token.kind = kind;
        }
    }
    function classifyOverride(node, kind) {
        const token = tokens.get(node.pos);
        if (token) {
            token.kind = kind;
        }
    }
    function classifyReference(node, kind = SemanticTokenKind.Type) {
        switch (node.kind) {
            case SyntaxKind.MemberExpression:
                classifyIdentifier(node.base, SemanticTokenKind.Namespace);
                classifyIdentifier(node.id, kind);
                break;
            case SyntaxKind.ProjectionMemberExpression:
                classifyReference(node.base, SemanticTokenKind.Namespace);
                classifyIdentifier(node.id, kind);
                break;
            case SyntaxKind.TypeReference:
                classifyIdentifier(node.target, kind);
                break;
            case SyntaxKind.Identifier:
                classify(node, kind);
                break;
        }
    }
    function classifyIdentifier(node, kind) {
        if (node.kind === SyntaxKind.Identifier) {
            classify(node, kind);
        }
    }
}

const serverOptions = {
    noEmit: true,
    designTimeBuild: true,
    parseOptions: {
        comments: true,
        docs: true,
    },
};
/**
 * Time in milliseconds to wait after a file change before recompiling.
 */
const UPDATE_DEBOUNCE_TIME = 200;
const Commands = {
    APPLY_CODE_FIX: "typespec.applyCodeFix",
};

/**
 * Track file updates and recompile the affected files after some debounce time.
 */
class UpdateManger {
    #pendingUpdates = new Map();
    #updateCb;
    constructor(updateCb) {
        this.#updateCb = updateCb;
    }
    scheduleUpdate(document) {
        const existing = this.#pendingUpdates.get(document.uri);
        if (existing === undefined) {
            this.#pendingUpdates.set(document.uri, {
                latest: document,
            });
        }
        else {
            existing.latest = document;
        }
        this.#scheduleBatchUpdate();
    }
    #scheduleBatchUpdate = debounceThrottle(() => {
        this.#pendingUpdates.forEach((update) => {
            void this.#update(update);
        });
        this.#pendingUpdates.clear();
    }, UPDATE_DEBOUNCE_TIME);
    async #update(update) {
        await this.#updateCb(update.latest);
    }
}
/**
 * Debounces a function but also waits at minimum the specified number of milliseconds until
 * the next invocation. This avoids needless calls when a synchronous call (like diagnostics)
 * took too long and the whole timeout of the next call was eaten up already.
 *
 * @param fn The function
 * @param milliseconds Number of milliseconds to debounce/throttle
 */
function debounceThrottle(fn, milliseconds) {
    let timeout;
    let lastInvocation = Date.now() - milliseconds;
    function maybeCall() {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            if (Date.now() - lastInvocation < milliseconds) {
                maybeCall();
                return;
            }
            fn();
            lastInvocation = Date.now();
        }, milliseconds);
    }
    return maybeCall;
}

function createCompileService({ compilerHost, serverHost, fileService, fileSystemCache, log, }) {
    const oldPrograms = new Map();
    const eventListeners = new Map();
    const updated = new UpdateManger((document) => compile$1(document));
    return { compile: compile$1, getScript, on, notifyChange };
    function on(event, listener) {
        eventListeners.set(event, listener);
    }
    function notify(event, ...args) {
        const listener = eventListeners.get(event);
        if (listener) {
            listener(...args);
        }
    }
    function notifyChange(document) {
        updated.scheduleUpdate(document);
    }
    async function compile$1(document) {
        const path = await fileService.getPath(document);
        const mainFile = await getMainFileForDocument(path);
        const config = await getConfig(mainFile);
        log({ level: "debug", message: `config resolved`, detail: config });
        const [optionsFromConfig, _] = resolveOptionsFromConfig(config, { cwd: path });
        const options = {
            ...optionsFromConfig,
            ...serverOptions,
        };
        log({ level: "debug", message: `compiler options resolved`, detail: options });
        if (!fileService.upToDate(document)) {
            return undefined;
        }
        let program;
        try {
            program = await compile(compilerHost, mainFile, options, oldPrograms.get(mainFile));
            oldPrograms.set(mainFile, program);
            if (!fileService.upToDate(document)) {
                return undefined;
            }
            if (mainFile !== path && !program.sourceFiles.has(path)) {
                // If the file that changed wasn't imported by anything from the main
                // file, retry using the file itself as the main file.
                log({
                    level: "debug",
                    message: `target file was not included in compiling, try to compile ${path} as main file directly`,
                });
                program = await compile(compilerHost, path, options, oldPrograms.get(path));
                oldPrograms.set(path, program);
            }
            if (!fileService.upToDate(document)) {
                return undefined;
            }
            const doc = "version" in document ? document : serverHost.getOpenDocumentByURL(document.uri);
            compilerAssert(doc, "Failed to get document.");
            const resolvedPath = await fileService.getPath(doc);
            const script = program.sourceFiles.get(resolvedPath);
            compilerAssert(script, "Failed to get script.");
            const result = { program, document: doc, script };
            notify("compileEnd", result);
            return result;
        }
        catch (err) {
            if (serverHost.throwInternalErrors) {
                throw err;
            }
            serverHost.sendDiagnostics({
                uri: document.uri,
                diagnostics: [
                    {
                        severity: main$3.DiagnosticSeverity.Error,
                        range: main$3.Range.create(0, 0, 0, 0),
                        message: `Internal compiler error!\nFile issue at https://github.com/microsoft/typespec\n\n` +
                            err.stack,
                    },
                ],
            });
            return undefined;
        }
    }
    async function getConfig(mainFile) {
        const entrypointStat = await compilerHost.stat(mainFile);
        const lookupDir = entrypointStat.isDirectory() ? mainFile : getDirectoryPath(mainFile);
        const configPath = await findTypeSpecConfigPath(compilerHost, lookupDir, true);
        if (!configPath) {
            log({
                level: "debug",
                message: `can't find path with config file, try to use default config`,
            });
            return { ...defaultConfig, projectRoot: getDirectoryPath(mainFile) };
        }
        const cached = await fileSystemCache.get(configPath);
        if (cached?.data) {
            return cached.data;
        }
        const config = await loadTypeSpecConfigFile(compilerHost, configPath);
        await fileSystemCache.setData(configPath, config);
        return config;
    }
    async function getScript(document) {
        const file = await compilerHost.readFile(await fileService.getPath(document));
        const cached = compilerHost.parseCache?.get(file);
        if (cached === undefined) {
            const parsed = parse$2(file, { docs: true, comments: true });
            compilerHost.parseCache?.set(file, parsed);
            return parsed;
        }
        else {
            return cached;
        }
    }
    /**
     * Infer the appropriate entry point (a.k.a. "main file") for analyzing a
     * change to the file at the given path. This is necessary because different
     * results can be obtained from compiling the same file with different entry
     * points.
     *
     * Walk directory structure upwards looking for package.json with tspMain or
     * main.tsp file. Stop search when reaching a workspace root. If a root is
     * reached without finding an entry point, use the given path as its own
     * entry point.
     *
     * Untitled documents are always treated as their own entry points as they
     * do not exist in a directory that could pull them in via another entry
     * point.
     */
    async function getMainFileForDocument(path) {
        if (path.startsWith("untitled:")) {
            log({ level: "debug", message: `untitled document treated as its own main file: ${path}` });
            return path;
        }
        let dir = getDirectoryPath(path);
        const options = { allowFileNotFound: true };
        while (true) {
            let mainFile = "main.tsp";
            let pkg;
            const pkgPath = joinPaths(dir, "package.json");
            const cached = await fileSystemCache.get(pkgPath);
            if (cached?.data) {
                pkg = cached.data;
            }
            else {
                [pkg] = await loadFile(compilerHost, pkgPath, JSON.parse, logMainFileSearchDiagnostic, options);
                await fileSystemCache.setData(pkgPath, pkg ?? {});
            }
            const tspMain = resolveTspMain(pkg);
            if (typeof tspMain === "string") {
                log({
                    level: "debug",
                    message: `tspMain resolved from package.json (${pkgPath}) as ${tspMain}`,
                });
                mainFile = tspMain;
            }
            const candidate = joinPaths(dir, mainFile);
            const stat = await doIO(() => compilerHost.stat(candidate), candidate, logMainFileSearchDiagnostic, options);
            if (stat?.isFile()) {
                log({ level: "debug", message: `main file found as ${candidate}` });
                return candidate;
            }
            const parentDir = getDirectoryPath(dir);
            if (parentDir === dir) {
                break;
            }
            log({
                level: "debug",
                message: `main file not found in ${dir}, search in parent directory ${parentDir}`,
            });
            dir = parentDir;
        }
        log({ level: "debug", message: `reached directory root, using ${path} as main file` });
        return path;
        function logMainFileSearchDiagnostic(diagnostic) {
            log({
                level: `error`,
                message: `Unexpected diagnostic while looking for main file of ${path}`,
                detail: formatDiagnostic(diagnostic),
            });
        }
    }
}

/** @internal */
function getSymbolSignature(program, sym) {
    const decl = sym.declarations[0];
    switch (decl?.kind) {
        case SyntaxKind.AliasStatement:
            return fence(`alias ${getAliasSignature(decl)}`);
    }
    const entity = sym.type ?? program.checker.getTypeOrValueForNode(decl);
    return getEntitySignature(sym, entity);
}
function getEntitySignature(sym, entity) {
    if (entity === null) {
        return "(error)";
    }
    if ("valueKind" in entity) {
        return fence(`const ${sym.name}: ${getTypeName(entity.type)}`);
    }
    return getTypeSignature(entity);
}
function getTypeSignature(type) {
    switch (type.kind) {
        case "Scalar":
        case "Enum":
        case "Union":
        case "Interface":
        case "Model":
        case "Namespace":
            return fence(`${type.kind.toLowerCase()} ${getPrintableTypeName(type)}`);
        case "ScalarConstructor":
            return fence(`init ${getTypeSignature(type.scalar)}.${type.name}`);
        case "Decorator":
            return fence(getDecoratorSignature(type));
        case "Function":
            return fence(getFunctionSignature(type));
        case "Operation":
            return fence(getOperationSignature(type));
        case "String":
            // BUG: https://github.com/microsoft/typespec/issues/1350 - should escape string literal values
            return `(string)\n${fence(`"${type.value}"`)}`;
        case "Boolean":
            return `(boolean)\n${fence(type.value ? "true" : "false")}`;
        case "Number":
            return `(number)\n${fence(type.value.toString())}`;
        case "StringTemplate":
            return `(string template)\n${fence(getStringTemplateSignature(type))}`;
        case "StringTemplateSpan":
            return `(string template span)\n${fence(getTypeName(type.type))}`;
        case "Intrinsic":
            return "";
        case "FunctionParameter":
            return `(function parameter)\n${fence(getFunctionParameterSignature(type))}`;
        case "ModelProperty":
            return `(model property)\n${fence(getModelPropertySignature(type))}`;
        case "EnumMember":
            return `(enum member)\n${fence(getEnumMemberSignature(type))}`;
        case "TemplateParameter":
            return `(template parameter)\n${fence(type.node.id.sv)}`;
        case "UnionVariant":
            return `(union variant)\n${fence(getUnionVariantSignature(type))}`;
        case "Tuple":
            return `(tuple)\n[${fence(type.values.map(getTypeSignature).join(", "))}]`;
        case "Projection":
            return "(projection)";
        case "Object":
            return "(object)";
        default:
            compilerAssert(false, "Unexpected type kind");
    }
}
function getDecoratorSignature(type) {
    const ns = getQualifier(type.namespace);
    const name = type.name.slice(1);
    const parameters = [type.target, ...type.parameters].map((x) => getFunctionParameterSignature(x));
    return `dec ${ns}${name}(${parameters.join(", ")})`;
}
function getFunctionSignature(type) {
    const ns = getQualifier(type.namespace);
    const parameters = type.parameters.map((x) => getFunctionParameterSignature(x));
    return `fn ${ns}${printIdentifier(type.name)}(${parameters.join(", ")}): ${getPrintableTypeName(type.returnType)}`;
}
function getOperationSignature(type) {
    const parameters = [...type.parameters.properties.values()].map(getModelPropertySignature);
    return `op ${getTypeName(type)}(${parameters.join(", ")}): ${getPrintableTypeName(type.returnType)}`;
}
function getFunctionParameterSignature(parameter) {
    const rest = parameter.rest ? "..." : "";
    const optional = parameter.optional ? "?" : "";
    return `${rest}${printIdentifier(parameter.name)}${optional}: ${getEntityName(parameter.type)}`;
}
function getStringTemplateSignature(stringTemplate) {
    return ("`" +
        [
            stringTemplate.spans.map((span) => {
                return span.isInterpolated ? "${" + getTypeName(span.type) + "}" : span.type.value;
            }),
        ].join("") +
        "`");
}
function getModelPropertySignature(property) {
    const ns = getQualifier(property.model);
    return `${ns}${printIdentifier(property.name)}: ${getPrintableTypeName(property.type)}`;
}
function getUnionVariantSignature(variant) {
    if (typeof variant.name !== "string") {
        return getPrintableTypeName(variant.type);
    }
    const ns = getQualifier(variant.union);
    return `${ns}${printIdentifier(variant.name)}: ${getPrintableTypeName(variant.type)}`;
}
function getEnumMemberSignature(member) {
    const ns = getQualifier(member.enum);
    const value = typeof member.value === "string" ? `"${member.value}"` : member.value;
    return value === undefined
        ? `${ns}${printIdentifier(member.name)}`
        : `${ns}${printIdentifier(member.name)}: ${value}`;
}
function getAliasSignature(alias) {
    const fullName = getFullyQualifiedSymbolName(alias.symbol);
    const args = alias.templateParameters.map((t) => t.id.sv);
    return args.length === 0 ? fullName : `${fullName}<${args.join(", ")}>`;
}
function getQualifier(parent) {
    if (!parent?.name ||
        typeof parent.name !== "string" ||
        (parent.kind === "Namespace" && isStdNamespace(parent))) {
        return "";
    }
    const parentName = getPrintableTypeName(parent);
    if (!parentName) {
        return "";
    }
    return parentName + ".";
}
function getPrintableTypeName(type) {
    return getTypeName(type, {
        printable: true,
    });
}
function fence(code) {
    return `\`\`\`typespec\n${code}\n\`\`\``;
}

/**
 * Get the detailed documentation for a symbol.
 * @param program The program
 * @internal
 */
function getSymbolDetails(program, symbol, options = {
    includeSignature: true,
    includeParameterTags: true,
}) {
    const lines = [];
    if (options.includeSignature) {
        lines.push(getSymbolSignature(program, symbol));
    }
    const doc = getSymbolDocumentation(program, symbol);
    if (doc) {
        lines.push(doc);
    }
    for (const node of symbol.declarations) {
        for (const doc of node?.docs ?? []) {
            for (const tag of doc.tags) {
                if (!options.includeParameterTags &&
                    (tag.kind === SyntaxKind.DocParamTag || tag.kind === SyntaxKind.DocTemplateTag)) {
                    continue;
                }
                lines.push(
                //prettier-ignore
                `_@${tag.tagName.sv}_${"paramName" in tag ? ` \`${tag.paramName.sv}\`` : ""} —\n${getDocContent(tag.content)}`);
            }
        }
    }
    return lines.join("\n\n");
}
function getSymbolDocumentation(program, symbol) {
    const docs = [];
    for (const node of symbol.declarations) {
        // Add /** ... */ developer docs
        for (const d of node.docs ?? []) {
            docs.push(getDocContent(d.content));
        }
    }
    // Add @doc(...) API docs
    let type = symbol.type;
    if (!type) {
        const entity = program.checker.getTypeOrValueForNode(symbol.declarations[0]);
        if (entity && isType(entity)) {
            type = entity;
        }
    }
    if (type) {
        const apiDocs = getDocData(program, type);
        // The doc comment is already included above we don't want to duplicate. Only include if it was specificed via `@doc`
        if (apiDocs && apiDocs.source === "decorator") {
            docs.push(apiDocs.value);
        }
    }
    return docs.join("\n\n");
}
/** @internal */
function getParameterDocumentation(program, type) {
    const map = new Map();
    for (const d of type?.node?.docs ?? []) {
        for (const tag of d.tags) {
            if (tag.kind === SyntaxKind.DocParamTag) {
                map.set(tag.paramName.sv, getDocContent(tag.content));
            }
        }
    }
    return map;
}
/** @internal */
function getTemplateParameterDocumentation(node) {
    const map = new Map();
    for (const d of node?.docs ?? []) {
        for (const tag of d.tags) {
            if (tag.kind === SyntaxKind.DocTemplateTag) {
                map.set(tag.paramName.sv, getDocContent(tag.content));
            }
        }
    }
    return map;
}
function getDocContent(content) {
    const docs = [];
    for (const node of content) {
        compilerAssert(node.kind === SyntaxKind.DocText, "No other doc content node kinds exist yet. Update this code appropriately when more are added.");
        docs.push(node.text);
    }
    return docs.join("");
}

async function resolveCompletion(context, posDetail) {
    let node = posDetail.node;
    if (!node) {
        if (posDetail.triviaStartPosition === 0 ||
            !addCompletionByLookingBackward(posDetail, context)) {
            addKeywordCompletion("root", context.completions);
        }
    }
    else {
        // look back first to see whether we can get some completion from the previous statement, e.g. `model Foo |`
        if (!addCompletionByLookingBackward(posDetail, context)) {
            if (posDetail.inTrivia) {
                // If we're not immediately after an identifier character, then advance
                // the position past any trivia. This is done because a zero-width
                // inserted missing identifier that the user is now trying to complete
                // starts after the trivia following the cursor.
                node = posDetail.getPositionDetailAfterTrivia().node;
            }
            await AddCompletionNonTrivia(node, context, posDetail);
        }
        else {
            if (!posDetail.inTrivia) {
                await AddCompletionNonTrivia(node, context, posDetail);
            }
        }
    }
    return context.completions;
}
function addCompletionByLookingBackward(posDetail, context) {
    if (posDetail.triviaStartPosition === 0) {
        return false;
    }
    const preDetail = posDetail.getPositionDetailBeforeTrivia();
    if (!preDetail.node) {
        return false;
    }
    const node = getFirstAncestor(preDetail.node, (n) => n.kind === SyntaxKind.ModelStatement ||
        n.kind === SyntaxKind.ScalarStatement ||
        n.kind === SyntaxKind.OperationStatement ||
        n.kind === SyntaxKind.InterfaceStatement ||
        n.kind === SyntaxKind.TemplateParameterDeclaration, true /*includeSelf*/);
    return node !== undefined && addCompletionByLookingBackwardNode(node, posDetail, context);
}
function addCompletionByLookingBackwardNode(preNode, posDetail, context) {
    const getIdentifierEndPos = (n) => {
        // n.pos === n.end, it means it's a missing identifier, just return -1;
        return n.pos === n.end ? -1 : n.end;
    };
    const map = {
        [SyntaxKind.ModelStatement]: "modelHeader",
        [SyntaxKind.ScalarStatement]: "scalarHeader",
        [SyntaxKind.OperationStatement]: "operationHeader",
        [SyntaxKind.InterfaceStatement]: "interfaceHeader",
    };
    switch (preNode?.kind) {
        case SyntaxKind.ModelStatement:
        case SyntaxKind.ScalarStatement:
        case SyntaxKind.OperationStatement:
        case SyntaxKind.InterfaceStatement:
            const idEndPos = preNode.templateParametersRange.end >= 0
                ? preNode.templateParametersRange.end
                : getIdentifierEndPos(preNode.id);
            if (posDetail.triviaStartPosition === idEndPos) {
                const key = map[preNode.kind];
                if (!key) {
                    compilerAssert(false, "KeywordArea missing in keyarea map.");
                }
                addKeywordCompletion(key, context.completions);
                return true;
            }
            break;
        case SyntaxKind.TemplateParameterDeclaration:
            if (posDetail.triviaStartPosition === getIdentifierEndPos(preNode.id)) {
                addKeywordCompletion("templateParameter", context.completions);
                return true;
            }
            else if (preNode.parent?.templateParametersRange.end === posDetail.triviaStartPosition) {
                return addCompletionByLookingBackwardNode(preNode.parent, posDetail, context);
            }
            break;
    }
    return false;
}
async function AddCompletionNonTrivia(node, context, posDetail, lookBackward = true) {
    if (node === undefined ||
        node.kind === SyntaxKind.InvalidStatement ||
        (node.kind === SyntaxKind.Identifier &&
            (node.parent?.kind === SyntaxKind.TypeSpecScript ||
                node.parent?.kind === SyntaxKind.NamespaceStatement))) {
        addKeywordCompletion("root", context.completions);
    }
    else {
        switch (node.kind) {
            case SyntaxKind.NamespaceStatement:
                addKeywordCompletion("namespace", context.completions);
                break;
            case SyntaxKind.ScalarStatement:
                if (positionInRange(posDetail.position, node.bodyRange)) {
                    addKeywordCompletion("scalarBody", context.completions);
                }
                break;
            case SyntaxKind.Identifier:
                addDirectiveCompletion(context, node);
                addIdentifierCompletion(context, node);
                break;
            case SyntaxKind.StringLiteral:
                if (node.parent && node.parent.kind === SyntaxKind.ImportStatement) {
                    await addImportCompletion(context, node);
                }
                break;
            case SyntaxKind.ModelStatement:
            case SyntaxKind.ObjectLiteral:
            case SyntaxKind.ModelExpression:
                addModelCompletion(context, posDetail);
                break;
        }
    }
}
const keywords = [
    // Root only
    ["import", { root: true }],
    // Root and namespace
    ["using", { root: true, namespace: true }],
    ["model", { root: true, namespace: true }],
    ["scalar", { root: true, namespace: true }],
    ["namespace", { root: true, namespace: true }],
    ["interface", { root: true, namespace: true }],
    ["union", { root: true, namespace: true }],
    ["enum", { root: true, namespace: true }],
    ["alias", { root: true, namespace: true }],
    ["op", { root: true, namespace: true }],
    ["dec", { root: true, namespace: true }],
    ["fn", { root: true, namespace: true }],
    ["const", { root: true, namespace: true }],
    // On model `model Foo <keyword> ...`
    [
        "extends",
        { modelHeader: true, scalarHeader: true, templateParameter: true, interfaceHeader: true },
    ],
    ["is", { modelHeader: true, operationHeader: true }],
    // On identifier
    ["true", { identifier: true }],
    ["false", { identifier: true }],
    ["unknown", { identifier: true }],
    ["void", { identifier: true }],
    ["never", { identifier: true }],
    // Modifiers
    ["extern", { root: true, namespace: true }],
    // Scalars
    ["init", { scalarBody: true }],
];
function addKeywordCompletion(area, completions) {
    const filteredKeywords = keywords.filter(([_, x]) => area in x);
    for (const [keyword] of filteredKeywords) {
        completions.items.push({
            label: keyword,
            kind: main$3.CompletionItemKind.Keyword,
        });
    }
}
async function loadPackageJson(host, path) {
    const [libPackageJson] = await loadFile(host, path, JSON.parse, () => { });
    return libPackageJson;
}
/** Check if the folder given has a package.json which has a tspMain. */
async function isTspLibraryPackage(host, dir) {
    const libPackageJson = await loadPackageJson(host, resolvePath(dir, "package.json"));
    return resolveTspMain(libPackageJson) !== undefined;
}
async function addLibraryImportCompletion({ program, file, completions }, node) {
    const documentPath = file.file.path;
    const projectRoot = await findProjectRoot(program.host.stat, documentPath);
    if (projectRoot !== undefined) {
        const packagejson = await loadPackageJson(program.host, resolvePath(projectRoot, "package.json"));
        let dependencies = [];
        if (packagejson.dependencies !== undefined) {
            dependencies = dependencies.concat(Object.keys(packagejson.dependencies));
        }
        if (packagejson.peerDependencies !== undefined) {
            dependencies = dependencies.concat(Object.keys(packagejson.peerDependencies));
        }
        for (const dependency of dependencies) {
            const dependencyDir = resolvePath(projectRoot, "node_modules", dependency);
            if (await isTspLibraryPackage(program.host, dependencyDir)) {
                const range = {
                    start: file.file.getLineAndCharacterOfPosition(node.pos + 1),
                    end: file.file.getLineAndCharacterOfPosition(node.end - 1),
                };
                completions.items.push({
                    textEdit: main$3.TextEdit.replace(range, dependency),
                    label: dependency,
                    kind: main$3.CompletionItemKind.Module,
                });
            }
        }
    }
}
async function addImportCompletion(context, node) {
    if (node.value.startsWith("./") || node.value.startsWith("../")) {
        await addRelativePathCompletion(context, node);
    }
    else if (!node.value.startsWith(".")) {
        await addLibraryImportCompletion(context, node);
    }
}
async function tryListItemInDir(host, path) {
    try {
        return await host.readDir(path);
    }
    catch (e) {
        if (e.code === "ENOENT") {
            return [];
        }
        throw e;
    }
}
async function addRelativePathCompletion({ program, completions, file }, node) {
    const documentPath = file.file.path;
    const documentFile = getBaseFileName(documentPath);
    const documentDir = getDirectoryPath(documentPath);
    const currentRelativePath = hasTrailingDirectorySeparator(node.value)
        ? node.value
        : getDirectoryPath(node.value);
    const currentAbsolutePath = resolvePath(documentDir, currentRelativePath);
    const files = (await tryListItemInDir(program.host, currentAbsolutePath)).filter((x) => x !== documentFile && x !== "node_modules");
    const lastSlash = node.value.lastIndexOf("/");
    const offset = lastSlash === -1 ? 0 : lastSlash + 1;
    const range = {
        start: file.file.getLineAndCharacterOfPosition(node.pos + 1 + offset),
        end: file.file.getLineAndCharacterOfPosition(node.end - 1),
    };
    for (const file of files) {
        const extension = getAnyExtensionFromPath(file);
        switch (extension) {
            case ".tsp":
            case ".js":
            case ".mjs":
                completions.items.push({
                    label: file,
                    kind: main$3.CompletionItemKind.File,
                    textEdit: main$3.TextEdit.replace(range, file),
                });
                break;
            case "":
                completions.items.push({
                    label: file,
                    kind: main$3.CompletionItemKind.Folder,
                    textEdit: main$3.TextEdit.replace(range, file),
                });
                break;
        }
    }
}
function addModelCompletion(context, posDetail) {
    const node = posDetail.node;
    if (!node ||
        (node.kind !== SyntaxKind.ModelStatement &&
            node.kind !== SyntaxKind.ModelExpression &&
            node.kind !== SyntaxKind.ObjectLiteral)) {
        return;
    }
    if (posDetail.position === node.bodyRange.end) {
        // skip the scenario like `{ ... }|`
        return;
    }
    else {
        // create a fake identifier node to further resolve the completions for the model/object
        // it's a little tricky but can help to keep things clean and simple while the cons. is limited
        // TODO: consider adding support in resolveCompletions for non-identifier-node directly when we find more scenario and worth the cost
        const fakeProp = {
            kind: node.kind === SyntaxKind.ObjectLiteral
                ? SyntaxKind.ObjectLiteralProperty
                : SyntaxKind.ModelProperty,
            flags: 0 /* NodeFlags.None */,
            parent: node,
        };
        const fakeId = {
            kind: SyntaxKind.Identifier,
            sv: "",
            flags: 0 /* NodeFlags.None */,
            parent: fakeProp,
        };
        addIdentifierCompletion(context, fakeId);
    }
}
/**
 * Add completion options for an identifier.
 */
function addIdentifierCompletion({ program, completions }, node) {
    const result = program.checker.resolveCompletions(node);
    if (result.size === 0) {
        return;
    }
    for (const [key, { sym, label, suffix }] of result) {
        let kind;
        let deprecated = false;
        const type = sym.type ?? program.checker.getTypeForNode(sym.declarations[0]);
        if (sym.flags & (131072 /* SymbolFlags.Function */ | 16384 /* SymbolFlags.Decorator */)) {
            kind = main$3.CompletionItemKind.Function;
        }
        else if (sym.flags & 4096 /* SymbolFlags.Namespace */ &&
            sym.declarations[0].kind !== SyntaxKind.NamespaceStatement) {
            kind = main$3.CompletionItemKind.Module;
        }
        else if (sym.declarations[0]?.kind === SyntaxKind.AliasStatement) {
            kind = main$3.CompletionItemKind.Variable;
            deprecated = getDeprecationDetails(program, sym.declarations[0]) !== undefined;
        }
        else {
            kind = getCompletionItemKind(program, type);
            deprecated = getDeprecationDetails(program, type) !== undefined;
        }
        const documentation = getSymbolDetails(program, sym);
        const item = {
            label: label ?? key,
            documentation: documentation
                ? {
                    kind: main$3.MarkupKind.Markdown,
                    value: documentation,
                }
                : undefined,
            kind,
            insertText: printIdentifier(key) + (suffix ?? ""),
        };
        if (deprecated) {
            // hide these deprecated items to discourage the usage
            // not using CompletionItemTag.Deprecated because the strike-through is a little confusing
            // and also it's not supported in vs extension
            continue;
        }
        completions.items.push(item);
    }
    if (node.parent?.kind === SyntaxKind.TypeReference) {
        addKeywordCompletion("identifier", completions);
    }
}
const directiveNames = ["suppress", "deprecated"];
function addDirectiveCompletion({ completions }, node) {
    if (!(node.parent?.kind === SyntaxKind.DirectiveExpression && node.parent.target === node)) {
        return;
    }
    for (const directive of directiveNames) {
        completions.items.push({
            label: directive,
            kind: main$3.CompletionItemKind.Keyword,
        });
    }
}
function getCompletionItemKind(program, target) {
    switch (target.node?.kind) {
        case SyntaxKind.EnumStatement:
        case SyntaxKind.UnionStatement:
            return main$3.CompletionItemKind.Enum;
        case SyntaxKind.EnumMember:
        case SyntaxKind.UnionVariant:
            return main$3.CompletionItemKind.EnumMember;
        case SyntaxKind.AliasStatement:
            return main$3.CompletionItemKind.Variable;
        case SyntaxKind.ModelStatement:
            return main$3.CompletionItemKind.Class;
        case SyntaxKind.ScalarStatement:
            return main$3.CompletionItemKind.Unit;
        case SyntaxKind.ModelProperty:
            return main$3.CompletionItemKind.Field;
        case SyntaxKind.OperationStatement:
            return main$3.CompletionItemKind.Method;
        case SyntaxKind.NamespaceStatement:
            return main$3.CompletionItemKind.Module;
        default:
            return main$3.CompletionItemKind.Struct;
    }
}

function createFileService({ serverHost }) {
    const compilerHost = serverHost.compilerHost;
    // Remember original URL when we convert it to a local path so that we can
    // get it back. We can't convert it back because things like URL-encoding
    // could give us back an equivalent but non-identical URL but the original
    // URL is used as a key into the opened documents and so we must reproduce
    // it exactly.
    const pathToURLMap = new Map();
    return {
        upToDate,
        fileURLToRealPath,
        getPath,
        getURL,
        getOpenDocument,
    };
    /**
     * Determine if the given document is the latest version.
     *
     * A document can become out-of-date if a change comes in during an async
     * operation.
     */
    function upToDate(document) {
        if (!("version" in document)) {
            return true;
        }
        return document.version === serverHost.getOpenDocumentByURL(document.uri)?.version;
    }
    async function fileURLToRealPath(url) {
        return getNormalizedRealPath(compilerHost, compilerHost.fileURLToPath(url));
    }
    async function getPath(document) {
        if (isUntitled(document.uri)) {
            return document.uri;
        }
        const path = await fileURLToRealPath(document.uri);
        pathToURLMap.set(path, document.uri);
        return path;
    }
    function getURL(path) {
        if (isUntitled(path)) {
            return path;
        }
        return pathToURLMap.get(path) ?? compilerHost.pathToFileURL(path);
    }
    function getOpenDocument(path) {
        const url = getURL(path);
        return url ? serverHost.getOpenDocumentByURL(url) : undefined;
    }
}
function isUntitled(pathOrUrl) {
    return pathOrUrl.startsWith("untitled:");
}

function createFileSystemCache({ fileService, log, }) {
    const cache = new Map();
    let changes = [];
    return {
        async get(path) {
            for (const change of changes) {
                const path = await fileService.fileURLToRealPath(change.uri);
                log({
                    level: "trace",
                    message: `FileSystemCache entry with key '${path}' removed`,
                });
                cache.delete(path);
            }
            changes = [];
            const r = cache.get(path);
            if (!r) {
                let callstack;
                try {
                    const target = {};
                    // some browser doesn't support Error.captureStackTrace (i.e. Firefox)
                    if (typeof Error.captureStackTrace === "function") {
                        Error.captureStackTrace(target);
                        callstack = target.stack.substring("Error\n".length);
                    }
                }
                catch {
                    // just ignore the error, we don't want tracing error to impact normal functionality
                }
                log({ level: "trace", message: `FileSystemCache miss for ${path}`, detail: callstack });
            }
            return r;
        },
        set(path, entry) {
            cache.set(path, entry);
        },
        async setData(path, data) {
            const entry = await this.get(path);
            if (entry) {
                entry.data = data;
            }
        },
        notify(changes) {
            changes.push(...changes);
        },
    };
}

function getSymbolStructure(ast) {
    const file = ast.file;
    const fileNamespace = findFileNamespace(ast);
    if (fileNamespace === undefined) {
        return getForStatements(ast.statements);
    }
    const fileNamespaceSymbol = getForNamespace(fileNamespace);
    fileNamespaceSymbol.children = getForStatements(ast.statements.filter((x) => x !== fileNamespace));
    return [fileNamespaceSymbol];
    function findFileNamespace(ast) {
        const firstNamespace = ast.statements.find((x) => x.kind === SyntaxKind.NamespaceStatement);
        if (firstNamespace === undefined) {
            return undefined;
        }
        let current = firstNamespace;
        while (current.statements !== undefined &&
            !isArray(current.statements) &&
            current.statements?.kind === SyntaxKind.NamespaceStatement) {
            current = current.statements;
        }
        return current.statements === undefined ? firstNamespace : undefined;
    }
    function getDocumentSymbolsForNode(node) {
        switch (node.kind) {
            case SyntaxKind.NamespaceStatement:
                return getForNamespace(node);
            case SyntaxKind.ModelStatement:
                return getForModel(node);
            case SyntaxKind.ModelProperty:
                return createDocumentSymbol(node, getName(node.id), main$3.SymbolKind.Property);
            case SyntaxKind.ModelSpreadProperty:
                return getForModelSpread(node);
            case SyntaxKind.UnionStatement:
                return getForUnion(node);
            case SyntaxKind.UnionVariant:
                return node.id === undefined
                    ? undefined
                    : createDocumentSymbol(node, getName(node.id), main$3.SymbolKind.EnumMember);
            case SyntaxKind.EnumStatement:
                return getForEnum(node);
            case SyntaxKind.EnumMember:
                return createDocumentSymbol(node, getName(node.id), main$3.SymbolKind.EnumMember);
            case SyntaxKind.EnumSpreadMember:
                return getForEnumSpread(node);
            case SyntaxKind.InterfaceStatement:
                return getForInterface(node);
            case SyntaxKind.OperationStatement:
                return createDocumentSymbol(node, node.id.sv, main$3.SymbolKind.Function);
            case SyntaxKind.AliasStatement:
                return createDocumentSymbol(node, node.id.sv, main$3.SymbolKind.Variable);
            default:
                return undefined;
        }
    }
    function getForStatements(statements) {
        return statements.map(getDocumentSymbolsForNode).filter(isDefined);
    }
    function getForNamespace(namespace) {
        const names = [namespace.id.sv];
        let current = namespace;
        while (current.statements !== undefined &&
            !isArray(current.statements) &&
            current.statements?.kind === SyntaxKind.NamespaceStatement) {
            current = current.statements;
            names.push(current.id.sv);
        }
        const statementSymbols = current.statements ? getForStatements(current.statements) : [];
        return createDocumentSymbol(namespace, names.join("."), main$3.SymbolKind.Namespace, statementSymbols);
    }
    function createDocumentSymbol(node, name, kind, symbols) {
        const start = file.getLineAndCharacterOfPosition(node.pos);
        const end = file.getLineAndCharacterOfPosition(node.end);
        const range = main$3.Range.create(start, end);
        return main$3.DocumentSymbol.create(name, undefined, kind, range, range, symbols);
    }
    function getName(id) {
        return id.kind === SyntaxKind.Identifier ? id.sv : id.value;
    }
    function getForModel(node) {
        const properties = [...node.properties.values()]
            .map(getDocumentSymbolsForNode)
            .filter(isDefined);
        return createDocumentSymbol(node, node.id.sv, main$3.SymbolKind.Struct, properties);
    }
    function getForModelSpread(node) {
        const target = node.target.target;
        if (target.kind === SyntaxKind.Identifier) {
            return createDocumentSymbol(node, target.sv, main$3.SymbolKind.Property);
        }
        return getDocumentSymbolsForNode(target);
    }
    function getForEnum(node) {
        const members = [...node.members.values()]
            .map(getDocumentSymbolsForNode)
            .filter(isDefined);
        return createDocumentSymbol(node, node.id.sv, main$3.SymbolKind.Enum, members);
    }
    function getForEnumSpread(node) {
        const target = node.target.target;
        if (target.kind === SyntaxKind.Identifier) {
            return createDocumentSymbol(node, target.sv, main$3.SymbolKind.EnumMember);
        }
        return getDocumentSymbolsForNode(target);
    }
    function getForInterface(node) {
        const operations = [...node.operations.values()]
            .map(getDocumentSymbolsForNode)
            .filter(isDefined);
        return createDocumentSymbol(node, node.id.sv, main$3.SymbolKind.Interface, operations);
    }
    function getForUnion(node) {
        const variants = [...node.options.values()]
            .map(getDocumentSymbolsForNode)
            .filter(isDefined);
        return createDocumentSymbol(node, node.id.sv, main$3.SymbolKind.Enum, variants);
    }
}

function createServer(host) {
    const fileService = createFileService({ serverHost: host });
    // Cache all file I/O. Only open documents are sent over the LSP pipe. When
    // the compiler reads a file that isn't open, we use this cache to avoid
    // hitting the disk. Entries are invalidated when LSP client notifies us of
    // a file change.
    const fileSystemCache = createFileSystemCache({
        fileService,
        log,
    });
    const compilerHost = createCompilerHost();
    const compileService = createCompileService({
        fileService,
        fileSystemCache,
        compilerHost,
        serverHost: host,
        log,
    });
    const currentDiagnosticIndex = new Map();
    let diagnosticIdCounter = 0;
    compileService.on("compileEnd", (result) => reportDiagnostics(result));
    let workspaceFolders = [];
    let isInitialized = false;
    let pendingMessages = [];
    return {
        get pendingMessages() {
            return pendingMessages;
        },
        get workspaceFolders() {
            return workspaceFolders;
        },
        compile: compileService.compile,
        initialize,
        initialized,
        workspaceFoldersChanged,
        watchedFilesChanged,
        formatDocument,
        gotoDefinition,
        documentClosed,
        complete,
        findReferences,
        findDocumentHighlight,
        prepareRename,
        rename,
        getSemanticTokens: getSemanticTokensForDocument,
        buildSemanticTokens,
        checkChange,
        getFoldingRanges,
        getHover,
        getSignatureHelp,
        getDocumentSymbols,
        getCodeActions,
        executeCommand,
        log,
    };
    async function initialize(params) {
        const tokenLegend = {
            tokenTypes: Object.keys(SemanticTokenKind)
                .filter((x) => Number.isNaN(Number(x)))
                .map((x) => x.slice(0, 1).toLocaleLowerCase() + x.slice(1)),
            tokenModifiers: [],
        };
        const capabilities = {
            textDocumentSync: node.TextDocumentSyncKind.Incremental,
            definitionProvider: true,
            foldingRangeProvider: true,
            hoverProvider: true,
            documentSymbolProvider: true,
            documentHighlightProvider: true,
            completionProvider: {
                resolveProvider: false,
                triggerCharacters: [".", "@", "/"],
            },
            semanticTokensProvider: {
                full: true,
                legend: tokenLegend,
            },
            referencesProvider: true,
            renameProvider: {
                prepareProvider: true,
            },
            documentFormattingProvider: true,
            signatureHelpProvider: {
                triggerCharacters: ["(", ",", "<"],
                retriggerCharacters: [")"],
            },
            codeActionProvider: {
                codeActionKinds: ["quickfix"],
            },
            executeCommandProvider: {
                commands: [Commands.APPLY_CODE_FIX],
            },
        };
        if (params.capabilities.workspace?.workspaceFolders) {
            for (const w of params.workspaceFolders ?? []) {
                workspaceFolders.push({
                    ...w,
                    path: ensureTrailingDirectorySeparator(await fileService.fileURLToRealPath(w.uri)),
                });
            }
            capabilities.workspace = {
                workspaceFolders: {
                    supported: true,
                    changeNotifications: true,
                },
            };
            // eslint-disable-next-line deprecation/deprecation
        }
        else if (params.rootUri) {
            workspaceFolders = [
                {
                    name: "<root>",
                    // eslint-disable-next-line deprecation/deprecation
                    uri: params.rootUri,
                    path: ensureTrailingDirectorySeparator(
                    // eslint-disable-next-line deprecation/deprecation
                    await fileService.fileURLToRealPath(params.rootUri)),
                },
            ];
            // eslint-disable-next-line deprecation/deprecation
        }
        else if (params.rootPath) {
            workspaceFolders = [
                {
                    name: "<root>",
                    // eslint-disable-next-line deprecation/deprecation
                    uri: compilerHost.pathToFileURL(params.rootPath),
                    path: ensureTrailingDirectorySeparator(
                    // eslint-disable-next-line deprecation/deprecation
                    await getNormalizedRealPath(compilerHost, params.rootPath)),
                },
            ];
        }
        log({ level: "info", message: `Workspace Folders`, detail: workspaceFolders });
        return { capabilities };
    }
    function initialized(params) {
        isInitialized = true;
        log({ level: "info", message: "Initialization complete." });
    }
    async function workspaceFoldersChanged(e) {
        log({ level: "info", message: "Workspace Folders Changed", detail: e });
        const map = new Map(workspaceFolders.map((f) => [f.uri, f]));
        for (const folder of e.removed) {
            map.delete(folder.uri);
        }
        for (const folder of e.added) {
            map.set(folder.uri, {
                ...folder,
                path: ensureTrailingDirectorySeparator(await fileService.fileURLToRealPath(folder.uri)),
            });
        }
        workspaceFolders = Array.from(map.values());
        log({ level: "info", message: `Workspace Folders`, detail: workspaceFolders });
    }
    function watchedFilesChanged(params) {
        fileSystemCache.notify(params.changes);
    }
    async function getFoldingRanges(params) {
        const ast = await compileService.getScript(params.textDocument);
        if (!ast) {
            return [];
        }
        const file = ast.file;
        const ranges = [];
        let rangeStartSingleLines = -1;
        for (let i = 0; i < ast.comments.length; i++) {
            const comment = ast.comments[i];
            if (comment.kind === SyntaxKind.LineComment &&
                i + 1 < ast.comments.length &&
                ast.comments[i + 1].kind === SyntaxKind.LineComment &&
                ast.comments[i + 1].pos === skipWhiteSpace(file.text, comment.end)) {
                if (rangeStartSingleLines === -1) {
                    rangeStartSingleLines = comment.pos;
                }
            }
            else if (rangeStartSingleLines !== -1) {
                addRange(rangeStartSingleLines, comment.end);
                rangeStartSingleLines = -1;
            }
            else {
                addRange(comment.pos, comment.end);
            }
        }
        visitChildren(ast, addRangesForNode);
        function addRangesForNode(node) {
            if (node.kind === SyntaxKind.Doc) {
                return; // fold doc comments as regular comments
            }
            let nodeStart = node.pos;
            if ("decorators" in node && node.decorators.length > 0) {
                const decoratorEnd = node.decorators[node.decorators.length - 1].end;
                addRange(nodeStart, decoratorEnd);
                nodeStart = skipTrivia(file.text, decoratorEnd);
            }
            addRange(nodeStart, node.end);
            visitChildren(node, addRangesForNode);
        }
        return ranges;
        function addRange(startPos, endPos) {
            const start = file.getLineAndCharacterOfPosition(startPos);
            const end = file.getLineAndCharacterOfPosition(endPos);
            if (start.line !== end.line) {
                ranges.push({
                    startLine: start.line,
                    startCharacter: start.character,
                    endLine: end.line,
                    endCharacter: end.character,
                });
            }
        }
    }
    async function getDocumentSymbols(params) {
        const ast = await compileService.getScript(params.textDocument);
        if (!ast) {
            return [];
        }
        return getSymbolStructure(ast);
    }
    async function findDocumentHighlight(params) {
        const result = await compileService.compile(params.textDocument);
        if (result === undefined) {
            return [];
        }
        const { program, document, script } = result;
        const identifiers = findReferenceIdentifiers(program, script, document.offsetAt(params.position), [script]);
        return identifiers.map((identifier) => ({
            range: getRange(identifier, script.file),
            kind: node.DocumentHighlightKind.Read,
        }));
    }
    async function checkChange(change) {
        compileService.notifyChange(change.document);
    }
    async function reportDiagnostics({ program, document }) {
        currentDiagnosticIndex.clear();
        // Group diagnostics by file.
        //
        // Initialize diagnostics for all source files in program to empty array
        // as we must send an empty array when a file has no diagnostics or else
        // stale diagnostics from a previous run will stick around in the IDE.
        //
        const diagnosticMap = new Map();
        diagnosticMap.set(document, []);
        for (const each of program.sourceFiles.values()) {
            const document = each.file?.document;
            if (document) {
                diagnosticMap.set(document, []);
            }
        }
        for (const each of program.diagnostics) {
            let diagDocument;
            const location = getSourceLocation(each.target, { locateId: true });
            if (location?.file) {
                diagDocument = location.file.document;
            }
            else {
                // https://github.com/microsoft/language-server-protocol/issues/256
                //
                // LSP does not currently allow sending a diagnostic with no location so
                // we report diagnostics with no location on the document that changed to
                // trigger.
                diagDocument = document;
                log({ level: "debug", message: `Diagnostic with no location: ${each.message}` });
            }
            if (!diagDocument || !fileService.upToDate(diagDocument)) {
                continue;
            }
            const start = diagDocument.positionAt(location?.pos ?? 0);
            const end = diagDocument.positionAt(location?.end ?? 0);
            const range = node.Range.create(start, end);
            const severity = convertSeverity(each.severity);
            const diagnostic = node.Diagnostic.create(range, each.message, severity, each.code, "TypeSpec");
            if (each.code === "deprecated") {
                diagnostic.tags = [node.DiagnosticTag.Deprecated];
            }
            diagnostic.data = { id: diagnosticIdCounter++ };
            const diagnostics = diagnosticMap.get(diagDocument);
            compilerAssert(diagnostics, "Diagnostic reported against a source file that was not added to the program.");
            diagnostics.push(diagnostic);
            currentDiagnosticIndex.set(diagnostic.data.id, each);
        }
        for (const [document, diagnostics] of diagnosticMap) {
            sendDiagnostics(document, diagnostics);
        }
    }
    async function getHover(params) {
        const result = await compileService.compile(params.textDocument);
        if (result === undefined) {
            return { contents: [] };
        }
        const { program, document, script } = result;
        const id = getNodeAtPosition(script, document.offsetAt(params.position));
        const sym = id?.kind === SyntaxKind.Identifier ? program.checker.resolveIdentifier(id) : undefined;
        const markdown = {
            kind: node.MarkupKind.Markdown,
            value: sym ? getSymbolDetails(program, sym) : "",
        };
        return {
            contents: markdown,
        };
    }
    async function getSignatureHelp(params) {
        const result = await compileService.compile(params.textDocument);
        if (result === undefined) {
            return undefined;
        }
        const { script, document, program } = result;
        const data = getSignatureHelpNodeAtPosition(script, document.offsetAt(params.position));
        if (data === undefined) {
            return undefined;
        }
        const { node, argumentIndex } = data;
        switch (node.kind) {
            case SyntaxKind.TypeReference:
                return getSignatureHelpForTemplate(program, node, argumentIndex);
            case SyntaxKind.DecoratorExpression:
            case SyntaxKind.AugmentDecoratorStatement:
                return getSignatureHelpForDecorator(program, node, argumentIndex);
            default:
                compilerAssert(false, "Unreachable");
        }
    }
    function getSignatureHelpForTemplate(program, node$1, argumentIndex) {
        const sym = program.checker.resolveIdentifier(node$1.target.kind === SyntaxKind.MemberExpression ? node$1.target.id : node$1.target);
        const templateDeclNode = sym?.declarations[0];
        if (!templateDeclNode ||
            !("templateParameters" in templateDeclNode) ||
            templateDeclNode.templateParameters.length === 0) {
            return undefined;
        }
        const parameterDocs = getTemplateParameterDocumentation(templateDeclNode);
        const parameters = templateDeclNode.templateParameters.map((x) => {
            const info = { label: x.id.sv };
            const doc = parameterDocs.get(x.id.sv);
            if (doc) {
                info.documentation = { kind: node.MarkupKind.Markdown, value: doc };
            }
            return info;
        });
        const help = {
            signatures: [
                {
                    label: `${sym.name}<${parameters.map((x) => x.label).join(", ")}>`,
                    parameters,
                    activeParameter: Math.min(parameters.length - 1, argumentIndex),
                },
            ],
            activeSignature: 0,
            activeParameter: 0,
        };
        const doc = getSymbolDetails(program, sym, {
            includeSignature: false,
            includeParameterTags: false,
        });
        if (doc) {
            help.signatures[0].documentation = { kind: node.MarkupKind.Markdown, value: doc };
        }
        return help;
    }
    function getSignatureHelpForDecorator(program, node$1, argumentIndex) {
        const sym = program.checker.resolveIdentifier(node$1.target.kind === SyntaxKind.MemberExpression ? node$1.target.id : node$1.target);
        if (!sym) {
            return undefined;
        }
        const decoratorDeclNode = sym.declarations.find((x) => x.kind === SyntaxKind.DecoratorDeclarationStatement);
        if (decoratorDeclNode === undefined) {
            return undefined;
        }
        const type = program.checker.getTypeForNode(decoratorDeclNode);
        compilerAssert(type.kind === "Decorator", "Expected type to be a decorator.");
        const parameterDocs = getParameterDocumentation(program, type);
        let labelPrefix = "";
        const parameters = [];
        if (node$1.kind === SyntaxKind.AugmentDecoratorStatement) {
            const targetType = decoratorDeclNode.target.type
                ? program.checker.getTypeForNode(decoratorDeclNode.target.type)
                : undefined;
            parameters.push({
                label: `${decoratorDeclNode.target.id.sv}: ${targetType ? getTypeName(targetType) : "unknown"}`,
            });
            labelPrefix = "@";
        }
        parameters.push(...type.parameters.map((x) => {
            const info = {
                // prettier-ignore
                label: `${x.rest ? "..." : ""}${x.name}${x.optional ? "?" : ""}: ${getEntityName(x.type)}`,
            };
            const doc = parameterDocs.get(x.name);
            if (doc) {
                info.documentation = { kind: node.MarkupKind.Markdown, value: doc };
            }
            return info;
        }));
        const help = {
            signatures: [
                {
                    label: `${labelPrefix}${type.name}(${parameters.map((x) => x.label).join(", ")})`,
                    parameters,
                    activeParameter: Math.min(parameters.length - 1, argumentIndex),
                },
            ],
            activeSignature: 0,
            activeParameter: 0,
        };
        const doc = getSymbolDetails(program, sym, {
            includeSignature: false,
            includeParameterTags: false,
        });
        if (doc) {
            help.signatures[0].documentation = { kind: node.MarkupKind.Markdown, value: doc };
        }
        return help;
    }
    async function formatDocument(params) {
        const document = host.getOpenDocumentByURL(params.textDocument.uri);
        if (document === undefined) {
            return [];
        }
        const formattedText = await formatTypeSpec(document.getText(), {
            tabWidth: params.options.tabSize,
            useTabs: !params.options.insertSpaces,
        });
        return [minimalEdit(document, formattedText)];
    }
    function minimalEdit(document, string1) {
        const string0 = document.getText();
        // length of common prefix
        let i = 0;
        while (i < string0.length && i < string1.length && string0[i] === string1[i]) {
            ++i;
        }
        // length of common suffix
        let j = 0;
        while (i + j < string0.length &&
            i + j < string1.length &&
            string0[string0.length - j - 1] === string1[string1.length - j - 1]) {
            ++j;
        }
        const newText = string1.substring(i, string1.length - j);
        const pos0 = document.positionAt(i);
        const pos1 = document.positionAt(string0.length - j);
        return node.TextEdit.replace(node.Range.create(pos0, pos1), newText);
    }
    async function gotoDefinition(params) {
        const result = await compileService.compile(params.textDocument);
        if (result === undefined) {
            return [];
        }
        const node = getNodeAtPosition(result.script, result.document.offsetAt(params.position));
        switch (node?.kind) {
            case SyntaxKind.Identifier:
                const sym = result.program.checker.resolveIdentifier(node);
                return getLocations(sym?.declarations);
            case SyntaxKind.StringLiteral:
                if (node.parent?.kind === SyntaxKind.ImportStatement) {
                    return [await getImportLocation(node.value, result.script)];
                }
                else {
                    return [];
                }
        }
        return [];
    }
    async function getImportLocation(importPath, currentFile) {
        const host = {
            realpath: compilerHost.realpath,
            readFile: async (path) => {
                const file = await compilerHost.readFile(path);
                return file.text;
            },
            stat: compilerHost.stat,
        };
        const resolved = await resolveModule(host, importPath, {
            baseDir: getDirectoryPath(currentFile.file.path),
            resolveMain(pkg) {
                // this lets us follow node resolve semantics more-or-less exactly
                // but using tspMain instead of main.
                return resolveTspMain(pkg) ?? pkg.main;
            },
        });
        return {
            uri: fileService.getURL(resolved.type === "file" ? resolved.path : resolved.mainFile),
            range: node.Range.create(0, 0, 0, 0),
        };
    }
    async function complete(params) {
        const completions = {
            isIncomplete: false,
            items: [],
        };
        const result = await compileService.compile(params.textDocument);
        if (result) {
            const { script, document, program } = result;
            const posDetail = getCompletionNodeAtPosition(script, document.offsetAt(params.position));
            return await resolveCompletion({
                program,
                file: script,
                completions,
                params,
            }, posDetail);
        }
        return completions;
    }
    async function findReferences(params) {
        const result = await compileService.compile(params.textDocument);
        if (result === undefined) {
            return [];
        }
        const identifiers = findReferenceIdentifiers(result.program, result.script, result.document.offsetAt(params.position));
        return getLocations(identifiers);
    }
    async function prepareRename(params) {
        const result = await compileService.compile(params.textDocument);
        if (result === undefined) {
            return undefined;
        }
        const id = getNodeAtPosition(result.script, result.document.offsetAt(params.position));
        return id?.kind === SyntaxKind.Identifier ? getLocation(id)?.range : undefined;
    }
    async function rename(params) {
        const changes = {};
        const result = await compileService.compile(params.textDocument);
        if (result) {
            const identifiers = findReferenceIdentifiers(result.program, result.script, result.document.offsetAt(params.position));
            for (const id of identifiers) {
                const location = getLocation(id);
                if (!location) {
                    continue;
                }
                const change = node.TextEdit.replace(location.range, params.newName);
                if (location.uri in changes) {
                    changes[location.uri].push(change);
                }
                else {
                    changes[location.uri] = [change];
                }
            }
        }
        return { changes };
    }
    function findReferenceIdentifiers(program, file, pos, searchFiles = program.sourceFiles.values()) {
        const id = getNodeAtPosition(file, pos);
        if (id?.kind !== SyntaxKind.Identifier) {
            return [];
        }
        const sym = program.checker.resolveIdentifier(id);
        if (!sym) {
            return [id];
        }
        const references = [];
        for (const searchFile of searchFiles) {
            visitChildren(searchFile, function visit(node) {
                if (node.kind === SyntaxKind.Identifier) {
                    const s = program.checker.resolveIdentifier(node);
                    if (s === sym || (sym.type && s?.type === sym.type)) {
                        references.push(node);
                    }
                }
                visitChildren(node, visit);
            });
        }
        return references;
    }
    async function getSemanticTokensForDocument(params) {
        const ast = await compileService.getScript(params.textDocument);
        if (!ast) {
            return [];
        }
        return getSemanticTokens(ast);
    }
    async function buildSemanticTokens(params) {
        const builder = new node.SemanticTokensBuilder();
        const tokens = await getSemanticTokensForDocument(params);
        const file = await compilerHost.readFile(await fileService.getPath(params.textDocument));
        const starts = file.getLineStarts();
        for (const token of tokens) {
            const start = file.getLineAndCharacterOfPosition(token.pos);
            const end = file.getLineAndCharacterOfPosition(token.end);
            for (let pos = token.pos, line = start.line; line <= end.line; line++) {
                const endPos = line === end.line ? token.end : starts[line + 1];
                const character = line === start.line ? start.character : 0;
                builder.push(line, character, endPos - pos, token.kind, 0);
                pos = endPos;
            }
        }
        return builder.build();
    }
    async function getCodeActions(params) {
        const actions = [];
        for (const vsDiag of params.context.diagnostics) {
            const tspDiag = currentDiagnosticIndex.get(vsDiag.data?.id);
            if (tspDiag === undefined || tspDiag.codefixes === undefined)
                continue;
            for (const fix of tspDiag.codefixes ?? []) {
                const codeAction = {
                    ...node.CodeAction.create(fix.label, {
                        title: fix.label,
                        command: Commands.APPLY_CODE_FIX,
                        arguments: [params.textDocument.uri, vsDiag.data?.id, fix.id],
                    }, node.CodeActionKind.QuickFix),
                    diagnostics: [vsDiag],
                };
                actions.push(codeAction);
            }
        }
        return actions;
    }
    async function executeCommand(params) {
        if (params.command === Commands.APPLY_CODE_FIX) {
            const [documentUri, diagId, fixId] = params.arguments ?? [];
            if (documentUri && diagId && fixId) {
                const diag = currentDiagnosticIndex.get(diagId);
                const codeFix = diag?.codefixes?.find((x) => x.id === fixId);
                if (codeFix) {
                    const edits = await resolveCodeFix(codeFix);
                    const vsEdits = convertCodeFixEdits(edits);
                    await host.applyEdit({ changes: { [documentUri]: vsEdits } });
                }
            }
        }
    }
    function convertCodeFixEdits(edits) {
        return edits.map(convertCodeFixEdit);
    }
    function convertCodeFixEdit(edit) {
        switch (edit.kind) {
            case "insert-text":
                return node.TextEdit.insert(edit.file.getLineAndCharacterOfPosition(edit.pos), edit.text);
            case "replace-text":
                return node.TextEdit.replace(getRange(edit, edit.file), edit.text);
        }
    }
    function documentClosed(change) {
        // clear diagnostics on file close
        sendDiagnostics(change.document, []);
    }
    function getLocations(targets) {
        return targets?.map(getLocation).filter((x) => !!x) ?? [];
    }
    function getLocation(target) {
        const location = getSourceLocation(target);
        if (location.isSynthetic) {
            return undefined;
        }
        return {
            uri: fileService.getURL(location.file.path),
            range: getRange(location, location.file),
        };
    }
    function getRange(location, file) {
        const start = file.getLineAndCharacterOfPosition(location.pos);
        const end = file.getLineAndCharacterOfPosition(location.end);
        return node.Range.create(start, end);
    }
    function convertSeverity(severity) {
        switch (severity) {
            case "warning":
                return node.DiagnosticSeverity.Warning;
            case "error":
                return node.DiagnosticSeverity.Error;
        }
    }
    function log(log) {
        if (!isInitialized) {
            pendingMessages.push(log);
            return;
        }
        for (const pending of pendingMessages) {
            host.log(pending);
        }
        pendingMessages = [];
        host.log(log);
    }
    function sendDiagnostics(document, diagnostics) {
        host.sendDiagnostics({
            uri: document.uri,
            version: document.version,
            diagnostics,
        });
    }
    function createCompilerHost() {
        const base = host.compilerHost;
        return {
            ...base,
            parseCache: new WeakMap(),
            readFile,
            stat,
            getSourceFileKind,
        };
        async function readFile(path) {
            const document = fileService.getOpenDocument(path);
            const cached = await fileSystemCache.get(path);
            // Try cache
            if (cached && (!document || document.version === cached.version)) {
                if (cached.type === "error") {
                    throw cached.error;
                }
                return cached.file;
            }
            // Try open document, although this is cheap, the instance still needs
            // to be cached so that the compiler can reuse parse and bind results.
            if (document) {
                const file = {
                    document,
                    ...createSourceFile(document.getText(), path),
                };
                fileSystemCache.set(path, { type: "file", file, version: document.version });
                return file;
            }
            // Hit the disk and cache
            try {
                const file = await base.readFile(path);
                fileSystemCache.set(path, { type: "file", file });
                return file;
            }
            catch (error) {
                fileSystemCache.set(path, { type: "error", error });
                throw error;
            }
        }
        async function stat(path) {
            // if we have an open document for the path or a cache entry, then we know
            // it's a file and not a directory and needn't hit the disk.
            if (fileService.getOpenDocument(path) || (await fileSystemCache.get(path))?.type === "file") {
                return {
                    isFile() {
                        return true;
                    },
                    isDirectory() {
                        return false;
                    },
                };
            }
            return await base.stat(path);
        }
        function getSourceFileKind(path) {
            const document = fileService.getOpenDocument(path);
            if (document?.languageId === "typespec") {
                return "typespec";
            }
            return getSourceFileKindFromExt(path);
        }
    }
}
function getSignatureHelpNodeAtPosition(script, position) {
    // Move back over any trailing trivia. Otherwise, if there is no
    // closing paren/angle bracket, we can find ourselves outside the desired
    // node altogether in cases like `@dec(test, |`.
    position = getPositionBeforeTrivia(script, position);
    const node = getNodeAtPosition(script, position, (n) => {
        switch (n.kind) {
            case SyntaxKind.DecoratorExpression:
            case SyntaxKind.AugmentDecoratorStatement:
            case SyntaxKind.TypeReference:
                // Do not consider node if positioned before the argument list.
                // This is the standard behavior for signature help and further
                // deals with nesting such as `Outer<Inner|> where we do not want
                // we want help with the `Outer` arguments, not the `Inner` ones.
                if (position <= n.target.end) {
                    return false;
                }
                // Likewise, no signature help at the end of argument list unless the
                // it has no closing paren/angle bracket.
                if (position === n.end) {
                    const endChar = script.file.text.charCodeAt(position - 1);
                    const closeChar = n.kind === SyntaxKind.TypeReference ? 62 /* CharCode.GreaterThan */ : 41 /* CharCode.CloseParen */;
                    if (endChar === closeChar) {
                        return false;
                    }
                }
                return true;
            default:
                return false;
        }
    });
    if (!node) {
        return undefined;
    }
    const argumentIndex = getSignatureHelpArgumentIndex(script, node, position);
    if (argumentIndex < 0) {
        return undefined;
    }
    return { node, argumentIndex };
}
function getSignatureHelpArgumentIndex(script, node, position) {
    // Normalize arguments into a single list to avoid special case for
    // augment decorators.
    const args = node.kind === SyntaxKind.AugmentDecoratorStatement
        ? [node.targetType, ...node.arguments]
        : node.arguments;
    // Find the first argument that ends after the position. We don't look at
    // the argument start position since the cursor might be in leading
    // trivia, and we skip trivia to get the effective argument end position
    // since the cursor might be in trailing trivia.
    for (let i = 0; i < args.length; i++) {
        if (position <= skipTrivia(script.file.text, args[i].end)) {
            return i;
        }
    }
    // If we reach here, we must be at the next argument after any that are in
    // the syntax tree. There won't be a missing identifier for this argument
    // in the tree since the parser error recovery will have assumed a
    // trailing delimiter or empty list.
    return args.length;
}
/**
 * Resolve the node that should be auto completed at the given position.
 * It will try to guess what node it could be as during auto complete the ast might not be complete.
 * @internal
 */
function getCompletionNodeAtPosition(script, position, filter = (node) => true) {
    return getNodeAtPositionDetail(script, position, filter);
}

const TypeSpecPrettierPlugin = formatter;
/** @deprecated Use TypeSpecPrettierPlugin */
const CadlPrettierPlugin = TypeSpecPrettierPlugin;

const TypeSpecJSSources = {
"dist/src/lib/intrinsic-decorators.js": f0,
"dist/src/lib/decorators.js": f1,
};
const TypeSpecSources = {
  "package.json": "{\"name\":\"@typespec/compiler\",\"version\":\"0.58.0\",\"description\":\"TypeSpec Compiler Preview\",\"author\":\"Microsoft Corporation\",\"license\":\"MIT\",\"homepage\":\"https://typespec.io\",\"readme\":\"https://github.com/microsoft/typespec/blob/main/README.md\",\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/microsoft/typespec.git\"},\"bugs\":{\"url\":\"https://github.com/microsoft/typespec/issues\"},\"keywords\":[\"typespec\",\"cli\"],\"type\":\"module\",\"main\":\"dist/src/index.js\",\"tspMain\":\"lib/std/main.tsp\",\"exports\":{\".\":{\"types\":\"./dist/src/index.d.ts\",\"default\":\"./dist/src/index.js\"},\"./utils\":{\"types\":\"./dist/src/utils/index.d.ts\",\"default\":\"./dist/src/utils/index.js\"},\"./testing\":{\"types\":\"./dist/src/testing/index.d.ts\",\"default\":\"./dist/src/testing/index.js\"},\"./module-resolver\":{\"types\":\"./dist/src/core/module-resolver.d.ts\",\"default\":\"./dist/src/core/module-resolver.js\"},\"./emitter-framework\":{\"types\":\"./dist/src/emitter-framework/index.d.ts\",\"default\":\"./dist/src/emitter-framework/index.js\"}},\"browser\":{\"./dist/src/core/node-host.js\":\"./dist/src/core/node-host.browser.js\",\"./dist/src/core/logger/console-sink.js\":\"./dist/src/core/logger/console-sink.browser.js\"},\"engines\":{\"node\":\">=18.0.0\"},\"bin\":{\"tsp\":\"cmd/tsp.js\",\"tsp-server\":\"cmd/tsp-server.js\"},\"files\":[\"lib/**/*.tsp\",\"dist/**\",\"templates/**\",\"entrypoints\",\"!dist/test/**\"],\"scripts\":{\"clean\":\"rimraf ./dist ./temp\",\"build:init-templates-index\":\"node --no-warnings --experimental-specifier-resolution=node --loader ts-node/esm ./.scripts/build-init-templates.ts\",\"build\":\"npm run gen-manifest && npm run build:init-templates-index && npm run compile && npm run generate-tmlanguage\",\"compile\":\"tsc -p .\",\"watch\":\"tsc -p . --watch\",\"watch-tmlanguage\":\"node scripts/watch-tmlanguage.js\",\"generate-tmlanguage\":\"node scripts/generate-tmlanguage.js\",\"gen-extern-signature\":\"node --no-warnings --experimental-specifier-resolution=node --loader ts-node/esm ./.scripts/gen-extern-signature.ts\",\"dogfood\":\"node scripts/dogfood.js\",\"test\":\"vitest run\",\"test:ui\":\"vitest --ui\",\"test:watch\":\"vitest -w\",\"test:ci\":\"vitest run --coverage --reporter=junit --reporter=default\",\"test:e2e\":\"vitest run --config ./vitest.config.e2e.ts\",\"gen-manifest\":\"node scripts/generate-manifest.js\",\"regen-nonascii\":\"node scripts/regen-nonascii.js\",\"fuzz\":\"node dist/test/manual/fuzz.js run\",\"lint\":\"eslint . --max-warnings=0\",\"lint:fix\":\"eslint . --fix\"},\"dependencies\":{\"@babel/code-frame\":\"~7.24.7\",\"ajv\":\"~8.16.0\",\"change-case\":\"~5.4.4\",\"globby\":\"~14.0.2\",\"mustache\":\"~4.2.0\",\"picocolors\":\"~1.0.1\",\"prettier\":\"~3.3.2\",\"prompts\":\"~2.4.2\",\"semver\":\"^7.6.2\",\"temporal-polyfill\":\"^0.2.5\",\"vscode-languageserver\":\"~9.0.1\",\"vscode-languageserver-textdocument\":\"~1.0.11\",\"yaml\":\"~2.4.5\",\"yargs\":\"~17.7.2\"},\"devDependencies\":{\"@types/babel__code-frame\":\"~7.0.6\",\"@types/mustache\":\"~4.2.5\",\"@types/node\":\"~18.11.19\",\"@types/prompts\":\"~2.4.9\",\"@types/semver\":\"^7.5.8\",\"@types/yargs\":\"~17.0.32\",\"@typespec/internal-build-utils\":\"workspace:~\",\"@vitest/coverage-v8\":\"^1.6.0\",\"@vitest/ui\":\"^1.6.0\",\"c8\":\"^10.1.2\",\"grammarkdown\":\"~3.3.2\",\"rimraf\":\"~5.0.7\",\"source-map-support\":\"~0.5.21\",\"tmlanguage-generator\":\"workspace:~\",\"ts-node\":\"~10.9.2\",\"typescript\":\"~5.5.3\",\"vitest\":\"^1.6.0\",\"vscode-oniguruma\":\"~2.0.1\",\"vscode-textmate\":\"~9.0.0\"}}",
  "lib/intrinsics.tsp": "import \"../dist/src/lib/intrinsic-decorators.js\";\n\n// This file contains all the intrinsic types of typespec. Everything here will always be loaded\nnamespace TypeSpec;\n\n/**\n * Represent a byte array\n */\nscalar bytes;\n\n/**\n * A numeric type\n */\nscalar numeric;\n\n/**\n * A whole number. This represent any `integer` value possible.\n * It is commonly represented as `BigInteger` in some languages.\n */\nscalar integer extends numeric;\n\n/**\n * A number with decimal value\n */\nscalar float extends numeric;\n\n/**\n * A 64-bit integer. (`-9,223,372,036,854,775,808` to `9,223,372,036,854,775,807`)\n */\nscalar int64 extends integer;\n\n/**\n * A 32-bit integer. (`-2,147,483,648` to `2,147,483,647`)\n */\nscalar int32 extends int64;\n\n/**\n * A 16-bit integer. (`-32,768` to `32,767`)\n */\nscalar int16 extends int32;\n\n/**\n * A 8-bit integer. (`-128` to `127`)\n */\nscalar int8 extends int16;\n\n/**\n * A 64-bit unsigned integer (`0` to `18,446,744,073,709,551,615`)\n */\nscalar uint64 extends integer;\n\n/**\n * A 32-bit unsigned integer (`0` to `4,294,967,295`)\n */\nscalar uint32 extends uint64;\n\n/**\n * A 16-bit unsigned integer (`0` to `65,535`)\n */\nscalar uint16 extends uint32;\n\n/**\n * A 8-bit unsigned integer (`0` to `255`)\n */\nscalar uint8 extends uint16;\n\n/**\n * An integer that can be serialized to JSON (`−9007199254740991 (−(2^53 − 1))` to `9007199254740991 (2^53 − 1)` )\n */\nscalar safeint extends int64;\n\n/**\n * A 32 bit floating point number. (`±1.5 x 10^−45` to `±3.4 x 10^38`)\n */\nscalar float64 extends float;\n\n/**\n * A 32 bit floating point number. (`±5.0 × 10^−324` to `±1.7 × 10^308`)\n */\nscalar float32 extends float64;\n\n/**\n * A decimal number with any length and precision. This represent any `decimal` value possible.\n * It is commonly represented as `BigDecimal` in some languages.\n */\nscalar decimal extends numeric;\n\n/**\n * A 128-bit decimal number.\n */\nscalar decimal128 extends decimal;\n\n/**\n * A sequence of textual characters.\n */\nscalar string;\n\n/**\n * A date on a calendar without a time zone, e.g. \"April 10th\"\n */\nscalar plainDate {\n  /**\n   * Create a plain date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = plainTime.fromISO(\"2024-05-06\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A time on a clock without a time zone, e.g. \"3:00 am\"\n */\nscalar plainTime {\n  /**\n   * Create a plain time from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = plainTime.fromISO(\"12:34\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * An instant in coordinated universal time (UTC)\"\n */\nscalar utcDateTime {\n  /**\n   * Create a date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = utcDateTime.fromISO(\"2024-05-06T12:20-12Z\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A date and time in a particular time zone, e.g. \"April 10th at 3:00am in PST\"\n */\nscalar offsetDateTime {\n  /**\n   * Create a date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = offsetDateTime.fromISO(\"2024-05-06T12:20-12-0700\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A duration/time period. e.g 5s, 10h\n */\nscalar duration {\n  /**\n   * Create a duration from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = duration.fromISO(\"P1Y1D\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * Boolean with `true` and `false` values.\n */\nscalar boolean;\n\n/**\n * @dev Array model type, equivalent to `Element[]`\n * @template Element The type of the array elements\n */\n@indexer(integer, Element)\nmodel Array<Element> {}\n\n/**\n * @dev Model with string properties where all the properties have type `Property`\n * @template Element The type of the properties\n */\n@indexer(string, Element)\nmodel Record<Element> {}\n",
  "lib/std/main.tsp": "// TypeSpec standard library. Everything in here can be omitted by using `--nostdlib` cli flag or `nostdlib` in the config.\nimport \"./types.tsp\";\nimport \"./decorators.tsp\";\nimport \"./reflection.tsp\";\nimport \"./projected-names.tsp\";\n",
  "lib/std/types.tsp": "namespace TypeSpec;\n\n/**\n * Represent a 32-bit unix timestamp datetime with 1s of granularity.\n * It measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970.\n */\n@encode(\"unixTimestamp\", int32)\nscalar unixTimestamp32 extends utcDateTime;\n\n/**\n * Represent a model\n */\n// Deprecated June 2023 sprint\n#deprecated \"object is deprecated. Please use {} for an empty model, `Record<unknown>` for a record with unknown property types, `unknown[]` for an array.\"\nmodel object {}\n\n/**\n * Represent a URL string as described by https://url.spec.whatwg.org/\n */\nscalar url extends string;\n\n/**\n * Represents a collection of optional properties.\n *\n * @template Source An object whose spread properties are all optional.\n */\n@doc(\"The template for adding optional properties.\")\n@withOptionalProperties\nmodel OptionalProperties<Source> {\n  ...Source;\n}\n\n/**\n * Represents a collection of updateable properties.\n *\n * @template Source An object whose spread properties are all updateable.\n */\n@doc(\"The template for adding updateable properties.\")\n@withUpdateableProperties\nmodel UpdateableProperties<Source> {\n  ...Source;\n}\n\n/**\n * Represents a collection of omitted properties.\n *\n * @template Source An object whose properties are spread.\n * @template Keys The property keys to omit.\n */\n@doc(\"The template for omitting properties.\")\n@withoutOmittedProperties(Keys)\nmodel OmitProperties<Source, Keys extends string> {\n  ...Source;\n}\n\n/**\n * Represents a collection of properties with only the specified keys included.\n *\n * @template Source An object whose properties are spread.\n * @template Keys The property keys to include.\n */\n@doc(\"The template for picking properties.\")\n@withPickedProperties(Keys)\nmodel PickProperties<Source, Keys extends string> {\n  ...Source;\n}\n\n/**\n * Represents a collection of properties with default values omitted.\n *\n * @template Source An object whose spread property defaults are all omitted.\n */\n@withoutDefaultValues\nmodel OmitDefaults<Source> {\n  ...Source;\n}\n\n/**\n * Applies a visibility setting to a collection of properties.\n *\n * @template Source An object whose properties are spread.\n * @template Visibility The visibility to apply to all properties.\n */\n@doc(\"The template for setting the default visibility of key properties.\")\n@withDefaultKeyVisibility(Visibility)\nmodel DefaultKeyVisibility<Source, Visibility extends valueof string> {\n  ...Source;\n}\n",
  "lib/std/decorators.tsp": "import \"../../dist/src/lib/decorators.js\";\n\nusing TypeSpec.Reflection;\n\nnamespace TypeSpec;\n\n/**\n * Typically a short, single-line description.\n * @param summary Summary string.\n *\n * @example\n * ```typespec\n * @summary(\"This is a pet\")\n * model Pet {}\n * ```\n */\nextern dec summary(target: unknown, summary: valueof string);\n\n/**\n * Attach a documentation string.\n * @param doc Documentation string\n * @param formatArgs Record with key value pair that can be interpolated in the doc.\n *\n * @example\n * ```typespec\n * @doc(\"Represent a Pet available in the PetStore\")\n * model Pet {}\n * ```\n */\nextern dec doc(target: unknown, doc: valueof string, formatArgs?: {});\n\n/**\n * Attach a documentation string to describe the successful return types of an operation.\n * If an operation returns a union of success and errors it only describes the success. See `@errorsDoc` for error documentation.\n * @param doc Documentation string\n *\n * @example\n * ```typespec\n * @returnsDoc(\"Returns doc\")\n * op get(): Pet | NotFound;\n * ```\n */\nextern dec returnsDoc(target: Operation, doc: valueof string);\n\n/**\n * Attach a documentation string to describe the error return types of an operation.\n * If an operation returns a union of success and errors it only describes the errors. See `@returnsDoc` for success documentation.\n * @param doc Documentation string\n *\n * @example\n * ```typespec\n * @errorsDoc(\"Errors doc\")\n * op get(): Pet | NotFound;\n * ```\n */\nextern dec errorsDoc(target: Operation, doc: valueof string);\n\n/**\n * Mark this type as deprecated.\n *\n * NOTE: This decorator **should not** be used, use the `#deprecated` directive instead.\n *\n * @deprecated Use the `#deprecated` directive instead.\n * @param message Deprecation message.\n *\n * @example\n *\n * Use the `#deprecated` directive instead:\n *\n * ```typespec\n * #deprecated \"Use ActionV2\"\n * op Action<Result>(): Result;\n * ```\n */\n#deprecated \"@deprecated decorator is deprecated. Use the `#deprecated` directive instead.\"\nextern dec deprecated(target: unknown, message: valueof string);\n\n/**\n * Service options.\n */\nmodel ServiceOptions {\n  /**\n   * Title of the service.\n   */\n  title?: string;\n\n  /**\n   * Version of the service.\n   */\n  version?: string;\n}\n\n/**\n * Mark this namespace as describing a service and configure service properties.\n * @param options Optional configuration for the service.\n *\n * @example\n * ```typespec\n * @service\n * namespace PetStore;\n * ```\n *\n * @example Setting service title\n * ```typespec\n * @service({title: \"Pet store\"})\n * namespace PetStore;\n * ```\n *\n * @example Setting service version\n * ```typespec\n * @service({version: \"1.0\"})\n * namespace PetStore;\n * ```\n */\nextern dec service(target: Namespace, options?: ServiceOptions);\n\n/**\n * Specify that this model is an error type. Operations return error types when the operation has failed.\n *\n * @example\n * ```typespec\n * @error\n * model PetStoreError {\n *   code: string;\n *   message: string;\n * }\n * ```\n */\nextern dec error(target: Model);\n\n/**\n * Specify a known data format hint for this string type. For example `uuid`, `uri`, etc.\n * This differs from the `@pattern` decorator which is meant to specify a regular expression while `@format` accepts a known format name.\n * The format names are open ended and are left to emitter to interpret.\n *\n * @param format format name.\n *\n * @example\n * ```typespec\n * @format(\"uuid\")\n * scalar uuid extends string;\n * ```\n */\nextern dec format(target: string | bytes | ModelProperty, format: valueof string);\n\n/**\n * Specify the the pattern this string should respect using simple regular expression syntax.\n * The following syntax is allowed: alternations (`|`), quantifiers (`?`, `*`, `+`, and `{ }`), wildcard (`.`), and grouping parentheses.\n * Advanced features like look-around, capture groups, and references are not supported.\n *\n * This decorator may optionally provide a custom validation _message_. Emitters may choose to use the message to provide\n * context when pattern validation fails. For the sake of consistency, the message should be a phrase that describes in\n * plain language what sort of content the pattern attempts to validate. For example, a complex regular expression that\n * validates a GUID string might have a message like \"Must be a valid GUID.\"\n *\n * @param pattern Regular expression.\n * @param validationMessage Optional validation message that may provide context when validation fails.\n *\n * @example\n * ```typespec\n * @pattern(\"[a-z]+\", \"Must be a string consisting of only lower case letters and of at least one character.\")\n * scalar LowerAlpha extends string;\n * ```\n */\nextern dec pattern(\n  target: string | bytes | ModelProperty,\n  pattern: valueof string,\n  validationMessage?: valueof string\n);\n\n/**\n * Specify the minimum length this string type should be.\n * @param value Minimum length\n *\n * @example\n * ```typespec\n * @minLength(2)\n * scalar Username extends string;\n * ```\n */\nextern dec minLength(target: string | ModelProperty, value: valueof integer);\n\n/**\n * Specify the maximum length this string type should be.\n * @param value Maximum length\n *\n * @example\n * ```typespec\n * @maxLength(20)\n * scalar Username extends string;\n * ```\n */\nextern dec maxLength(target: string | ModelProperty, value: valueof integer);\n\n/**\n * Specify the minimum number of items this array should have.\n * @param value Minimum number\n *\n * @example\n * ```typespec\n * @minItems(1)\n * model Endpoints is string[];\n * ```\n */\nextern dec minItems(target: unknown[] | ModelProperty, value: valueof integer);\n\n/**\n * Specify the maximum number of items this array should have.\n * @param value Maximum number\n *\n * @example\n * ```typespec\n * @maxItems(5)\n * model Endpoints is string[];\n * ```\n */\nextern dec maxItems(target: unknown[] | ModelProperty, value: valueof integer);\n\n/**\n * Specify the minimum value this numeric type should be.\n * @param value Minimum value\n *\n * @example\n * ```typespec\n * @minValue(18)\n * scalar Age is int32;\n * ```\n */\nextern dec minValue(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the maximum value this numeric type should be.\n * @param value Maximum value\n *\n * @example\n * ```typespec\n * @maxValue(200)\n * scalar Age is int32;\n * ```\n */\nextern dec maxValue(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the minimum value this numeric type should be, exclusive of the given\n * value.\n * @param value Minimum value\n *\n * @example\n * ```typespec\n * @minValueExclusive(0)\n * scalar distance is float64;\n * ```\n */\nextern dec minValueExclusive(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the maximum value this numeric type should be, exclusive of the given\n * value.\n * @param value Maximum value\n *\n * @example\n * ```typespec\n * @maxValueExclusive(50)\n * scalar distance is float64;\n * ```\n */\nextern dec maxValueExclusive(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Mark this string as a secret value that should be treated carefully to avoid exposure\n *\n * @example\n * ```typespec\n * @secret\n * scalar Password is string;\n * ```\n */\nextern dec secret(target: string | ModelProperty);\n\n/**\n * Mark this operation as a `list` operation for resource types.\n * @deprecated Use the `listsResource` decorator in `@typespec/rest` instead.\n * @param listedType Optional type of the items in the list.\n */\nextern dec list(target: Operation, listedType?: Model);\n\n/**\n * Attaches a tag to an operation, interface, or namespace. Multiple `@tag` decorators can be specified to attach multiple tags to a TypeSpec element.\n * @param tag Tag value\n */\nextern dec tag(target: Namespace | Interface | Operation, tag: valueof string);\n\n/**\n * Specifies how a templated type should name their instances.\n * @param name name the template instance should take\n * @param formatArgs Model with key value used to interpolate the name\n *\n * @example\n * ```typespec\n * @friendlyName(\"{name}List\", T)\n * model List<Item> {\n *   value: Item[];\n *   nextLink: string;\n * }\n * ```\n */\nextern dec friendlyName(target: unknown, name: valueof string, formatArgs?: unknown);\n\n/**\n * Provide a set of known values to a string type.\n * @param values Known values enum.\n *\n * @example\n * ```typespec\n * @knownValues(KnownErrorCode)\n * scalar ErrorCode extends string;\n *\n * enum KnownErrorCode {\n *   NotFound,\n *   Invalid,\n * }\n * ```\n */\n#deprecated \"This decorator has been deprecated. Use a named union of string literals with a string variant to achieve the same result without a decorator.\"\nextern dec knownValues(target: string | numeric | ModelProperty, values: Enum);\n\n/**\n * Mark a model property as the key to identify instances of that type\n * @param altName Name of the property. If not specified, the decorated property name is used.\n *\n * @example\n * ```typespec\n * model Pet {\n *   @key id: string;\n * }\n * ```\n */\nextern dec key(target: ModelProperty, altName?: valueof string);\n\n/**\n * Specify this operation is an overload of the given operation.\n * @param overloadbase Base operation that should be a union of all overloads\n *\n * @example\n * ```typespec\n * op upload(data: string | bytes, @header contentType: \"text/plain\" | \"application/octet-stream\"): void;\n * @overload(upload)\n * op uploadString(data: string, @header contentType: \"text/plain\" ): void;\n * @overload(upload)\n * op uploadBytes(data: bytes, @header contentType: \"application/octet-stream\"): void;\n * ```\n */\nextern dec overload(target: Operation, overloadbase: Operation);\n\n/**\n * DEPRECATED: Use `@encodedName` instead.\n *\n * Provide an alternative name for this type.\n * @param targetName Projection target\n * @param projectedName Alternative name\n *\n * @example\n * ```typespec\n * model Certificate {\n *   @projectedName(\"json\", \"exp\")\n *   expireAt: int32;\n * }\n * ```\n */\n#deprecated \"Use `@encodedName` instead for changing the name over the wire.\"\nextern dec projectedName(\n  target: unknown,\n  targetName: valueof string,\n  projectedName: valueof string\n);\n\n/**\n * Provide an alternative name for this type when serialized to the given mime type.\n * @param mimeType Mime type this should apply to. The mime type should be a known mime type as described here https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types without any suffix (e.g. `+json`)\n * @param name Alternative name\n *\n * @example\n *\n * ```typespec\n * model Certificate {\n *   @encodedName(\"application/json\", \"exp\")\n *   @encodedName(\"application/xml\", \"expiry\")\n *   expireAt: int32;\n * }\n * ```\n *\n * @example Invalid values\n *\n * ```typespec\n * @encodedName(\"application/merge-patch+json\", \"exp\")\n *              ^ error cannot use subtype\n * ```\n */\nextern dec encodedName(target: unknown, mimeType: valueof string, name: valueof string);\n\n/**\n * Specify the property to be used to discriminate this type.\n * @param propertyName The property name to use for discrimination\n *\n * @example\n *\n * ```typespec\n * @discriminator(\"kind\")\n * union Pet{ cat: Cat, dog: Dog }\n *\n * model Cat {kind: \"cat\", meow: boolean}\n * model Dog {kind: \"dog\", bark: boolean}\n * ```\n *\n * ```typespec\n * @discriminator(\"kind\")\n * model Pet{ kind: string }\n *\n * model Cat extends Pet {kind: \"cat\", meow: boolean}\n * model Dog extends Pet  {kind: \"dog\", bark: boolean}\n * ```\n */\nextern dec discriminator(target: Model | Union, propertyName: valueof string);\n\n/**\n * Known encoding to use on utcDateTime or offsetDateTime\n */\nenum DateTimeKnownEncoding {\n  /**\n   * RFC 3339 standard. https://www.ietf.org/rfc/rfc3339.txt\n   * Encode to string.\n   */\n  rfc3339: \"rfc3339\",\n\n  /**\n   * RFC 7231 standard. https://www.ietf.org/rfc/rfc7231.txt\n   * Encode to string.\n   */\n  rfc7231: \"rfc7231\",\n\n  /**\n   * Encode a datetime to a unix timestamp.\n   * Unix timestamps are represented as an integer number of seconds since the Unix epoch and usually encoded as an int32.\n   */\n  unixTimestamp: \"unixTimestamp\",\n}\n\n/**\n * Known encoding to use on duration\n */\nenum DurationKnownEncoding {\n  /**\n   * ISO8601 duration\n   */\n  ISO8601: \"ISO8601\",\n\n  /**\n   * Encode to integer or float\n   */\n  seconds: \"seconds\",\n}\n\n/**\n * Known encoding to use on bytes\n */\nenum BytesKnownEncoding {\n  /**\n   * Encode to Base64\n   */\n  base64: \"base64\",\n\n  /**\n   * Encode to Base64 Url\n   */\n  base64url: \"base64url\",\n}\n\n/**\n * Specify how to encode the target type.\n * @param encoding Known name of an encoding.\n * @param encodedAs What target type is this being encoded as. Default to string.\n *\n * @example offsetDateTime encoded with rfc7231\n *\n * ```tsp\n * @encode(\"rfc7231\")\n * scalar myDateTime extends offsetDateTime;\n * ```\n *\n * @example utcDateTime encoded with unixTimestamp\n *\n * ```tsp\n * @encode(\"unixTimestamp\", int32)\n * scalar myDateTime extends unixTimestamp;\n * ```\n */\nextern dec encode(\n  target: Scalar | ModelProperty,\n  encoding: string | EnumMember,\n  encodedAs?: Scalar\n);\n\n/** Options for example decorators */\nmodel ExampleOptions {\n  /** The title of the example */\n  title?: string;\n\n  /** Description of the example */\n  description?: string;\n}\n\n/**\n * Provide an example value for a data type.\n *\n * @param example Example value.\n * @param options Optional metadata for the example.\n *\n * @example\n *\n * ```tsp\n * @example(#{name: \"Fluffy\", age: 2})\n * model Pet {\n *  name: string;\n *  age: int32;\n * }\n * ```\n */\nextern dec example(\n  target: Model | Enum | Scalar | Union | ModelProperty | UnionVariant,\n  example: valueof unknown,\n  options?: valueof ExampleOptions\n);\n\n/**\n * Operation example configuration.\n */\nmodel OperationExample {\n  /** Example request body. */\n  parameters?: unknown;\n\n  /** Example response body. */\n  returnType?: unknown;\n}\n\n/**\n * Provide example values for an operation's parameters and corresponding return type.\n *\n * @param example Example value.\n * @param options Optional metadata for the example.\n *\n * @example\n *\n * ```tsp\n * @example(#{parameters: #{name: \"Fluffy\", age: 2}, returnType: #{name: \"Fluffy\", age: 2, id: \"abc\"})\n * op createPet(pet: Pet): Pet;\n * ```\n */\nextern dec opExample(\n  target: Operation,\n  example: valueof OperationExample,\n  options?: valueof ExampleOptions\n);\n/**\n * Indicates that a property is only considered to be present or applicable (\"visible\") with\n * the in the given named contexts (\"visibilities\"). When a property has no visibilities applied\n * to it, it is implicitly visible always.\n *\n * As far as the TypeSpec core library is concerned, visibilities are open-ended and can be arbitrary\n * strings, but  the following visibilities are well-known to standard libraries and should be used\n * with standard emitters that interpret them as follows:\n *\n * - \"read\": output of any operation.\n * - \"create\": input to operations that create an entity..\n * - \"query\": input to operations that read data.\n * - \"update\": input to operations that update data.\n * - \"delete\": input to operations that delete data.\n *\n * See also: [Automatic visibility](https://typespec.io/docs/libraries/http/operations#automatic-visibility)\n *\n * @param visibilities List of visibilities which apply to this property.\n *\n * @example\n *\n * ```typespec\n * model Dog {\n *   // the service will generate an ID, so you don't need to send it.\n *   @visibility(\"read\") id: int32;\n *   // the service will store this secret name, but won't ever return it\n *   @visibility(\"create\", \"update\") secretName: string;\n *   // the regular name is always present\n *   name: string;\n * }\n * ```\n */\nextern dec visibility(target: ModelProperty, ...visibilities: valueof string[]);\n\n/**\n * Removes properties that are not considered to be present or applicable\n * (\"visible\") in the given named contexts (\"visibilities\"). Can be used\n * together with spread to effectively spread only visible properties into\n * a new model.\n *\n * See also: [Automatic visibility](https://typespec.io/docs/libraries/http/operations#automatic-visibility)\n *\n * When using an emitter that applies visibility automatically, it is generally\n * not necessary to use this decorator.\n *\n * @param visibilities List of visibilities which apply to this property.\n *\n * @example\n * ```typespec\n * model Dog {\n *   @visibility(\"read\") id: int32;\n *   @visibility(\"create\", \"update\") secretName: string;\n *   name: string;\n * }\n *\n * // The spread operator will copy all the properties of Dog into DogRead,\n * // and @withVisibility will then remove those that are not visible with\n * // create or update visibility.\n * //\n * // In this case, the id property is removed, and the name and secretName\n * // properties are kept.\n * @withVisibility(\"create\", \"update\")\n * model DogCreateOrUpdate {\n *   ...Dog;\n * }\n *\n * // In this case the id and name properties are kept and the secretName property\n * // is removed.\n * @withVisibility(\"read\")\n * model DogRead {\n *   ...Dog;\n * }\n * ```\n */\nextern dec withVisibility(target: Model, ...visibilities: valueof string[]);\n\n/**\n * Set the visibility of key properties in a model if not already set.\n *\n * @param visibility The desired default visibility value. If a key property already has a `visibility` decorator then the default visibility is not applied.\n */\nextern dec withDefaultKeyVisibility(target: Model, visibility: valueof string);\n\n/**\n * Returns the model with non-updateable properties removed.\n */\nextern dec withUpdateableProperties(target: Model);\n\n/**\n * Returns the model with required properties removed.\n */\nextern dec withOptionalProperties(target: Model);\n\n/**\n * Returns the model with any default values removed.\n */\nextern dec withoutDefaultValues(target: Model);\n\n/**\n * Returns the model with the given properties omitted.\n * @param omit List of properties to omit\n */\nextern dec withoutOmittedProperties(target: Model, omit: string | Union);\n\n/**\n * Returns the model with only the given properties included.\n * @param pick List of properties to include\n */\nextern dec withPickedProperties(target: Model, pick: string | Union);\n\n//---------------------------------------------------------------------------\n// Debugging\n//---------------------------------------------------------------------------\n\n/**\n * A debugging decorator used to inspect a type.\n * @param text Custom text to log\n */\nextern dec inspectType(target: unknown, text: valueof string);\n\n/**\n * A debugging decorator used to inspect a type name.\n * @param text Custom text to log\n */\nextern dec inspectTypeName(target: unknown, text: valueof string);\n\n/**\n * Sets which visibilities apply to parameters for the given operation.\n * @param visibilities List of visibility strings which apply to this operation.\n */\nextern dec parameterVisibility(target: Operation, ...visibilities: valueof string[]);\n\n/**\n * Sets which visibilities apply to the return type for the given operation.\n * @param visibilities List of visibility strings which apply to this operation.\n */\nextern dec returnTypeVisibility(target: Operation, ...visibilities: valueof string[]);\n",
  "lib/std/reflection.tsp": "namespace TypeSpec.Reflection;\n\nmodel Enum {}\nmodel EnumMember {}\nmodel Interface {}\nmodel Model {}\nmodel ModelProperty {}\nmodel Namespace {}\nmodel Operation {}\nmodel Scalar {}\nmodel Union {}\nmodel UnionVariant {}\nmodel StringTemplate {}\n",
  "lib/std/projected-names.tsp": "// Set of projections consuming the @projectedName decorator\n#suppress \"projections-are-experimental\"\nprojection op#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n  }\n}\n\n#suppress \"projections-are-experimental\"\nprojection interface#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n  }\n}\n\n#suppress \"projections-are-experimental\"\nprojection model#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n\n    self::properties::forEach((p) => {\n      if hasProjectedName(p, targetName) {\n        self::renameProperty(p::name, getProjectedName(p, targetName));\n      };\n    });\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n\n    self::projectionBase::properties::forEach((p) => {\n      if hasProjectedName(p, targetName) {\n        self::renameProperty(getProjectedName(p, targetName), p::name);\n      };\n    });\n  }\n}\n\n#suppress \"projections-are-experimental\"\nprojection enum#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n\n    self::members::forEach((p) => {\n      if hasProjectedName(p, targetName) {\n        self::renameMember(p::name, getProjectedName(p, targetName));\n      };\n    });\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n\n    self::projectionBase::members::forEach((p) => {\n      if hasProjectedName(p, targetName) {\n        self::renameMember(getProjectedName(p, targetName), p::name);\n      };\n    });\n  }\n}\n\n#suppress \"projections-are-experimental\"\nprojection union#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n  }\n}\n"
};
const _TypeSpecLibrary_ = {
  jsSourceFiles: TypeSpecJSSources,
  typespecSourceFiles: TypeSpecSources,
};

export { $deprecated, $discriminator, $doc, $encode, $encodedName, $error, $errorsDoc, $example, $format, $friendlyName, $inspectType, $inspectTypeName, $key, $knownValues, $list, $maxItems, $maxLength, $maxValue, $maxValueExclusive, $minItems, $minLength, $minValue, $minValueExclusive, $opExample, $overload, $parameterVisibility, $pattern, $projectedName, $returnTypeVisibility, $returnsDoc, $secret, $service, $summary, $tag, $visibility, $withDefaultKeyVisibility, $withOptionalProperties, $withPickedProperties, $withUpdateableProperties, $withVisibility, $withoutDefaultValues, $withoutOmittedProperties, CadlLanguageConfiguration, CadlPrettierPlugin, DuplicateTracker, EventEmitter, ListenerFlow, MANIFEST, NoTarget, NodeHost, SemanticTokenKind, SyntaxKind, Token, TokenFlags, TypeSpecLanguageConfiguration, TypeSpecPrettierPlugin, _TypeSpecLibrary_, addService, cadlTypeToJson, checkFormatCadl, checkFormatTypeSpec, compile, compilerAssert, createChecker, createDecoratorDefinition, createDiagnosticCollector, createProjectedNameProgram, createRekeyableMap, createScanner, createServer, createSourceFile, defineCodeFix, ensureTrailingDirectorySeparator, finishTypeForProgram, formatDiagnostic, printIdentifier as formatIdentifier, formatTypeSpec, getAllTags, getAnyExtensionFromPath, getBaseFileName, getDeprecated, getDeprecationDetails, getDirectoryPath, getDiscriminatedUnion, getDoc, getDocData, getEncode, getEntityName, getErrorsDoc, getErrorsDocData, getExamples, getFirstAncestor, getFormat, getFriendlyName, getFullyQualifiedSymbolName, getKeyName, getKnownValues, getListOperationType, getLocationContext, getMaxItemsAsNumeric, getMaxLengthAsNumeric, getMaxValueAsNumeric, getMaxValueExclusiveAsNumeric, getMinItemsAsNumeric, getMinLengthAsNumeric, getMinValueAsNumeric, getMinValueExclusiveAsNumeric, getNodeAtPosition, getNodeAtPositionDetail, getOpExamples, getOverloadedOperation, getOverloads, getParameterVisibility, getParentTemplateNode, getPattern, getPatternData, getPositionBeforeTrivia, getProjectedName, getProjectedNames, getProperty, getPropertyType, getReturnTypeVisibility, getReturnsDoc, getReturnsDocData, getService, getSourceFileKindFromExt, getSourceLocation, getSummary, getTags, getTypeName, getVisibility, hasProjectedName, hasTrailingDirectorySeparator, ignoreDiagnostics, interpolatePath, isArrayModelType, isCadlValueTypeOf, isErrorModel, isImportStatement, isIntrinsicType, isKey, isKeyword, isListOperation, isNeverType, isNumericType, isPathAbsolute, isProjectedProgram, isPunctuation, isSecret, isService, isStdNamespace, isStringType, isTemplateDeclaration, isTemplateDeclarationOrInstance, isTemplateInstance, isType, isTypeSpecValueTypeOf, isValue, isVisible, joinPaths, listOperationsIn, listServices, mapEventEmitterToNodeListener, markDeprecated, namespace, navigateProgram, navigateType, navigateTypesInNamespace, normalizePath, parse$2 as parse, parseStandaloneTypeReference, positionInRange, printIdentifier, projectProgram, reportDeprecated, resolveCompilerOptions, resolveEncodedName, resolveLinterDefinition, resolveModule, resolvePath, scopeNavigationToNamespace, serializeValueAsJson, skipTrivia, skipWhiteSpace, typespecTypeToJson, validateDecoratorNotOnType, validateDecoratorParamCount, validateDecoratorParamType, validateDecoratorTarget, validateDecoratorTargetIntrinsic, validateDecoratorUniqueOnNode, visitChildren };
